Skip to content

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

fix(video-learning): decode caption HTML entities

Yin17fb9d04b722
diff --git a/deeptutor/video_learning/service.py b/deeptutor/video_learning/service.py
index ed7b3ea21..0d3cf95b4 100644
--- a/deeptutor/video_learning/service.py
+++ b/deeptutor/video_learning/service.py
@@ -7,6 +7,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
import hashlib
+import html
import ipaddress
import json
import os
@@ -187,6 +188,11 @@ def save_video_learning_settings(payload: Any) -> dict[str, Any]:
return normalized
+def clean_transcript_text(value: Any) -> str:
+ """Decode caption-source entities into the text readers should see."""
+ return re.sub(r"\s+", " ", html.unescape(str(value or ""))).strip()
+
+
def normalize_cues(rows: Any) -> list[dict[str, Any]]:
if not isinstance(rows, (list, tuple)):
return []
@@ -201,7 +207,7 @@ def normalize_cues(rows: Any) -> list[dict[str, Any]]:
"duration": getattr(row, "duration", 0),
"text": getattr(row, "text", ""),
}
- text = str(merged.get("text") or merged.get("content") or "").strip()
+ text = clean_transcript_text(merged.get("text") or merged.get("content") or "")
if not text:
continue
encoded = text.encode("utf-8")
@@ -276,8 +282,7 @@ def parse_webvtt(text: str) -> list[dict[str, Any]]:
body_lines.append(line)
index += 1
- body = re.sub(r"<[^>]+>", "", "\n".join(body_lines))
- body = re.sub(r"\s+", " ", body).strip()
+ body = clean_transcript_text(re.sub(r"<[^>]+>", "", "\n".join(body_lines)))
if body:
result.append(
{
@@ -310,7 +315,7 @@ class TimedMediaStore:
raise TimedMediaNotFound("Timed media material was not found.")
return self.root / f"{material_id}.json"
- def get(self, material_id: str) -> dict[str, Any]:
+ def _load(self, material_id: str) -> dict[str, Any]:
try:
payload = json.loads(self._path(material_id).read_text(encoding="utf-8"))
except (FileNotFoundError, OSError, json.JSONDecodeError) as exc:
@@ -319,6 +324,36 @@ class TimedMediaStore:
raise TimedMediaNotFound("Timed media material was not found.")
return payload
+ @staticmethod
+ def _repair_transcript_text(material: dict[str, Any]) -> bool:
+ """Repair legacy machine-generated captions without touching user content."""
+ transcript = material.get("transcript")
+ if not isinstance(transcript, dict):
+ return False
+ changed = False
+ for key in ("cues", "segments"):
+ rows = material.get(key) if key == "segments" else transcript.get(key)
+ if not isinstance(rows, list):
+ continue
+ for row in rows:
+ if not isinstance(row, dict) or not isinstance(row.get("text"), str):
+ continue
+ text = clean_transcript_text(row["text"])
+ if text != row["text"]:
+ row["text"] = text
+ changed = True
+ return changed
+
+ def get(self, material_id: str) -> dict[str, Any]:
+ payload = self._load(material_id)
+ if not self._repair_transcript_text(payload):
+ return payload
+ with self.lock(material_id):
+ latest = self._load(material_id)
+ if self._repair_transcript_text(latest):
+ return self.save(latest)
+ return latest
+
def save(self, material: dict[str, Any]) -> dict[str, Any]:
payload = dict(material)
payload.pop("playback", None)
diff --git a/tests/video_learning/test_router.py b/tests/video_learning/test_router.py
index 20595f3db..bbc8ffb1d 100644
--- a/tests/video_learning/test_router.py
+++ b/tests/video_learning/test_router.py
@@ -58,7 +58,13 @@ def _material(*, duration: int = 100) -> dict[str, object]:
"metadata": {"duration_seconds": duration},
"transcript": {
"status": "ready",
- "cues": [{"start": 1.25, "end": 3.5, "text": "one\n<script>two</script>"}],
+ "cues": [
+ {
+ "start": 1.25,
+ "end": 3.5,
+ "text": "one&nbsp;&nbsp;&amp;\n<script>two</script>",
+ }
+ ],
},
"learning": {"last_position": 0},
"provider_cache": {
@@ -284,7 +290,8 @@ def test_subtitles_are_valid_vtt_and_escape_markup(client: TestClient) -> None:
assert response.status_code == 200
assert response.headers["content-type"].startswith("text/vtt")
assert "00:00:01.250 --> 00:00:03.500" in response.text
- assert "one &lt;script&gt;two&lt;/script&gt;" in response.text
+ assert "one &amp; &lt;script&gt;two&lt;/script&gt;" in response.text
+ assert "&nbsp;" not in response.text
assert "\n<script>" not in response.text
diff --git a/tests/video_learning/test_service.py b/tests/video_learning/test_service.py
index 810c56027..d99d6da34 100644
--- a/tests/video_learning/test_service.py
+++ b/tests/video_learning/test_service.py
@@ -81,16 +81,30 @@ def test_transcript_normalization_enforces_the_storage_budget(monkeypatch) -> No
assert [cue["text"] for cue in cues] == ["1234", "5678"]
+def test_transcript_normalization_decodes_entities_and_normalizes_whitespace() -> None:
+ cues = service.normalize_cues(
+ [
+ {
+ "start": 0,
+ "duration": 1,
+ "text": "Learn&nbsp;&nbsp;from &#x41; &amp; &#66;",
+ }
+ ]
+ )
+
+ assert cues == [{"start": 0.0, "end": 1.0, "text": "Learn from A & B"}]
+
+
def test_webvtt_preserves_caption_after_leading_blank_and_inline_tags() -> None:
cues = service.parse_webvtt(
- "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\n \nOpening <c>idea</c>\nand continuation\n"
+ "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\n \nOpening <c>idea</c>&nbsp;&amp;\nand continuation\n"
)
assert cues == [
{
"start": 0.0,
"end": 2.0,
- "text": "Opening idea and continuation",
+ "text": "Opening idea & and continuation",
}
]
@@ -114,6 +128,35 @@ Second line
]
+def test_store_repairs_legacy_caption_entities(isolated: Path) -> None:
+ store = service.TimedMediaStore()
+ material_id = service.material_id_for("dQw4w9WgXcQ")
+ store.save(
+ {
+ "version": 1,
+ "type": "timed_media",
+ "material_id": material_id,
+ "transcript": {
+ "status": "ready",
+ "cues": [{"start": 0, "end": 1, "text": "Learn&nbsp;&nbsp;&amp; apply"}],
+ },
+ "segments": [
+ {"locator": 7, "start": 0, "end": 1, "text": "Learn&nbsp;&nbsp;&amp; apply"}
+ ],
+ "learning": {"last_position": 0},
+ }
+ )
+
+ repaired = store.get(material_id)
+
+ assert repaired["transcript"]["cues"][0]["text"] == "Learn & apply"
+ assert repaired["segments"] == [
+ {"locator": 7, "start": 0, "end": 1, "text": "Learn & apply"}
+ ]
+ persisted = json.loads(store._path(material_id).read_text(encoding="utf-8"))
+ assert persisted["transcript"]["cues"][0]["text"] == "Learn & apply"
+
+
def test_invidious_caption_choice_accepts_the_real_snake_case_schema() -> None:
captions = [
{"label": "English (auto-generated)", "language_code": "en", "auto_generated": True},