Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

style: satisfy repository lint and format gates

Bingxi Zhao (Frank)55e96e429ec9
diff --git a/deeptutor/capabilities/reading/media_notes.py b/deeptutor/capabilities/reading/media_notes.py
index 5b55af621..430f582c3 100644
--- a/deeptutor/capabilities/reading/media_notes.py
+++ b/deeptutor/capabilities/reading/media_notes.py
@@ -40,9 +40,7 @@ def _render_image(name: str, caption: str) -> str:
return f"{name} — {clipped}"
-def render_media_note(
- store: Any, material_id: str, unit: str, locators: Sequence[int]
-) -> str:
+def render_media_note(store: Any, material_id: str, unit: str, locators: Sequence[int]) -> str:
"""List the embedded images that live in the units just read.
The reader pane displays these images next to their unit, and the turn
diff --git a/deeptutor/reading/captions.py b/deeptutor/reading/captions.py
index e0852437a..f24dcdb84 100644
--- a/deeptutor/reading/captions.py
+++ b/deeptutor/reading/captions.py
@@ -65,11 +65,7 @@ async def caption_material_media(
"""
store = store or ReadingStore()
rows = store.media_items(material_id)
- pending = [
- row
- for row in rows
- if force or not str(row.get("caption") or "").strip()
- ]
+ pending = [row for row in rows if force or not str(row.get("caption") or "").strip()]
if limit is not None:
pending = pending[: max(0, int(limit))]
if not pending:
@@ -81,9 +77,7 @@ async def caption_material_media(
logger.warning("Image captioning skipped: LLM client is unavailable (%s)", exc)
return 0
if not client.supports_multimodal_images():
- logger.warning(
- "Image captioning skipped: the configured LLM does not accept image input."
- )
+ logger.warning("Image captioning skipped: the configured LLM does not accept image input.")
return 0
concurrency, timeout_seconds = image_description_limits()
@@ -113,9 +107,7 @@ async def caption_material_media(
timeout=timeout_seconds,
)
except asyncio.TimeoutError:
- logger.warning(
- "Image captioning timed out after %ss: %s", timeout_seconds, name
- )
+ logger.warning("Image captioning timed out after %ss: %s", timeout_seconds, name)
return None
except Exception as exc: # noqa: BLE001 - one bad image must not sink the rest
logger.warning("Image captioning failed for %s: %s", name, exc)
@@ -126,9 +118,7 @@ async def caption_material_media(
return None
return name, caption
- results = await asyncio.gather(
- *(_caption_one(row) for row in pending), return_exceptions=True
- )
+ results = await asyncio.gather(*(_caption_one(row) for row in pending), return_exceptions=True)
captions: dict[str, str] = {}
for result in results:
if isinstance(result, BaseException):
diff --git a/deeptutor/reading/refresh.py b/deeptutor/reading/refresh.py
index 2150740b3..1450c6a06 100644
--- a/deeptutor/reading/refresh.py
+++ b/deeptutor/reading/refresh.py
@@ -87,9 +87,7 @@ def _refresh_document(store: ReadingStore, material_id: str) -> Any:
return refresh(material_id)
-async def _caption_material_media(
- store: ReadingStore, material_id: str, *, force: bool
-) -> int:
+async def _caption_material_media(store: ReadingStore, material_id: str, *, force: bool) -> int:
"""Caption one material's media, importing the captions module lazily.
Deferred so ``--dry-run`` keeps working before ``captions.py`` lands.
@@ -100,9 +98,7 @@ async def _caption_material_media(
raise ReadingError(
"captioning is unavailable: deeptutor.reading.captions is not importable"
) from exc
- return int(
- await caption_material_media(material_id, store=store, force=force, limit=None)
- )
+ return int(await caption_material_media(material_id, store=store, force=force, limit=None))
async def refresh_materials(
diff --git a/deeptutor/services/voice/__init__.py b/deeptutor/services/voice/__init__.py
index c7ac7bc10..d071e5dc1 100644
--- a/deeptutor/services/voice/__init__.py
+++ b/deeptutor/services/voice/__init__.py
@@ -53,9 +53,7 @@ async def synthesize_speech(
config.response_format = response_format
speak_math = _math_speak_from_settings() if math_speak is None else math_speak
prepared = (
- strip_markdown_for_speech(
- text, max_chars=config.max_input_chars, math_speak=speak_math
- )
+ strip_markdown_for_speech(text, max_chars=config.max_input_chars, math_speak=speak_math)
if strip_markdown
else text.strip()
)
diff --git a/deeptutor/services/voice/base.py b/deeptutor/services/voice/base.py
index 7c22eae8f..ba3590f93 100644
--- a/deeptutor/services/voice/base.py
+++ b/deeptutor/services/voice/base.py
@@ -152,9 +152,7 @@ _WHITESPACE = re.compile(r"[ \t]+")
_BLANK_LINES = re.compile(r"\n{3,}")
-def strip_markdown_for_speech(
- text: str, *, max_chars: int = 0, math_speak: bool = True
-) -> str:
+def strip_markdown_for_speech(text: str, *, max_chars: int = 0, math_speak: bool = True) -> str:
"""Reduce Markdown to plain prose suitable for TTS.
Drops code blocks and tables outright (they read terribly), unwraps links
diff --git a/deeptutor/services/voice/speech_text.py b/deeptutor/services/voice/speech_text.py
index baa061d85..de247fe0a 100644
--- a/deeptutor/services/voice/speech_text.py
+++ b/deeptutor/services/voice/speech_text.py
@@ -199,7 +199,6 @@ _SPACING_DROP = {
"notag": "",
"tag": "",
"label": "",
- "quad": " ",
}
_BLACKBOARD = {
diff --git a/deeptutor/utils/document_images.py b/deeptutor/utils/document_images.py
index 4d8915d94..85074c8cd 100644
--- a/deeptutor/utils/document_images.py
+++ b/deeptutor/utils/document_images.py
@@ -202,6 +202,7 @@ def build_marker(image: EmbeddedImage) -> str:
"""The canonical in-text marker for one image."""
return f"[图片 {image_index_from_name(image.name)}: {image.name}]"
+
_MARKER_PATTERN = re.compile(r"\[图片 (\d+): ([^\]\s]+)\]")
@@ -505,9 +506,7 @@ def _rels_for(member: str) -> str:
# ---------------------------------------------------------------------------
-def extract_pdf_images(
- data: bytes, *, budget: ImageBudget | None = None
-) -> PdfImages:
+def extract_pdf_images(data: bytes, *, budget: ImageBudget | None = None) -> PdfImages:
"""Raster images per page via PyMuPDF, deduplicated across the document.
Running headers/footers embed the same logo xref on every page; only the
@@ -544,9 +543,10 @@ def extract_pdf_images(
except Exception:
continue
raw = extracted.get("image") or b""
- if int(extracted.get("width") or 0) < 64 or int(
- extracted.get("height") or 0
- ) < 64:
+ if (
+ int(extracted.get("width") or 0) < 64
+ or int(extracted.get("height") or 0) < 64
+ ):
continue
ext = _normalise_ext("." + (extracted.get("ext") or ""))
if ext in {".emf", ".wmf"}:
diff --git a/scripts/reading_refresh_figures.py b/scripts/reading_refresh_figures.py
index 7908f8986..a83ce8dfb 100644
--- a/scripts/reading_refresh_figures.py
+++ b/scripts/reading_refresh_figures.py
@@ -72,12 +72,8 @@ def _build_parser() -> argparse.ArgumentParser:
action="store_true",
help="caption even if a stored caption already exists (implies --caption)",
)
- parser.add_argument(
- "--limit", type=int, metavar="N", help="process at most N materials"
- )
- parser.add_argument(
- "--yes", action="store_true", help="skip the interactive confirmation"
- )
+ parser.add_argument("--limit", type=int, metavar="N", help="process at most N materials")
+ parser.add_argument("--yes", action="store_true", help="skip the interactive confirmation")
return parser
@@ -158,8 +154,7 @@ def main(argv: list[str] | None = None) -> int:
return 0
if not sys.stdin.isatty():
print(
- "refusing to run a non-dry refresh without --yes in a "
- "non-interactive shell",
+ "refusing to run a non-dry refresh without --yes in a non-interactive shell",
file=sys.stderr,
)
return 2
diff --git a/tests/multi_user/test_learning_surface_map.py b/tests/multi_user/test_learning_surface_map.py
index b4c662554..0179af477 100644
--- a/tests/multi_user/test_learning_surface_map.py
+++ b/tests/multi_user/test_learning_surface_map.py
@@ -54,9 +54,7 @@ def test_learning_surface_map(path: str, method: str, expected: str) -> None:
assert _learning_surface_for_path(path, method) == expected
-def test_put_restrictions_flips_standard_preset_to_learner(
- mu_isolated_root, seed_user
-):
+def test_put_restrictions_flips_standard_preset_to_learner(mu_isolated_root, seed_user):
"""PUT restrictions on a standard-preset account seeds the policy and
flips the account preset to ``learner`` (#1222 preset/policy mix)."""
import asyncio
diff --git a/tests/reading/test_reading_captions.py b/tests/reading/test_reading_captions.py
index df6f98a88..8f893141f 100644
--- a/tests/reading/test_reading_captions.py
+++ b/tests/reading/test_reading_captions.py
@@ -32,7 +32,9 @@ class _StubClient:
def supports_multimodal_images(self) -> bool:
return self._vision
- async def complete(self, prompt: str, system_prompt: str | None = None, **kwargs: object) -> str:
+ async def complete(
+ self, prompt: str, system_prompt: str | None = None, **kwargs: object
+ ) -> str:
name = str(kwargs.get("image_filename") or "")
self.calls.append(name)
if name in self._fail:
@@ -158,9 +160,7 @@ def _pdf_with_image(path: Path) -> None:
doc = pymupdf.open()
page = doc.new_page()
- prose = (
- "Figure one shows the measured throughput across three configurations. " * 8
- )
+ prose = "Figure one shows the measured throughput across three configurations. " * 8
page.insert_textbox(pymupdf.Rect(72, 72, 520, 280), prose, fontsize=9)
page.insert_image(pymupdf.Rect(72, 320, 300, 520), stream=_png_bytes(seed=11))
page.insert_image(pymupdf.Rect(320, 320, 540, 520), stream=_png_bytes(seed=23))
@@ -197,12 +197,22 @@ def test_refresh_document_preserves_state_and_captions(tmp_path: Path) -> None:
new_name = names[1]
media_index = content_dir / "media.json"
rows = [
- {"name": kept_name, "locator": 1, "mime": "image/png", "bytes": 9,
- "caption": f"kept caption for {kept_name}"},
+ {
+ "name": kept_name,
+ "locator": 1,
+ "mime": "image/png",
+ "bytes": 9,
+ "caption": f"kept caption for {kept_name}",
+ },
]
rows.append(
- {"name": "ghost.png", "locator": 1, "mime": "image/png", "bytes": 9,
- "caption": "ghost caption"}
+ {
+ "name": "ghost.png",
+ "locator": 1,
+ "mime": "image/png",
+ "bytes": 9,
+ "caption": "ghost caption",
+ }
)
media_index.write_text(json.dumps(rows), encoding="utf-8")
diff --git a/tests/reading/test_reading_media_notes.py b/tests/reading/test_reading_media_notes.py
index b08676ee3..637c773a0 100644
--- a/tests/reading/test_reading_media_notes.py
+++ b/tests/reading/test_reading_media_notes.py
@@ -26,7 +26,6 @@ from deeptutor.capabilities.reading.media_notes import (
)
from deeptutor.capabilities.reading.tools import _media_note
from deeptutor.core.context import UnifiedContext
-
import deeptutor.reading as reading_pkg
from deeptutor.reading import page_render as page_render_module
@@ -74,7 +73,9 @@ def test_media_note_without_captions_is_byte_for_byte_the_legacy_output() -> Non
note = _media_note(_FakeStore(rows), "material", "page", [3, 5])
- assert note == _legacy_note("page", [(3, ["image-01.png", "image-02.png"]), (5, ["image-09.png"])])
+ assert note == _legacy_note(
+ "page", [(3, ["image-01.png", "image-02.png"]), (5, ["image-09.png"])]
+ )
def test_media_note_appends_each_caption_after_its_figure() -> None:
@@ -203,9 +204,7 @@ def test_pre_loop_seed_skips_media_work_without_a_locator(monkeypatch, locator)
def test_pre_loop_seed_announces_a_page_render(monkeypatch) -> None:
monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore([]))
- monkeypatch.setattr(
- page_render_module, "page_has_render", lambda material_id, locator: True
- )
+ monkeypatch.setattr(page_render_module, "page_has_render", lambda material_id, locator: True)
seed = ReadingCapability().pre_loop_seed(_viewport_context(14))
@@ -215,9 +214,7 @@ def test_pre_loop_seed_announces_a_page_render(monkeypatch) -> None:
def test_pre_loop_seed_is_byte_for_byte_unchanged_without_a_page_render(monkeypatch) -> None:
monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore([_row(4, "image-01.png")]))
- monkeypatch.setattr(
- page_render_module, "page_has_render", lambda material_id, locator: False
- )
+ monkeypatch.setattr(page_render_module, "page_has_render", lambda material_id, locator: False)
seed = ReadingCapability().pre_loop_seed(_viewport_context(4))
diff --git a/tests/reading/test_reading_page_render.py b/tests/reading/test_reading_page_render.py
index 464fed82d..a83d9fadb 100644
--- a/tests/reading/test_reading_page_render.py
+++ b/tests/reading/test_reading_page_render.py
@@ -64,9 +64,7 @@ def _prose(label: str) -> str:
def _draw_diagram(page) -> None:
"""Ten vector primitives — comfortably past the render gate of 8."""
for index in range(4):
- page.draw_line(
- pymupdf.Point(72, 120 + index * 12), pymupdf.Point(300, 120 + index * 12)
- )
+ page.draw_line(pymupdf.Point(72, 120 + index * 12), pymupdf.Point(300, 120 + index * 12))
for index in range(3):
page.draw_rect(pymupdf.Rect(72, 220 + index * 34, 220, 244 + index * 34))
for index in range(3):
@@ -82,9 +80,7 @@ def _build_pdf(path: Path, *, embedded_images: int = 0) -> None:
rect = pymupdf.Rect(72, 380 + index * 60, 260, 440 + index * 60)
page.insert_image(rect, stream=_png_bytes(seed=index + 1))
text_page = doc.new_page(width=612, height=792)
- text_page.insert_textbox(
- pymupdf.Rect(72, 72, 540, 600), _prose("Page two."), fontsize=11
- )
+ text_page.insert_textbox(pymupdf.Rect(72, 72, 540, 600), _prose("Page two."), fontsize=11)
doc.save(str(path))
doc.close()
@@ -157,9 +153,7 @@ def test_attachments_truncate_to_max_with_render_first(reading_home: Path) -> No
manifest = store.ingest(source)
_write_media_index(store, manifest.material_id, count=5)
- attachments = _reading_viewport_image_attachments(
- manifest.material_id, {"locator": 1}
- )
+ attachments = _reading_viewport_image_attachments(manifest.material_id, {"locator": 1})
assert len(attachments) == READING_VIEWPORT_MAX_IMAGES == 4
assert attachments[0]["id"].startswith("rp-")
diff --git a/tests/services/llm/test_model_overrides.py b/tests/services/llm/test_model_overrides.py
index 8f4d5abc4..1db539efa 100644
--- a/tests/services/llm/test_model_overrides.py
+++ b/tests/services/llm/test_model_overrides.py
@@ -66,9 +66,7 @@ def test_unrelated_models_are_untouched(model: str) -> None:
@pytest.mark.parametrize("model", ["claude-sonnet-5", "claude-opus-4-8"])
@pytest.mark.parametrize("binding", ["openai", "anthropic", "no-such-provider"])
-def test_claude_models_that_deprecated_temperature_never_send_it(
- binding: str, model: str
-) -> None:
+def test_claude_models_that_deprecated_temperature_never_send_it(binding: str, model: str) -> None:
"""Anthropic answers HTTP 400 ``\`temperature\` is deprecated for this
model.`` for Sonnet 5 and Opus 4.8. Haiku 4.5 still accepts it, so the
rule names models, not the vendor prefix.
diff --git a/tests/services/test_voice.py b/tests/services/test_voice.py
index cf3b2d695..7f2c52f7e 100644
--- a/tests/services/test_voice.py
+++ b/tests/services/test_voice.py
@@ -147,9 +147,7 @@ def test_strip_markdown_drops_unpaired_dollars() -> None:
def test_strip_markdown_verbalizes_fractions_roots_and_greek() -> None:
- out = strip_markdown_for_speech(
- r"Take $\frac{1}{2}$ of $\sqrt{x}$ and $\alpha + \beta$."
- )
+ out = strip_markdown_for_speech(r"Take $\frac{1}{2}$ of $\sqrt{x}$ and $\alpha + \beta$.")
assert "$" not in out
assert "\\" not in out
assert "{" not in out and "}" not in out