mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-04 20:49:56 +08:00
chore: remove dead Python modules and helpers (#2253)
* chore: remove dead Python modules and helpers Delete unreferenced P0 code identified by the dead-code audit: - services/llm/registry.py and its test-only coverage - logging/adapters package (LlamaIndex log forwarding) - textbook_struct.chapter_rebuild.detect_frames - load_config_with_main_async and its async file helper - memory.trace.iter_by_ids / latest_ts - TokenTracker.format_summary - WeixinChannel._api_get - ArxivSearchTool.extract_arxiv_id_from_url - FileLibraryStore migration scaffolding (_run_migrations et al.) - eight small dead helpers in services, api/utils, and knowledge - redundant runtime C2CMessage import in the QQ channel * chore: drop the prompt-language shim and a dead storage helper The book agents were the last in-tree users of blocks/_language.py, which only re-exported services.prompt.language. Import the real module and delete the shim. storage._storage_path_from_version_entry had no caller. Verified: ruff F401/F811/F841/F821 on changed files; py_compile. --------- Co-authored-by: Antonio-Faure <209759495+Antonio-Faure@users.noreply.github.com>
This commit is contained in:
@@ -227,41 +227,6 @@ class TokenTracker:
|
||||
"litellm_available": LITELLM_AVAILABLE,
|
||||
}
|
||||
|
||||
def format_summary(self) -> str:
|
||||
s = self.get_summary()
|
||||
lines = [
|
||||
"=" * 70,
|
||||
"📊 [DeepResearch] LLM Usage Summary",
|
||||
"=" * 70,
|
||||
f"Total API Calls: {s['total_calls']}",
|
||||
f"Total Tokens: {s['total_tokens']:,}",
|
||||
f" - Input: {s['total_prompt_tokens']:,}",
|
||||
f" - Output: {s['total_completion_tokens']:,}",
|
||||
f"Total Cost: ${s['total_cost_usd']:.6f} USD",
|
||||
"",
|
||||
"By Agent:",
|
||||
"-" * 70,
|
||||
]
|
||||
for agent, stats in sorted(s["by_agent"].items()):
|
||||
lines += [
|
||||
f" {agent}:",
|
||||
f" Calls: {stats['calls']}",
|
||||
f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})",
|
||||
f" Cost: ${stats['cost_usd']:.6f} USD",
|
||||
"",
|
||||
]
|
||||
lines += ["By Model:", "-" * 70]
|
||||
for model, stats in sorted(s["by_model"].items()):
|
||||
lines += [
|
||||
f" {model}:",
|
||||
f" Calls: {stats['calls']}",
|
||||
f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})",
|
||||
f" Cost: ${stats['cost_usd']:.6f} USD",
|
||||
"",
|
||||
]
|
||||
lines.append("=" * 70)
|
||||
return "\n".join(lines)
|
||||
|
||||
def reset(self):
|
||||
self.usage_records.clear()
|
||||
self.total_prompt_tokens = 0
|
||||
|
||||
@@ -67,7 +67,3 @@ class ProgressBroadcaster:
|
||||
|
||||
if not self._connections[kb_name]:
|
||||
del self._connections[kb_name]
|
||||
|
||||
def get_connection_count(self, kb_name: str) -> int:
|
||||
"""Get connection count for specified knowledge base"""
|
||||
return len(self._connections.get(kb_name, set()))
|
||||
|
||||
@@ -63,11 +63,6 @@ class TaskIDManager:
|
||||
|
||||
return task_id
|
||||
|
||||
def get_task_id(self, task_key: str) -> str | None:
|
||||
"""Get task ID"""
|
||||
with self._lock:
|
||||
return self._task_ids.get(task_key)
|
||||
|
||||
def update_task_status(self, task_id: str, status: str, **kwargs):
|
||||
"""Update task status"""
|
||||
with self._lock:
|
||||
|
||||
@@ -48,7 +48,7 @@ class IdeationAgent(BookAgent):
|
||||
*,
|
||||
ideation_context: IdeationContext,
|
||||
) -> BookProposal:
|
||||
from ..blocks._language import language_directive
|
||||
from deeptutor.services.prompt.language import language_directive
|
||||
|
||||
system_prompt = self.get_prompt("system") or _FALLBACK_SYSTEM
|
||||
system_prompt = system_prompt.rstrip() + language_directive(self.language)
|
||||
|
||||
@@ -679,7 +679,7 @@ class SourceExplorer(BookAgent):
|
||||
if not chunks:
|
||||
return ("", [], [])
|
||||
|
||||
from ..blocks._language import language_directive
|
||||
from deeptutor.services.prompt.language import language_directive
|
||||
|
||||
system_prompt = self.get_prompt("summary_system") or _FALLBACK_SUMMARY_SYSTEM
|
||||
system_prompt = system_prompt.rstrip() + language_directive(self.language)
|
||||
|
||||
@@ -261,7 +261,7 @@ class SpineSynthesizer(BookAgent):
|
||||
stage: str,
|
||||
expected_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from ..blocks._language import language_directive
|
||||
from deeptutor.services.prompt.language import language_directive
|
||||
|
||||
system_prompt = system_prompt.rstrip() + language_directive(self.language)
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
"""Backward-compatible re-export of shared prompt language helpers."""
|
||||
|
||||
from deeptutor.services.prompt.language import (
|
||||
append_language_directive,
|
||||
language_directive,
|
||||
language_label,
|
||||
normalize_language,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"append_language_directive",
|
||||
"language_directive",
|
||||
"language_label",
|
||||
"normalize_language",
|
||||
]
|
||||
@@ -84,11 +84,6 @@ class ProgressTracker:
|
||||
if callback not in self._callbacks:
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def remove_callback(self, callback: Callable[[dict], None]):
|
||||
"""Remove progress callback function"""
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _notify(self, progress: dict):
|
||||
"""Notify progress update (call all callbacks)"""
|
||||
from deeptutor.runtime.mode import is_server
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
"""
|
||||
Log Adapters
|
||||
============
|
||||
|
||||
Adapters for forwarding logs from external libraries to the unified logging system.
|
||||
"""
|
||||
|
||||
from .llamaindex import LlamaIndexLogContext, LlamaIndexLogForwarder
|
||||
|
||||
__all__ = [
|
||||
"LlamaIndexLogContext",
|
||||
"LlamaIndexLogForwarder",
|
||||
]
|
||||
@@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""Scoped LlamaIndex stdlib logging configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
import logging
|
||||
from typing import Any, Iterator
|
||||
|
||||
|
||||
class LlamaIndexLogForwarder(logging.Handler):
|
||||
"""Forward selected LlamaIndex records into a DeepTutor logger."""
|
||||
|
||||
def __init__(self, target: logging.Logger) -> None:
|
||||
super().__init__(logging.DEBUG)
|
||||
self._target = target
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
try:
|
||||
self._target.log(record.levelno, record.getMessage(), exc_info=record.exc_info)
|
||||
except Exception:
|
||||
self.handleError(record)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def LlamaIndexLogContext(
|
||||
logger_name: str | None = None,
|
||||
scene: str = "llamaindex",
|
||||
min_level: str = "INFO",
|
||||
) -> Iterator[None]:
|
||||
"""Forward noisy LlamaIndex records to a named stdlib logger while in scope."""
|
||||
target_name = logger_name or f"deeptutor.{scene}"
|
||||
target = logging.getLogger(target_name)
|
||||
min_level_int = getattr(logging, min_level.upper(), logging.INFO)
|
||||
llama_loggers = [
|
||||
logging.getLogger("llama_index"),
|
||||
logging.getLogger("llama_index.core"),
|
||||
logging.getLogger("llama_index.vector_stores"),
|
||||
logging.getLogger("llama_index.embeddings"),
|
||||
]
|
||||
|
||||
original_states: list[dict[str, Any]] = []
|
||||
forwarders: list[tuple[logging.Logger, LlamaIndexLogForwarder]] = []
|
||||
for llama_logger in llama_loggers:
|
||||
original_states.append(
|
||||
{
|
||||
"logger": llama_logger,
|
||||
"handlers": list(llama_logger.handlers),
|
||||
"level": llama_logger.level,
|
||||
"propagate": llama_logger.propagate,
|
||||
}
|
||||
)
|
||||
for handler in list(llama_logger.handlers):
|
||||
if isinstance(handler, logging.StreamHandler):
|
||||
llama_logger.removeHandler(handler)
|
||||
llama_logger.setLevel(logging.DEBUG)
|
||||
llama_logger.propagate = False
|
||||
forwarder = LlamaIndexLogForwarder(target)
|
||||
forwarder.setLevel(min_level_int)
|
||||
llama_logger.addHandler(forwarder)
|
||||
forwarders.append((llama_logger, forwarder))
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for llama_logger, forwarder in forwarders:
|
||||
if forwarder in llama_logger.handlers:
|
||||
llama_logger.removeHandler(forwarder)
|
||||
forwarder.close()
|
||||
for state in original_states:
|
||||
llama_logger = state["logger"]
|
||||
llama_logger.handlers[:] = state["handlers"]
|
||||
llama_logger.setLevel(state["level"])
|
||||
llama_logger.propagate = state["propagate"]
|
||||
@@ -14,13 +14,12 @@ from deeptutor.partners.config.schema import DeliveryOverrides
|
||||
|
||||
try:
|
||||
import botpy
|
||||
from botpy.message import C2CMessage, GroupMessage
|
||||
from botpy.message import GroupMessage
|
||||
|
||||
QQ_AVAILABLE = True
|
||||
except ImportError:
|
||||
QQ_AVAILABLE = False
|
||||
botpy = None
|
||||
C2CMessage = None
|
||||
GroupMessage = None
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
@@ -282,23 +282,6 @@ class WeixinChannel(BaseChannel):
|
||||
return status_code >= 500
|
||||
return False
|
||||
|
||||
async def _api_get(
|
||||
self,
|
||||
endpoint: str,
|
||||
params: dict | None = None,
|
||||
*,
|
||||
auth: bool = True,
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
) -> dict:
|
||||
assert self._client is not None
|
||||
url = f"{self.config.base_url}/{endpoint}"
|
||||
hdrs = self._make_headers(auth=auth)
|
||||
if extra_headers:
|
||||
hdrs.update(extra_headers)
|
||||
resp = await self._client.get(url, params=params, headers=hdrs)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def _api_post(
|
||||
self,
|
||||
endpoint: str,
|
||||
|
||||
@@ -7,7 +7,6 @@ Unified configuration loading for all DeepTutor modules.
|
||||
Provides YAML configuration loading, path resolution, and language parsing.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -78,11 +77,6 @@ def _inject_runtime_paths(config: dict[str, Any]) -> dict[str, Any]:
|
||||
return normalized
|
||||
|
||||
|
||||
async def _load_yaml_file_async(file_path: Path) -> dict[str, Any]:
|
||||
"""Async version of _load_yaml_file."""
|
||||
return await asyncio.to_thread(_load_yaml_file, file_path)
|
||||
|
||||
|
||||
def resolve_config_path(
|
||||
config_file: str,
|
||||
project_root: Path | None = None,
|
||||
@@ -126,28 +120,6 @@ def load_config_with_main(config_file: str, project_root: Path | None = None) ->
|
||||
return _inject_runtime_paths(_load_yaml_file(config_path))
|
||||
|
||||
|
||||
async def load_config_with_main_async(
|
||||
config_file: str, project_root: Path | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Async version of load_config_with_main for non-blocking file operations.
|
||||
|
||||
Load configuration file, automatically merge with main.yaml common configuration
|
||||
|
||||
Args:
|
||||
config_file: Configuration file name (e.g., "main.yaml")
|
||||
project_root: Project root directory (if None, will try to auto-detect)
|
||||
|
||||
Returns:
|
||||
Merged configuration dictionary
|
||||
"""
|
||||
if project_root is None:
|
||||
project_root = PROJECT_ROOT
|
||||
|
||||
config_path, _ = resolve_config_path(config_file, project_root)
|
||||
return _inject_runtime_paths(await _load_yaml_file_async(config_path))
|
||||
|
||||
|
||||
def get_path_from_config(config: dict[str, Any], path_key: str, default: str = None) -> str:
|
||||
"""
|
||||
Get path from configuration.
|
||||
|
||||
@@ -153,19 +153,6 @@ def _accumulate_streamed_tool_call(
|
||||
return {**buffer, "id": buffer["id"] or f"call_{index}"}
|
||||
|
||||
|
||||
def _coerce_dict(value: Any) -> dict[str, Any] | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, dict):
|
||||
return value if value else None
|
||||
model_dump = getattr(value, "model_dump", None)
|
||||
if callable(model_dump):
|
||||
dumped = model_dump()
|
||||
if isinstance(dumped, dict) and dumped:
|
||||
return dumped
|
||||
return None
|
||||
|
||||
|
||||
def _provider_state_output_items(message: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
state = normalize_provider_response_state(message.get("_provider_response_state"))
|
||||
items = state.get("responses_output_items") if state is not None else None
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
"""
|
||||
LLM Provider Registry
|
||||
====================
|
||||
|
||||
Simple provider registration system for LLM providers.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
# Global registry for LLM providers
|
||||
_provider_registry: dict[str, type] = {}
|
||||
|
||||
|
||||
def register_provider(name: str) -> Callable[[type], type]:
|
||||
"""
|
||||
Decorator to register an LLM provider class.
|
||||
|
||||
Args:
|
||||
name: Name to register the provider under
|
||||
|
||||
Returns:
|
||||
Decorator function
|
||||
"""
|
||||
|
||||
def decorator(cls: type) -> type:
|
||||
if name in _provider_registry:
|
||||
raise ValueError(f"Provider '{name}' is already registered")
|
||||
_provider_registry[name] = cls
|
||||
setattr(cls, "__provider_name__", name)
|
||||
return cls
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_provider_class(name: str) -> type:
|
||||
"""
|
||||
Get a registered provider class by name.
|
||||
|
||||
Args:
|
||||
name: Provider name
|
||||
|
||||
Returns:
|
||||
Provider class
|
||||
|
||||
Raises:
|
||||
KeyError: If provider is not registered
|
||||
"""
|
||||
return _provider_registry[name]
|
||||
|
||||
|
||||
def list_providers() -> list[str]:
|
||||
"""
|
||||
List all registered provider names.
|
||||
|
||||
Returns:
|
||||
List of provider names
|
||||
"""
|
||||
return list(_provider_registry.keys())
|
||||
|
||||
|
||||
def is_provider_registered(name: str) -> bool:
|
||||
"""
|
||||
Check if a provider is registered.
|
||||
|
||||
Args:
|
||||
name: Provider name
|
||||
|
||||
Returns:
|
||||
True if registered, False otherwise
|
||||
"""
|
||||
return name in _provider_registry
|
||||
@@ -17,7 +17,7 @@ from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
from deeptutor.services.memory.ids import new_trace_id
|
||||
from deeptutor.services.memory.paths import SURFACES, Surface, trace_dir, trace_file
|
||||
from deeptutor.services.memory.paths import Surface, trace_dir, trace_file
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -112,42 +112,5 @@ def iter_since(surface: Surface, since: datetime | None = None) -> Iterator[Trac
|
||||
continue
|
||||
|
||||
|
||||
def iter_by_ids(ids: list[str]) -> Iterator[TraceEvent]:
|
||||
"""Resolve trace ids back to their events. Cross-surface walk."""
|
||||
wanted_by_surface: dict[str, set[str]] = {}
|
||||
for tid in ids:
|
||||
if ":" not in tid:
|
||||
continue
|
||||
surface, _ = tid.split(":", 1)
|
||||
if surface in SURFACES:
|
||||
wanted_by_surface.setdefault(surface, set()).add(tid)
|
||||
|
||||
for surface, wanted in wanted_by_surface.items():
|
||||
for event in iter_since(surface): # type: ignore[arg-type]
|
||||
if event.id in wanted:
|
||||
yield event
|
||||
|
||||
|
||||
def count_since(surface: Surface, since: datetime | None = None) -> int:
|
||||
return sum(1 for _ in iter_since(surface, since))
|
||||
|
||||
|
||||
def latest_ts(surface: Surface) -> str | None:
|
||||
"""Most recent event timestamp for ``surface``, or None."""
|
||||
files = sorted(trace_dir(surface).glob("*.jsonl"), reverse=True)
|
||||
for path in files:
|
||||
try:
|
||||
last = ""
|
||||
with path.open("r", encoding="utf-8") as fh:
|
||||
for raw in fh:
|
||||
raw = raw.strip()
|
||||
if raw:
|
||||
last = raw
|
||||
if last:
|
||||
obj = json.loads(last)
|
||||
ts = obj.get("ts")
|
||||
if isinstance(ts, str):
|
||||
return ts
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
@@ -60,22 +60,6 @@ class ResumeCandidate:
|
||||
index: Any
|
||||
|
||||
|
||||
def _storage_path_from_version_entry(entry: dict[str, Any]) -> Path | None:
|
||||
storage_path = entry.get("storage_path")
|
||||
if storage_path:
|
||||
return Path(str(storage_path))
|
||||
|
||||
version_path = entry.get("version_path")
|
||||
if not version_path:
|
||||
return None
|
||||
|
||||
path = Path(str(version_path))
|
||||
layout = str(entry.get("layout") or "")
|
||||
if layout == "nested_legacy":
|
||||
return path / "llamaindex_storage"
|
||||
return path
|
||||
|
||||
|
||||
_EMPTY_VERSION_MARKERS = frozenset({"meta.json", ".building.json"})
|
||||
_EMBEDDING_CHECKPOINT_FILENAME = ".embedding-checkpoint.json"
|
||||
|
||||
|
||||
@@ -729,16 +729,6 @@ def _timed_media_id(value: Any) -> str:
|
||||
return candidate if _TIMED_MEDIA_ID_RE.fullmatch(candidate) else ""
|
||||
|
||||
|
||||
def _timed_media_viewport(value: Any) -> dict[str, float]:
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
try:
|
||||
seconds = float(value.get("time_seconds") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
return {"time_seconds": min(24 * 60 * 60, max(0.0, seconds))}
|
||||
|
||||
|
||||
def _reading_references(value: Any) -> list[dict[str, Any]]:
|
||||
"""Normalize reading units explicitly attached to an ordinary chat turn."""
|
||||
|
||||
|
||||
@@ -10,10 +10,6 @@ from deeptutor.services.config.provider_links import (
|
||||
)
|
||||
|
||||
|
||||
def _identity(ref):
|
||||
return {key: ref[key] for key in ("connection_id", "service", "profile_id") if ref.get(key)}
|
||||
|
||||
|
||||
def _select_remaining(bucket, service):
|
||||
candidates = [
|
||||
p
|
||||
|
||||
@@ -5,7 +5,6 @@ from __future__ import annotations
|
||||
from contextvars import ContextVar
|
||||
|
||||
from deeptutor.services.skill.service import (
|
||||
SkillNotFoundError,
|
||||
SkillService,
|
||||
get_admin_skill_service,
|
||||
render_skills_manifest,
|
||||
@@ -86,10 +85,3 @@ def skill_context() -> tuple[str, str]:
|
||||
def skill_manifest() -> str:
|
||||
"""Both skill parts joined, for callers that need a single text."""
|
||||
return "\n\n".join(part for part in skill_context() if part)
|
||||
|
||||
|
||||
def resolve_runtime_skill(name: str) -> SkillService:
|
||||
service = runtime_skills().get(name)
|
||||
if service is None:
|
||||
raise SkillNotFoundError(name)
|
||||
return service
|
||||
|
||||
@@ -47,34 +47,6 @@ def _sha256(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Schema migrations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SCHEMA_VERSION = 1
|
||||
|
||||
_MIGRATIONS: list[tuple[int, str]] = [
|
||||
# (version, sql)
|
||||
]
|
||||
|
||||
|
||||
def _current_schema_version(conn) -> int:
|
||||
try:
|
||||
row = conn.execute("PRAGMA user_version").fetchone()
|
||||
return row[0] if row else 0
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def _run_migrations(conn) -> None:
|
||||
version = _current_schema_version(conn)
|
||||
for target_version, sql in _MIGRATIONS:
|
||||
if target_version <= version:
|
||||
continue
|
||||
conn.executescript(sql)
|
||||
conn.execute(f"PRAGMA user_version = {_SCHEMA_VERSION}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# FileLibraryStore
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -46,13 +46,6 @@ def _utcnow_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _url_to_filename(url: str, base_path_prefix: str) -> str:
|
||||
"""Stable ``.md`` filename derived from a page URL."""
|
||||
from deeptutor.services.web_source.crawler import _to_filename
|
||||
|
||||
return _to_filename(url, base_path_prefix)
|
||||
|
||||
|
||||
def _record_sync_failure(
|
||||
kb_name: str,
|
||||
source_id: str,
|
||||
|
||||
@@ -13,7 +13,6 @@ page with ``page_idx`` / ``para_blocks``; blocks carry ``type`` / ``bbox`` /
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
import re
|
||||
|
||||
@@ -138,64 +137,6 @@ def assign_page_ranges(chapters: list[Chapter], *, page_count: int) -> list[Chap
|
||||
return chapters
|
||||
|
||||
|
||||
# ── Mid-page section-frame detection (no page-top band constraint) ─────────
|
||||
# Measured heading heights: frame ~22-24, exploration ~27, body lines ~21,
|
||||
# lesson-title wrap residue ~28. Column names go to the blacklist; stray
|
||||
# publisher header lines go to PUBLISHER_NOISE.
|
||||
|
||||
PUBLISHER_NOISE = frozenset({"人民教育出版社", "出版社", "思想政治", "目录", "后记"})
|
||||
|
||||
|
||||
def detect_frames(
|
||||
layout: dict,
|
||||
*,
|
||||
height_range: tuple[float, float] = (20.0, 25.0),
|
||||
extras_range: tuple[float, float] = (26.0, 29.0),
|
||||
first_lesson_page_idx: int | None = None,
|
||||
lesson_titles: Sequence[str] = (),
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""Detect section-frame headings (and chapter-level extras like 综合探究).
|
||||
|
||||
Returns ``(frames, extras)`` — each item ``{title, page_idx, bbox, height}``.
|
||||
Frames are mid-page title blocks in the frame height band; extras
|
||||
(exploration sections / afterword) sit in the slightly taller band.
|
||||
Blacklist + publisher noise + lesson-level regex filtered out.
|
||||
"""
|
||||
frames: list[dict] = []
|
||||
extras: list[dict] = []
|
||||
for page in layout.get("pdf_info", []):
|
||||
for block in page.get("para_blocks", []):
|
||||
if block.get("type") != "title":
|
||||
continue
|
||||
text = block_text(block)
|
||||
if not text or text in COLUMN_BLACKLIST or text in PUBLISHER_NOISE:
|
||||
continue
|
||||
if CHAPTER_RE.match(text):
|
||||
continue # lesson-level handled by the footer path
|
||||
height = block["bbox"][3] - block["bbox"][1]
|
||||
item = {
|
||||
"title": text,
|
||||
"page_idx": page["page_idx"],
|
||||
"bbox": list(block["bbox"]),
|
||||
"height": round(height, 1),
|
||||
}
|
||||
if height_range[0] <= height <= height_range[1]:
|
||||
if len(text) >= 6:
|
||||
# front-matter noise + lesson-title wrap residue
|
||||
# (substring of a lesson title)
|
||||
if (
|
||||
first_lesson_page_idx is not None
|
||||
and item["page_idx"] < first_lesson_page_idx
|
||||
):
|
||||
continue
|
||||
if any(text in lt for lt in lesson_titles):
|
||||
continue
|
||||
frames.append(item)
|
||||
elif extras_range[0] <= height <= extras_range[1] and len(text) >= 3:
|
||||
extras.append(item)
|
||||
return frames, extras
|
||||
|
||||
|
||||
# ── Level-aware boundaries + printed-offset consistency check ──────────────
|
||||
|
||||
UNIT_RE_MAP = {
|
||||
|
||||
@@ -8,7 +8,6 @@ tool usage in chat flows.
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
import logging
|
||||
import re
|
||||
|
||||
import arxiv
|
||||
|
||||
@@ -158,21 +157,6 @@ class ArxivSearchTool:
|
||||
return f"({first_author} et al., {paper['year']})"
|
||||
return f"({first_author}, {paper['year']})"
|
||||
|
||||
def extract_arxiv_id_from_url(self, url: str) -> str | None:
|
||||
"""
|
||||
Extract ArXiv ID from URL
|
||||
|
||||
Args:
|
||||
url: ArXiv URL
|
||||
|
||||
Returns:
|
||||
ArXiv ID or None
|
||||
"""
|
||||
match = re.search(r"arxiv\.org/(?:abs|pdf)/(\d+\.\d+)", url)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return None
|
||||
|
||||
|
||||
# ========== Usage Example ==========
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Tests for provider registry utilities."""
|
||||
|
||||
from deeptutor.services.llm import registry
|
||||
|
||||
|
||||
def test_registry_register_and_lookup() -> None:
|
||||
"""Registering a provider should make it discoverable."""
|
||||
|
||||
class _Provider:
|
||||
pass
|
||||
|
||||
name = "registry_test"
|
||||
registry._provider_registry.pop(name, None)
|
||||
try:
|
||||
decorated = registry.register_provider(name)(_Provider)
|
||||
|
||||
assert registry.is_provider_registered(name) is True
|
||||
assert registry.get_provider_class(name) is decorated
|
||||
assert name in registry.list_providers()
|
||||
finally:
|
||||
registry._provider_registry.pop(name, None)
|
||||
Reference in New Issue
Block a user