mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 11:39:34 +08:00
Merge PR #1479 timed media entity rendering
This commit is contained in:
@@ -211,7 +211,7 @@ async def save_video_progress(material_id: str, payload: ProgressRequest) -> dic
|
||||
try:
|
||||
store = get_timed_media_store()
|
||||
with store.lock(material_id):
|
||||
material = store.get(material_id)
|
||||
material = store.get(material_id, lock_held=True)
|
||||
known_duration = float(material.get("metadata", {}).get("duration_seconds") or 0)
|
||||
duration = known_duration or float(payload.duration_seconds or 0)
|
||||
position = min(payload.time_seconds, duration) if duration > 0 else payload.time_seconds
|
||||
|
||||
@@ -8,6 +8,7 @@ from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import html
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
@@ -188,6 +189,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 []
|
||||
@@ -202,7 +208,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")
|
||||
@@ -277,8 +283,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(
|
||||
{
|
||||
@@ -311,7 +316,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:
|
||||
@@ -320,6 +325,38 @@ 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, *, lock_held: bool = False) -> dict[str, Any]:
|
||||
payload = self._load(material_id)
|
||||
if not self._repair_transcript_text(payload):
|
||||
return payload
|
||||
if lock_held:
|
||||
return self.save(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)
|
||||
@@ -640,7 +677,7 @@ async def resolve_material(
|
||||
# Network resolution happens outside the file lock. Re-read only the
|
||||
# mutable learning state so a concurrent progress save cannot be lost.
|
||||
try:
|
||||
latest = store.get(material_id)
|
||||
latest = store.get(material_id, lock_held=True)
|
||||
except TimedMediaNotFound:
|
||||
latest = {}
|
||||
if isinstance(latest.get("learning"), dict):
|
||||
@@ -728,7 +765,7 @@ async def refresh_invidious_transcript(material_id: str) -> dict[str, Any]:
|
||||
"cues": cues,
|
||||
}
|
||||
with store.lock(material_id):
|
||||
latest = store.get(material_id)
|
||||
latest = store.get(material_id, lock_held=True)
|
||||
latest["transcript"] = refreshed_transcript
|
||||
latest["segments"] = build_segments(cues)
|
||||
saved = store.save(latest)
|
||||
|
||||
@@ -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 &\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 <script>two</script>" in response.text
|
||||
assert "one & <script>two</script>" in response.text
|
||||
assert " " not in response.text
|
||||
assert "\n<script>" not in response.text
|
||||
|
||||
|
||||
|
||||
@@ -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 from A & B",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
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> &\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 & apply"}],
|
||||
},
|
||||
"segments": [
|
||||
{"locator": 7, "start": 0, "end": 1, "text": "Learn & apply"}
|
||||
],
|
||||
"learning": {"last_position": 0},
|
||||
}
|
||||
)
|
||||
|
||||
with store.lock(material_id):
|
||||
repaired = store.get(material_id, lock_held=True)
|
||||
|
||||
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"
|
||||
assert store.get(material_id)["segments"][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},
|
||||
|
||||
Reference in New Issue
Block a user