@clipen/clipen-cli 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +52 -4
- package/pyproject.toml +28 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +416 -0
- package/src/clipen/analysis/audio.py +392 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +751 -0
- package/src/clipen/analysis/image_similarity.py +143 -0
- package/src/clipen/analysis/keyframes.py +171 -0
- package/src/clipen/analysis/models.py +230 -0
- package/src/clipen/analysis/qwen_worker.py +629 -0
- package/src/clipen/analysis/resources.py +21 -0
- package/src/clipen/analysis/runtime.py +64 -0
- package/src/clipen/analysis/service.py +626 -0
- package/src/clipen/analysis/setup.py +935 -0
- package/src/clipen/analysis/setup_cli.py +117 -0
- package/src/clipen/analysis/storage.py +2046 -0
- package/src/clipen/analysis/transcription.py +948 -0
- package/src/clipen/analysis/visual.py +176 -0
- package/src/clipen/annotations/__init__.py +10 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +380 -0
- package/src/clipen/annotations/suggestions.py +120 -0
- package/src/clipen/asr_release.py +139 -0
- package/src/clipen/bootstrap.py +967 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1470 -0
- package/src/clipen/controller/server.py +543 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +117 -0
- package/src/clipen/domain/timeline.py +584 -0
- package/src/clipen/domain/validation.py +15 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +134 -0
- package/src/clipen/editing/agent_repository.py +757 -0
- package/src/clipen/editing/agent_tools.py +532 -0
- package/src/clipen/editing/alignment.py +110 -0
- package/src/clipen/editing/alignment_setup.py +108 -0
- package/src/clipen/editing/alignment_worker.py +22 -0
- package/src/clipen/editing/change_report.py +71 -0
- package/src/clipen/editing/compiler.py +41 -0
- package/src/clipen/editing/component_looks.py +107 -0
- package/src/clipen/editing/component_review.py +78 -0
- package/src/clipen/editing/coordinator.py +374 -0
- package/src/clipen/editing/editorial_review.py +187 -0
- package/src/clipen/editing/evidence_jobs.py +295 -0
- package/src/clipen/editing/history_changes.py +131 -0
- package/src/clipen/editing/music_choices.py +15 -0
- package/src/clipen/editing/production_catalog.py +192 -0
- package/src/clipen/editing/production_limits.py +59 -0
- package/src/clipen/editing/production_media.py +226 -0
- package/src/clipen/editing/production_preview.py +180 -0
- package/src/clipen/editing/production_progress.py +141 -0
- package/src/clipen/editing/production_requirements.py +50 -0
- package/src/clipen/editing/production_tools.py +596 -0
- package/src/clipen/editing/program_audio.py +118 -0
- package/src/clipen/editing/program_direction.py +49 -0
- package/src/clipen/editing/program_story.py +53 -0
- package/src/clipen/editing/program_subtitles.py +134 -0
- package/src/clipen/editing/programme_review.py +73 -0
- package/src/clipen/editing/prompt_history.py +47 -0
- package/src/clipen/editing/recut.py +127 -0
- package/src/clipen/editing/refinement_references.py +188 -0
- package/src/clipen/editing/resolve_export.py +616 -0
- package/src/clipen/editing/resolve_titles.py +234 -0
- package/src/clipen/editing/skill_tools.py +575 -0
- package/src/clipen/editing/source_dialogue.py +82 -0
- package/src/clipen/editing/speech_coverage.py +30 -0
- package/src/clipen/editing/speech_quality.py +6 -0
- package/src/clipen/editing/tool_receipts.py +52 -0
- package/src/clipen/editing/versions.py +161 -0
- package/src/clipen/editing/visual_preview.py +93 -0
- package/src/clipen/editing/workbench.py +74 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +149 -0
- package/src/clipen/finishing/catalog.py +181 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +26 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +40 -0
- package/src/clipen/mcp_editing/server.py +353 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +266 -0
- package/src/clipen/media/models.py +360 -0
- package/src/clipen/media/preview.py +147 -0
- package/src/clipen/media/probe.py +446 -0
- package/src/clipen/media/service.py +317 -0
- package/src/clipen/media/storage.py +742 -0
- package/src/clipen/music_vocabulary.py +5 -0
- package/src/clipen/planning/__init__.py +9 -0
- package/src/clipen/planning/models.py +240 -0
- package/src/clipen/power.py +23 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +269 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +34 -0
- package/src/clipen/projects/models.py +192 -0
- package/src/clipen/projects/picker.py +256 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +175 -0
- package/src/clipen/projects/storage.py +1478 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +75 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +194 -0
- package/src/clipen/providers/claude.py +375 -0
- package/src/clipen/providers/claude_editing.py +111 -0
- package/src/clipen/providers/codex.py +1036 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +565 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +270 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +126 -0
- package/src/clipen/rendering/custom_components.py +240 -0
- package/src/clipen/rendering/custom_render.py +197 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +64 -0
- package/src/clipen/rendering/program_components.py +193 -0
- package/src/clipen/rendering/program_creator.py +649 -0
- package/src/clipen/rendering/program_identities.py +255 -0
- package/src/clipen/rendering/program_motion.py +141 -0
- package/src/clipen/rendering/program_studio.py +168 -0
- package/src/clipen/rendering/program_styles.py +235 -0
- package/src/clipen/rendering/program_subtitles.py +52 -0
- package/src/clipen/rendering/renderer.py +708 -0
- package/src/clipen/rendering/storage.py +243 -0
- package/src/clipen/rendering/titles.py +360 -0
- package/src/clipen/skills/__init__.py +4 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +218 -0
- package/src/clipen/skills/library.py +131 -0
- package/src/clipen/skills/package.py +231 -0
- package/src/clipen/skills/visual_styles.py +44 -0
- package/src/clipen/workspace.py +210 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Bounded local evidence extraction, using decoded PTS rather than average FPS."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from array import array
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from fractions import Fraction
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
import shutil
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
import wave
|
|
15
|
+
|
|
16
|
+
from clipen.media import bounded_file_fingerprint
|
|
17
|
+
from clipen.media.discovery import open_file_beneath
|
|
18
|
+
from .audio import AudioPreparationInput, AudioPreparationError, FFmpegAudioAdapter
|
|
19
|
+
from .keyframes import AdaptiveKeyframeSelector
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@contextmanager
|
|
23
|
+
def verified_source(source: AudioPreparationInput):
|
|
24
|
+
descriptor = open_file_beneath(source.root, source.relative_path)
|
|
25
|
+
try:
|
|
26
|
+
def identity():
|
|
27
|
+
info = os.fstat(descriptor)
|
|
28
|
+
return info.st_size, info.st_mtime_ns, bounded_file_fingerprint(descriptor, info.st_size)
|
|
29
|
+
expected = source.size_bytes, source.mtime_ns, source.fingerprint
|
|
30
|
+
if identity() != expected:
|
|
31
|
+
raise AudioPreparationError("source_changed")
|
|
32
|
+
before = os.fstat(descriptor)
|
|
33
|
+
yield descriptor
|
|
34
|
+
if identity() != expected:
|
|
35
|
+
raise AudioPreparationError("source_changed")
|
|
36
|
+
reopened = open_file_beneath(source.root, source.relative_path)
|
|
37
|
+
try:
|
|
38
|
+
current = os.fstat(reopened)
|
|
39
|
+
if (before.st_dev, before.st_ino) != (current.st_dev, current.st_ino):
|
|
40
|
+
raise AudioPreparationError("source_changed")
|
|
41
|
+
finally:
|
|
42
|
+
os.close(reopened)
|
|
43
|
+
finally:
|
|
44
|
+
os.close(descriptor)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class LocalEvidenceExtractor(FFmpegAudioAdapter):
|
|
48
|
+
"""Bounded sparse video evidence plus a 120-second audio window per stream."""
|
|
49
|
+
MAX_FRAMES = AdaptiveKeyframeSelector.MAXIMUM_BUDGET
|
|
50
|
+
WINDOW_SECONDS = 120
|
|
51
|
+
|
|
52
|
+
def __init__(self, executable: str | None = None, probe_executable: str | None = None):
|
|
53
|
+
super().__init__(executable, timeout_seconds=120, maximum_output_bytes=8 * 1024**2)
|
|
54
|
+
sibling = Path(self.executable).with_name("ffprobe")
|
|
55
|
+
self.probe_executable = probe_executable or (
|
|
56
|
+
str(sibling) if sibling.is_file() else shutil.which("ffprobe")
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def frame(self, source, offset: Fraction, output: Path, cancel: threading.Event):
|
|
60
|
+
output = self._validate_empty_output(output)
|
|
61
|
+
span = source.source_span
|
|
62
|
+
tb = span.time_base
|
|
63
|
+
if tb.numerator <= 0:
|
|
64
|
+
raise AudioPreparationError("video_time_metadata_missing")
|
|
65
|
+
duration = Fraction(span.duration_pts) * Fraction(tb.numerator, tb.denominator)
|
|
66
|
+
if not 0 <= offset < duration:
|
|
67
|
+
raise AudioPreparationError("frame_time_mapping_invalid")
|
|
68
|
+
absolute_time = Fraction(int(span.start_pts)) * Fraction(tb.numerator, tb.denominator) + offset
|
|
69
|
+
with verified_source(source) as descriptor:
|
|
70
|
+
_, stderr, code = self._run((
|
|
71
|
+
self.executable, "-nostdin", "-hide_banner", "-loglevel", "info",
|
|
72
|
+
"-copyts", "-noaccurate_seek", "-seek_timestamp", "1", "-ss", f"{float(absolute_time):.9f}", "-i", f"/dev/fd/{descriptor}",
|
|
73
|
+
"-map", f"0:{source.stream_index}", "-an", "-frames:v", "1",
|
|
74
|
+
"-vf", f"scale=512:512:force_original_aspect_ratio=decrease,format=rgb24,settb={tb.numerator}/{tb.denominator},select=gte(pts\\,{math.ceil(absolute_time / Fraction(tb.numerator, tb.denominator))}),showinfo",
|
|
75
|
+
"-threads", "1", "-c:v", "png", "-f", "image2", "-y", str(output),
|
|
76
|
+
), (descriptor,), cancel, observed_output=output)
|
|
77
|
+
matches = re.findall(rb"\bn:\s*0\s+pts:\s*(-?\d+)", stderr)
|
|
78
|
+
if code or len(matches) != 1 or not output.stat().st_size:
|
|
79
|
+
raise AudioPreparationError("frame_decode_failed")
|
|
80
|
+
pts = int(matches[0])
|
|
81
|
+
if not int(span.start_pts) <= pts < int(span.end_pts):
|
|
82
|
+
raise AudioPreparationError("frame_time_mapping_invalid")
|
|
83
|
+
return pts
|
|
84
|
+
|
|
85
|
+
def keyframe_candidates(self, source, cancel: threading.Event):
|
|
86
|
+
if self.probe_executable is None:
|
|
87
|
+
raise AudioPreparationError("ffprobe_not_found")
|
|
88
|
+
span = source.source_span
|
|
89
|
+
time_base = Fraction(span.time_base.numerator, span.time_base.denominator)
|
|
90
|
+
anchors = AdaptiveKeyframeSelector.uniform(
|
|
91
|
+
int(span.start_pts), int(span.end_pts), 32
|
|
92
|
+
)
|
|
93
|
+
intervals = ",".join(
|
|
94
|
+
f"{float(Fraction(candidate.pts) * time_base):.9f}%+0.02"
|
|
95
|
+
for candidate in anchors
|
|
96
|
+
)
|
|
97
|
+
with verified_source(source) as descriptor:
|
|
98
|
+
stdout, _, code = self._run((
|
|
99
|
+
self.probe_executable, "-v", "error", "-read_intervals", intervals,
|
|
100
|
+
"-select_streams", str(source.stream_index),
|
|
101
|
+
"-show_packets", "-show_entries", "packet=pts,size,flags",
|
|
102
|
+
"-of", "csv=p=0", f"/dev/fd/{descriptor}",
|
|
103
|
+
), (descriptor,), cancel)
|
|
104
|
+
if code:
|
|
105
|
+
raise AudioPreparationError("keyframe_packet_probe_failed")
|
|
106
|
+
packets = {}
|
|
107
|
+
try:
|
|
108
|
+
for raw_line in stdout.decode("utf-8", "strict").splitlines():
|
|
109
|
+
fields = raw_line.split(",")
|
|
110
|
+
if len(fields) != 3 or "K" not in fields[2]:
|
|
111
|
+
continue
|
|
112
|
+
point, size = int(fields[0]), int(fields[1])
|
|
113
|
+
if int(span.start_pts) <= point < int(span.end_pts):
|
|
114
|
+
packets[point] = max(packets.get(point, 0), size)
|
|
115
|
+
except (UnicodeDecodeError, ValueError) as error:
|
|
116
|
+
raise AudioPreparationError("keyframe_packet_parse_failed") from error
|
|
117
|
+
ordered = sorted(packets.items())
|
|
118
|
+
limited = len(ordered) > 256
|
|
119
|
+
if limited:
|
|
120
|
+
ordered = [
|
|
121
|
+
ordered[index * len(ordered) // 256]
|
|
122
|
+
for index in range(256)
|
|
123
|
+
]
|
|
124
|
+
sizes = [size for _, size in ordered]
|
|
125
|
+
minimum, maximum = (min(sizes), max(sizes)) if sizes else (0, 0)
|
|
126
|
+
candidates = [
|
|
127
|
+
{
|
|
128
|
+
"pts": str(point),
|
|
129
|
+
"score": round((size - minimum) / (maximum - minimum), 6)
|
|
130
|
+
if maximum > minimum
|
|
131
|
+
else 0.0,
|
|
132
|
+
}
|
|
133
|
+
for point, size in ordered
|
|
134
|
+
]
|
|
135
|
+
return {
|
|
136
|
+
"candidate_pts": [item["pts"] for item in candidates],
|
|
137
|
+
"candidates": candidates,
|
|
138
|
+
"probe_count": len(anchors),
|
|
139
|
+
"probe_interval_seconds": 0.02,
|
|
140
|
+
"candidate_limit_reached": limited,
|
|
141
|
+
"method": "sparse_codec_keyframe_packet_complexity_v2",
|
|
142
|
+
"decoded_frames": False,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
def audio_features(self, source, output: Path, cancel: threading.Event):
|
|
146
|
+
output = self._validate_empty_output(output)
|
|
147
|
+
with verified_source(source) as descriptor:
|
|
148
|
+
_, _, code = self._run((
|
|
149
|
+
self.executable, "-nostdin", "-hide_banner", "-loglevel", "error",
|
|
150
|
+
"-i", f"/dev/fd/{descriptor}", "-map", f"0:{source.stream_index}",
|
|
151
|
+
"-t", str(self.WINDOW_SECONDS), "-vn", "-ac", "1", "-ar", "16000",
|
|
152
|
+
"-c:a", "pcm_s16le", "-f", "wav", "-y", str(output),
|
|
153
|
+
), (descriptor,), cancel, observed_output=output)
|
|
154
|
+
if code:
|
|
155
|
+
raise AudioPreparationError("audio_decode_failed")
|
|
156
|
+
windows = []
|
|
157
|
+
with wave.open(str(output), "rb") as audio:
|
|
158
|
+
if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) != (1, 2, 16000):
|
|
159
|
+
raise AudioPreparationError("normalized_audio_invalid")
|
|
160
|
+
start = 0
|
|
161
|
+
while data := audio.readframes(16000):
|
|
162
|
+
if cancel.is_set():
|
|
163
|
+
raise AudioPreparationError("cancelled")
|
|
164
|
+
values = array("h", data)
|
|
165
|
+
if sys.byteorder != "little":
|
|
166
|
+
values.byteswap()
|
|
167
|
+
rms = math.sqrt(sum(v*v for v in values) / len(values)) / 32768
|
|
168
|
+
windows.append({"start_sample": start, "end_sample": start + len(values),
|
|
169
|
+
"rms_dbfs": round(20 * math.log10(max(rms, 1e-6)), 2),
|
|
170
|
+
"peak": round(max(abs(v) for v in values) / 32768, 6),
|
|
171
|
+
"low_energy": rms < 0.01})
|
|
172
|
+
start += len(values)
|
|
173
|
+
if not windows:
|
|
174
|
+
raise AudioPreparationError("normalized_audio_invalid")
|
|
175
|
+
return {"sample_rate": 16000, "windows": windows,
|
|
176
|
+
"method": "signal_energy_not_music_or_speech_classification"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""User-authored material metadata and transcript corrections."""
|
|
2
|
+
|
|
3
|
+
from .models import DayPart, MaterialUsage
|
|
4
|
+
from .storage import AnnotationRepository
|
|
5
|
+
from .suggestions import annotation_suggestion, annotation_suggestions
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AnnotationRepository", "DayPart", "MaterialUsage",
|
|
9
|
+
"annotation_suggestion", "annotation_suggestions",
|
|
10
|
+
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Validated annotation values shared by storage and planning."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import Enum
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DayPart(str, Enum):
|
|
9
|
+
DAWN = "dawn"
|
|
10
|
+
MORNING = "morning"
|
|
11
|
+
NOON = "noon"
|
|
12
|
+
AFTERNOON = "afternoon"
|
|
13
|
+
EVENING = "evening"
|
|
14
|
+
NIGHT = "night"
|
|
15
|
+
LATE_NIGHT = "late_night"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class MaterialUsage(str, Enum):
|
|
19
|
+
NORMAL = "normal"
|
|
20
|
+
MUST_USE = "must_use"
|
|
21
|
+
EXCLUDE = "exclude"
|
|
22
|
+
AMBIENT_ONLY = "ambient_only"
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""Transactional persistence for user-authored material annotations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import sqlite3
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
|
|
10
|
+
from clipen.projects.models import ProjectError, validate_project_id, validate_request_id
|
|
11
|
+
from clipen.projects.storage import ProjectRepository, command_digest, utc_now
|
|
12
|
+
|
|
13
|
+
from .models import DayPart, MaterialUsage
|
|
14
|
+
from .suggestions import annotation_suggestion
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
_VERSION_ID = re.compile(r"av_[0-9a-f]{32}\Z")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AnnotationRepository:
|
|
21
|
+
def __init__(self, projects: ProjectRepository) -> None:
|
|
22
|
+
self.projects = projects
|
|
23
|
+
|
|
24
|
+
def get(self, project_id: str, version_id: str, stream_index: int) -> dict[str, object]:
|
|
25
|
+
validate_project_id(project_id)
|
|
26
|
+
self._validate_identity(version_id, stream_index)
|
|
27
|
+
try:
|
|
28
|
+
with self.projects.connect(project_id) as database:
|
|
29
|
+
self._require_version(database, version_id)
|
|
30
|
+
material = database.execute(
|
|
31
|
+
"SELECT * FROM material_annotations WHERE version_id=?",
|
|
32
|
+
(version_id,),
|
|
33
|
+
).fetchone()
|
|
34
|
+
transcript = database.execute(
|
|
35
|
+
"SELECT * FROM transcript_annotations "
|
|
36
|
+
"WHERE version_id=? AND stream_index=?",
|
|
37
|
+
(version_id, stream_index),
|
|
38
|
+
).fetchone() if stream_index >= 0 else None
|
|
39
|
+
current_revision = self._current_transcript_revision(
|
|
40
|
+
database, version_id, stream_index
|
|
41
|
+
)
|
|
42
|
+
suggestion = annotation_suggestion(database, version_id)
|
|
43
|
+
return self._public(
|
|
44
|
+
material, transcript, version_id, stream_index, current_revision, suggestion
|
|
45
|
+
)
|
|
46
|
+
except ProjectError:
|
|
47
|
+
raise
|
|
48
|
+
except (json.JSONDecodeError, TypeError, ValueError) as error:
|
|
49
|
+
raise ProjectError(
|
|
50
|
+
"storage_corrupt", "Clipen 無法讀取素材標註。", status_code=500
|
|
51
|
+
) from error
|
|
52
|
+
except sqlite3.Error as error:
|
|
53
|
+
raise ProjectError(
|
|
54
|
+
"storage_failed", "Clipen 無法讀取素材標註。", status_code=500
|
|
55
|
+
) from error
|
|
56
|
+
|
|
57
|
+
def save(
|
|
58
|
+
self,
|
|
59
|
+
project_id: str,
|
|
60
|
+
request_id: object,
|
|
61
|
+
version_id: str,
|
|
62
|
+
stream_index: int,
|
|
63
|
+
expected_material_revision: object,
|
|
64
|
+
expected_transcript_revision: object,
|
|
65
|
+
material: object,
|
|
66
|
+
transcript: object,
|
|
67
|
+
) -> dict[str, object]:
|
|
68
|
+
validate_project_id(project_id)
|
|
69
|
+
normalized_request = validate_request_id(request_id)
|
|
70
|
+
self._validate_identity(version_id, stream_index)
|
|
71
|
+
material_revision = self._expected_revision(expected_material_revision)
|
|
72
|
+
transcript_revision = self._expected_revision(expected_transcript_revision)
|
|
73
|
+
normalized_material = self._material(material)
|
|
74
|
+
normalized_transcript = self._transcript(transcript, stream_index)
|
|
75
|
+
request_hash = command_digest({
|
|
76
|
+
"version_id": version_id,
|
|
77
|
+
"stream_index": stream_index,
|
|
78
|
+
"expected_material_revision": material_revision,
|
|
79
|
+
"expected_transcript_revision": transcript_revision,
|
|
80
|
+
"material": normalized_material,
|
|
81
|
+
"transcript": normalized_transcript,
|
|
82
|
+
})
|
|
83
|
+
now = utc_now()
|
|
84
|
+
try:
|
|
85
|
+
with self.projects.connect(project_id) as database:
|
|
86
|
+
database.execute("BEGIN IMMEDIATE")
|
|
87
|
+
receipt = database.execute(
|
|
88
|
+
"SELECT command_type,request_hash,response_json "
|
|
89
|
+
"FROM annotation_command_receipts WHERE request_id=?",
|
|
90
|
+
(normalized_request,),
|
|
91
|
+
).fetchone()
|
|
92
|
+
if receipt is not None:
|
|
93
|
+
if receipt["command_type"] != "save_annotation" or receipt["request_hash"] != request_hash:
|
|
94
|
+
raise ProjectError(
|
|
95
|
+
"request_conflict",
|
|
96
|
+
"這次保存標註的操作與既有內容衝突。",
|
|
97
|
+
status_code=409,
|
|
98
|
+
)
|
|
99
|
+
response = json.loads(receipt["response_json"])
|
|
100
|
+
database.rollback()
|
|
101
|
+
return response
|
|
102
|
+
self._require_version(database, version_id)
|
|
103
|
+
current_material = database.execute(
|
|
104
|
+
"SELECT revision FROM material_annotations WHERE version_id=?",
|
|
105
|
+
(version_id,),
|
|
106
|
+
).fetchone()
|
|
107
|
+
observed_material = 0 if current_material is None else current_material["revision"]
|
|
108
|
+
current_transcript = database.execute(
|
|
109
|
+
"SELECT revision FROM transcript_annotations "
|
|
110
|
+
"WHERE version_id=? AND stream_index=?",
|
|
111
|
+
(version_id, stream_index),
|
|
112
|
+
).fetchone() if stream_index >= 0 else None
|
|
113
|
+
observed_transcript = 0 if current_transcript is None else current_transcript["revision"]
|
|
114
|
+
if observed_material != material_revision or observed_transcript != transcript_revision:
|
|
115
|
+
raise ProjectError(
|
|
116
|
+
"annotation_revision_conflict",
|
|
117
|
+
"素材標註已更新,請重新整理後再保存。",
|
|
118
|
+
status_code=409,
|
|
119
|
+
)
|
|
120
|
+
next_material = observed_material + 1
|
|
121
|
+
database.execute(
|
|
122
|
+
"INSERT INTO material_annotations "
|
|
123
|
+
"(version_id,revision,people_json,location,trip_day,day_part,note,usage,updated_at) "
|
|
124
|
+
"VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(version_id) DO UPDATE SET "
|
|
125
|
+
"revision=excluded.revision,people_json=excluded.people_json,"
|
|
126
|
+
"location=excluded.location,trip_day=excluded.trip_day,"
|
|
127
|
+
"day_part=excluded.day_part,note=excluded.note,usage=excluded.usage,"
|
|
128
|
+
"updated_at=excluded.updated_at",
|
|
129
|
+
(
|
|
130
|
+
version_id, next_material,
|
|
131
|
+
json.dumps(normalized_material["people"], ensure_ascii=False, separators=(",", ":")),
|
|
132
|
+
normalized_material["location"], normalized_material["trip_day"],
|
|
133
|
+
normalized_material["day_part"], normalized_material["note"],
|
|
134
|
+
normalized_material["usage"], now,
|
|
135
|
+
),
|
|
136
|
+
)
|
|
137
|
+
next_transcript = observed_transcript
|
|
138
|
+
if normalized_transcript is not None:
|
|
139
|
+
source_revision = self._current_transcript_revision(
|
|
140
|
+
database, version_id, stream_index
|
|
141
|
+
)
|
|
142
|
+
if source_revision is None or source_revision != normalized_transcript["source_revision_id"]:
|
|
143
|
+
raise ProjectError(
|
|
144
|
+
"annotation_transcript_changed",
|
|
145
|
+
"逐字稿已重新分析,請重新載入後再保存修正。",
|
|
146
|
+
status_code=409,
|
|
147
|
+
)
|
|
148
|
+
self._validate_corrections(
|
|
149
|
+
database, source_revision, normalized_transcript["corrections"]
|
|
150
|
+
)
|
|
151
|
+
next_transcript += 1
|
|
152
|
+
database.execute(
|
|
153
|
+
"INSERT INTO transcript_annotations "
|
|
154
|
+
"(version_id,stream_index,source_revision_id,revision,confirmed,discarded,"
|
|
155
|
+
"corrections_json,updated_at) VALUES(?,?,?,?,?,?,?,?) "
|
|
156
|
+
"ON CONFLICT(version_id,stream_index) DO UPDATE SET "
|
|
157
|
+
"source_revision_id=excluded.source_revision_id,revision=excluded.revision,"
|
|
158
|
+
"confirmed=excluded.confirmed,discarded=excluded.discarded,"
|
|
159
|
+
"corrections_json=excluded.corrections_json,"
|
|
160
|
+
"updated_at=excluded.updated_at",
|
|
161
|
+
(
|
|
162
|
+
version_id, stream_index, source_revision, next_transcript,
|
|
163
|
+
int(normalized_transcript["confirmed"]),
|
|
164
|
+
int(normalized_transcript["discarded"]),
|
|
165
|
+
json.dumps(normalized_transcript["corrections"], ensure_ascii=False, separators=(",", ":")),
|
|
166
|
+
now,
|
|
167
|
+
),
|
|
168
|
+
)
|
|
169
|
+
material_row = database.execute(
|
|
170
|
+
"SELECT * FROM material_annotations WHERE version_id=?", (version_id,)
|
|
171
|
+
).fetchone()
|
|
172
|
+
transcript_row = database.execute(
|
|
173
|
+
"SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=?",
|
|
174
|
+
(version_id, stream_index),
|
|
175
|
+
).fetchone() if stream_index >= 0 else None
|
|
176
|
+
response = self._public(
|
|
177
|
+
material_row, transcript_row, version_id, stream_index,
|
|
178
|
+
self._current_transcript_revision(database, version_id, stream_index),
|
|
179
|
+
annotation_suggestion(database, version_id),
|
|
180
|
+
)
|
|
181
|
+
database.execute(
|
|
182
|
+
"INSERT INTO annotation_command_receipts "
|
|
183
|
+
"(request_id,command_type,request_hash,response_json,created_at) "
|
|
184
|
+
"VALUES(?,'save_annotation',?,?,?)",
|
|
185
|
+
(
|
|
186
|
+
normalized_request, request_hash,
|
|
187
|
+
json.dumps(response, ensure_ascii=False, sort_keys=True, separators=(",", ":")),
|
|
188
|
+
now,
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
database.commit()
|
|
192
|
+
return response
|
|
193
|
+
except ProjectError:
|
|
194
|
+
raise
|
|
195
|
+
except (json.JSONDecodeError, TypeError, ValueError) as error:
|
|
196
|
+
raise ProjectError(
|
|
197
|
+
"annotation_invalid", "素材標註內容無效。", status_code=422
|
|
198
|
+
) from error
|
|
199
|
+
except sqlite3.Error as error:
|
|
200
|
+
raise ProjectError(
|
|
201
|
+
"storage_failed", "Clipen 無法保存素材標註。", status_code=500
|
|
202
|
+
) from error
|
|
203
|
+
|
|
204
|
+
@staticmethod
|
|
205
|
+
def _validate_identity(version_id: str, stream_index: int) -> None:
|
|
206
|
+
if not isinstance(version_id, str) or _VERSION_ID.fullmatch(version_id) is None:
|
|
207
|
+
raise ProjectError("annotation_not_found", "找不到這個素材。", status_code=404)
|
|
208
|
+
if isinstance(stream_index, bool) or not isinstance(stream_index, int) or stream_index < -1:
|
|
209
|
+
raise ProjectError("annotation_not_found", "找不到這個素材。", status_code=404)
|
|
210
|
+
|
|
211
|
+
@staticmethod
|
|
212
|
+
def _expected_revision(value: object) -> int:
|
|
213
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
214
|
+
raise ProjectError("annotation_invalid", "素材標註版本無效。", status_code=422)
|
|
215
|
+
return value
|
|
216
|
+
|
|
217
|
+
@staticmethod
|
|
218
|
+
def _material(value: object) -> dict[str, object]:
|
|
219
|
+
if not isinstance(value, Mapping) or set(value) != {"people", "location", "trip_day", "day_part", "note", "usage"}:
|
|
220
|
+
raise ProjectError("annotation_invalid", "素材標註內容無效。", status_code=422)
|
|
221
|
+
people = value["people"]
|
|
222
|
+
if not isinstance(people, list) or len(people) > 20:
|
|
223
|
+
raise ProjectError("annotation_invalid", "人物標註內容無效。", status_code=422)
|
|
224
|
+
normalized_people = []
|
|
225
|
+
for person in people:
|
|
226
|
+
if not isinstance(person, str) or not person.strip() or "\x00" in person or len(person.strip()) > 80:
|
|
227
|
+
raise ProjectError("annotation_invalid", "人物標註內容無效。", status_code=422)
|
|
228
|
+
normalized_people.append(person.strip())
|
|
229
|
+
if len(normalized_people) != len(set(normalized_people)):
|
|
230
|
+
raise ProjectError("annotation_invalid", "人物標註不能重複。", status_code=422)
|
|
231
|
+
location = value["location"]
|
|
232
|
+
note = value["note"]
|
|
233
|
+
if location is not None and (not isinstance(location, str) or "\x00" in location or len(location.strip()) > 160):
|
|
234
|
+
raise ProjectError("annotation_invalid", "地點標註內容無效。", status_code=422)
|
|
235
|
+
if not isinstance(note, str) or "\x00" in note or len(note) > 2_000:
|
|
236
|
+
raise ProjectError("annotation_invalid", "剪輯備註內容無效。", status_code=422)
|
|
237
|
+
trip_day = value["trip_day"]
|
|
238
|
+
if trip_day is not None and (isinstance(trip_day, bool) or not isinstance(trip_day, int) or not 1 <= trip_day <= 365):
|
|
239
|
+
raise ProjectError("annotation_invalid", "旅程日次無效。", status_code=422)
|
|
240
|
+
day_part = value["day_part"]
|
|
241
|
+
usage = value["usage"]
|
|
242
|
+
try:
|
|
243
|
+
if day_part is not None:
|
|
244
|
+
day_part = DayPart(day_part).value
|
|
245
|
+
usage = MaterialUsage(usage).value
|
|
246
|
+
except (TypeError, ValueError) as error:
|
|
247
|
+
raise ProjectError(
|
|
248
|
+
"annotation_invalid", "素材使用方式或旅程時段無效。", status_code=422
|
|
249
|
+
) from error
|
|
250
|
+
return {
|
|
251
|
+
"people": normalized_people,
|
|
252
|
+
"location": None if location is None or not location.strip() else location.strip(),
|
|
253
|
+
"trip_day": trip_day,
|
|
254
|
+
"day_part": day_part,
|
|
255
|
+
"note": note.strip(),
|
|
256
|
+
"usage": usage,
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
@staticmethod
|
|
260
|
+
def _transcript(value: object, stream_index: int) -> dict[str, object] | None:
|
|
261
|
+
if value is None:
|
|
262
|
+
return None
|
|
263
|
+
if stream_index < 0 or not isinstance(value, Mapping) or set(value) != {"source_revision_id", "confirmed", "discarded", "corrections"}:
|
|
264
|
+
raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
|
|
265
|
+
source_revision = value["source_revision_id"]
|
|
266
|
+
confirmed = value["confirmed"]
|
|
267
|
+
discarded = value["discarded"]
|
|
268
|
+
corrections = value["corrections"]
|
|
269
|
+
if not isinstance(source_revision, str) or not source_revision or not isinstance(confirmed, bool) or not isinstance(discarded, bool) or not isinstance(corrections, list) or len(corrections) > 1_000:
|
|
270
|
+
raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
|
|
271
|
+
normalized = []
|
|
272
|
+
ordinals = set()
|
|
273
|
+
for correction in corrections:
|
|
274
|
+
if not isinstance(correction, Mapping) or set(correction) != {"ordinal", "text"}:
|
|
275
|
+
raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
|
|
276
|
+
ordinal = correction["ordinal"]
|
|
277
|
+
text = correction["text"]
|
|
278
|
+
if isinstance(ordinal, bool) or not isinstance(ordinal, int) or ordinal < 0 or ordinal in ordinals or not isinstance(text, str) or "\x00" in text or len(text) > 1_000:
|
|
279
|
+
raise ProjectError("annotation_invalid", "逐字稿修正內容無效。", status_code=422)
|
|
280
|
+
ordinals.add(ordinal)
|
|
281
|
+
normalized.append({"ordinal": ordinal, "text": text.strip()})
|
|
282
|
+
return {
|
|
283
|
+
"source_revision_id": source_revision,
|
|
284
|
+
"confirmed": False if discarded else confirmed,
|
|
285
|
+
"discarded": discarded,
|
|
286
|
+
"corrections": normalized,
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
@staticmethod
|
|
290
|
+
def _require_version(database: sqlite3.Connection, version_id: str) -> None:
|
|
291
|
+
if database.execute("SELECT 1 FROM asset_versions WHERE version_id=?", (version_id,)).fetchone() is None:
|
|
292
|
+
raise ProjectError("annotation_not_found", "找不到這個素材。", status_code=404)
|
|
293
|
+
|
|
294
|
+
@staticmethod
|
|
295
|
+
def _current_transcript_revision(database: sqlite3.Connection, version_id: str, stream_index: int) -> str | None:
|
|
296
|
+
if stream_index < 0:
|
|
297
|
+
return None
|
|
298
|
+
row = database.execute(
|
|
299
|
+
"SELECT items.transcript_revision_id FROM current_preparation AS current "
|
|
300
|
+
"JOIN preparation_items AS items ON items.run_id=current.run_id "
|
|
301
|
+
"WHERE current.slot=1 AND items.version_id=? AND items.stream_index=? "
|
|
302
|
+
"AND items.status='transcribed'",
|
|
303
|
+
(version_id, stream_index),
|
|
304
|
+
).fetchone()
|
|
305
|
+
return None if row is None else row["transcript_revision_id"]
|
|
306
|
+
|
|
307
|
+
@staticmethod
|
|
308
|
+
def _validate_corrections(database: sqlite3.Connection, revision_id: str, corrections: object) -> None:
|
|
309
|
+
available = {
|
|
310
|
+
row["ordinal"]
|
|
311
|
+
for row in database.execute(
|
|
312
|
+
"SELECT ordinal FROM transcript_segments WHERE revision_id=?", (revision_id,)
|
|
313
|
+
)
|
|
314
|
+
}
|
|
315
|
+
if any(item["ordinal"] not in available for item in corrections):
|
|
316
|
+
raise ProjectError("annotation_transcript_changed", "逐字稿片段已更新,請重新載入。", status_code=409)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@staticmethod
|
|
320
|
+
def _public(
|
|
321
|
+
material,
|
|
322
|
+
transcript,
|
|
323
|
+
version_id: str,
|
|
324
|
+
stream_index: int,
|
|
325
|
+
current_revision: str | None,
|
|
326
|
+
suggestion: dict[str, object],
|
|
327
|
+
) -> dict[str, object]:
|
|
328
|
+
if material is None:
|
|
329
|
+
material_public = {
|
|
330
|
+
"version_id": version_id, "revision": 0, "people": [], "location": None,
|
|
331
|
+
"trip_day": None, "day_part": None, "note": "", "usage": "normal",
|
|
332
|
+
}
|
|
333
|
+
else:
|
|
334
|
+
people = json.loads(material["people_json"])
|
|
335
|
+
try:
|
|
336
|
+
normalized = AnnotationRepository._material({
|
|
337
|
+
"people": people,
|
|
338
|
+
"location": material["location"],
|
|
339
|
+
"trip_day": material["trip_day"],
|
|
340
|
+
"day_part": material["day_part"],
|
|
341
|
+
"note": material["note"],
|
|
342
|
+
"usage": material["usage"],
|
|
343
|
+
})
|
|
344
|
+
except ProjectError as error:
|
|
345
|
+
raise ValueError("stored material annotation is invalid") from error
|
|
346
|
+
if isinstance(material["revision"], bool) or not isinstance(material["revision"], int) or material["revision"] < 1:
|
|
347
|
+
raise ValueError("stored material annotation revision is invalid")
|
|
348
|
+
material_public = {
|
|
349
|
+
"version_id": version_id, "revision": material["revision"], **normalized,
|
|
350
|
+
}
|
|
351
|
+
transcript_public = None
|
|
352
|
+
if current_revision is not None:
|
|
353
|
+
stale = transcript is not None and transcript["source_revision_id"] != current_revision
|
|
354
|
+
corrections = [] if transcript is None or stale else json.loads(transcript["corrections_json"])
|
|
355
|
+
if transcript is not None and not stale:
|
|
356
|
+
try:
|
|
357
|
+
normalized_transcript = AnnotationRepository._transcript({
|
|
358
|
+
"source_revision_id": current_revision,
|
|
359
|
+
"confirmed": bool(transcript["confirmed"]),
|
|
360
|
+
"discarded": bool(transcript["discarded"]),
|
|
361
|
+
"corrections": corrections,
|
|
362
|
+
}, stream_index)
|
|
363
|
+
except ProjectError as error:
|
|
364
|
+
raise ValueError("stored transcript annotation is invalid") from error
|
|
365
|
+
assert normalized_transcript is not None
|
|
366
|
+
corrections = normalized_transcript["corrections"]
|
|
367
|
+
transcript_public = {
|
|
368
|
+
"stream_index": stream_index,
|
|
369
|
+
"revision": 0 if transcript is None else transcript["revision"],
|
|
370
|
+
"source_revision_id": current_revision,
|
|
371
|
+
"confirmed": False if transcript is None or stale else bool(transcript["confirmed"]),
|
|
372
|
+
"discarded": False if transcript is None else bool(transcript["discarded"]),
|
|
373
|
+
"corrections": corrections,
|
|
374
|
+
"stale": stale,
|
|
375
|
+
}
|
|
376
|
+
return {
|
|
377
|
+
"material": material_public,
|
|
378
|
+
"transcript": transcript_public,
|
|
379
|
+
"suggestion": suggestion,
|
|
380
|
+
}
|