@clipen/clipen-cli 0.0.0-stage → 1.0.1
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 +89 -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 +55 -4
- package/pyproject.toml +44 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/dev.txt +2 -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 +410 -0
- package/src/clipen/analysis/audio.py +394 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +929 -0
- package/src/clipen/analysis/image_similarity.py +134 -0
- package/src/clipen/analysis/keyframes.py +159 -0
- package/src/clipen/analysis/models.py +228 -0
- package/src/clipen/analysis/qwen_worker.py +594 -0
- package/src/clipen/analysis/resources.py +22 -0
- package/src/clipen/analysis/runtime.py +62 -0
- package/src/clipen/analysis/service.py +594 -0
- package/src/clipen/analysis/setup.py +921 -0
- package/src/clipen/analysis/setup_cli.py +107 -0
- package/src/clipen/analysis/storage.py +1864 -0
- package/src/clipen/analysis/transcription.py +906 -0
- package/src/clipen/analysis/visual.py +237 -0
- package/src/clipen/annotations/__init__.py +13 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +428 -0
- package/src/clipen/annotations/suggestions.py +115 -0
- package/src/clipen/asr_release.py +132 -0
- package/src/clipen/bootstrap.py +978 -0
- package/src/clipen/candidates.py +222 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1657 -0
- package/src/clipen/controller/server.py +533 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +110 -0
- package/src/clipen/domain/timeline.py +582 -0
- package/src/clipen/domain/validation.py +14 -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 +127 -0
- package/src/clipen/editing/agent_repository.py +978 -0
- package/src/clipen/editing/agent_tools.py +613 -0
- package/src/clipen/editing/alignment.py +150 -0
- package/src/clipen/editing/alignment_setup.py +156 -0
- package/src/clipen/editing/alignment_worker.py +24 -0
- package/src/clipen/editing/change_report.py +128 -0
- package/src/clipen/editing/compiler.py +40 -0
- package/src/clipen/editing/component_looks.py +131 -0
- package/src/clipen/editing/component_review.py +74 -0
- package/src/clipen/editing/coordinator.py +497 -0
- package/src/clipen/editing/editorial_review.py +309 -0
- package/src/clipen/editing/evidence_jobs.py +552 -0
- package/src/clipen/editing/history_changes.py +192 -0
- package/src/clipen/editing/music_choices.py +18 -0
- package/src/clipen/editing/production_catalog.py +629 -0
- package/src/clipen/editing/production_limits.py +85 -0
- package/src/clipen/editing/production_media.py +435 -0
- package/src/clipen/editing/production_preview.py +373 -0
- package/src/clipen/editing/production_progress.py +236 -0
- package/src/clipen/editing/production_requirements.py +117 -0
- package/src/clipen/editing/production_tools.py +1198 -0
- package/src/clipen/editing/program_audio.py +248 -0
- package/src/clipen/editing/program_direction.py +83 -0
- package/src/clipen/editing/program_story.py +91 -0
- package/src/clipen/editing/program_subtitles.py +232 -0
- package/src/clipen/editing/programme_review.py +121 -0
- package/src/clipen/editing/prompt_history.py +84 -0
- package/src/clipen/editing/recut.py +167 -0
- package/src/clipen/editing/refinement_references.py +278 -0
- package/src/clipen/editing/resolve_export.py +847 -0
- package/src/clipen/editing/resolve_titles.py +291 -0
- package/src/clipen/editing/skill_tools.py +951 -0
- package/src/clipen/editing/source_dialogue.py +192 -0
- package/src/clipen/editing/speech_coverage.py +50 -0
- package/src/clipen/editing/speech_quality.py +11 -0
- package/src/clipen/editing/tool_receipts.py +98 -0
- package/src/clipen/editing/versions.py +219 -0
- package/src/clipen/editing/visual_preview.py +189 -0
- package/src/clipen/editing/workbench.py +136 -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 +188 -0
- package/src/clipen/finishing/catalog.py +264 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +45 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +42 -0
- package/src/clipen/mcp_editing/server.py +396 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +253 -0
- package/src/clipen/media/models.py +349 -0
- package/src/clipen/media/preview.py +137 -0
- package/src/clipen/media/probe.py +418 -0
- package/src/clipen/media/service.py +304 -0
- package/src/clipen/media/storage.py +694 -0
- package/src/clipen/music_vocabulary.py +34 -0
- package/src/clipen/power.py +28 -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 +256 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +36 -0
- package/src/clipen/projects/models.py +189 -0
- package/src/clipen/projects/picker.py +232 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +159 -0
- package/src/clipen/projects/storage.py +1458 -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 +77 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +245 -0
- package/src/clipen/providers/claude.py +409 -0
- package/src/clipen/providers/claude_editing.py +118 -0
- package/src/clipen/providers/codex.py +991 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +567 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +269 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +139 -0
- package/src/clipen/rendering/custom_components.py +328 -0
- package/src/clipen/rendering/custom_render.py +218 -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 +96 -0
- package/src/clipen/rendering/program_components.py +254 -0
- package/src/clipen/rendering/program_creator.py +804 -0
- package/src/clipen/rendering/program_identities.py +350 -0
- package/src/clipen/rendering/program_motion.py +186 -0
- package/src/clipen/rendering/program_studio.py +227 -0
- package/src/clipen/rendering/program_styles.py +321 -0
- package/src/clipen/rendering/program_subtitles.py +89 -0
- package/src/clipen/rendering/renderer.py +737 -0
- package/src/clipen/rendering/storage.py +230 -0
- package/src/clipen/rendering/titles.py +467 -0
- package/src/clipen/skills/__init__.py +5 -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 +314 -0
- package/src/clipen/skills/library.py +137 -0
- package/src/clipen/skills/package.py +254 -0
- package/src/clipen/skills/visual_styles.py +55 -0
- package/src/clipen/workspace.py +181 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Read-only, range-capable access to user-authorized source media."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import mimetypes
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sqlite3
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path, PurePosixPath
|
|
12
|
+
from typing import Iterator
|
|
13
|
+
|
|
14
|
+
from clipen.projects import DirectoryRole, ProjectError, ProjectRepository
|
|
15
|
+
from clipen.projects.models import validate_project_id
|
|
16
|
+
|
|
17
|
+
from .discovery import DiscoveryError, open_file_beneath
|
|
18
|
+
from .models import InventoryRoot
|
|
19
|
+
|
|
20
|
+
_VERSION_ID = re.compile(r"av_[0-9a-f]{32}\Z")
|
|
21
|
+
_VIDEO_TYPES = {".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime"}
|
|
22
|
+
_AUDIO_TYPES = {".m4a": "audio/mp4", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".aac": "audio/aac"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class MediaPreview:
|
|
27
|
+
descriptor: int
|
|
28
|
+
size: int
|
|
29
|
+
media_type: str
|
|
30
|
+
audio_stream_indices: tuple[int, ...] = ()
|
|
31
|
+
video_stream_indices: tuple[int, ...] = ()
|
|
32
|
+
|
|
33
|
+
def chunks(self, start: int, end: int, chunk_size: int = 1024 * 1024) -> Iterator[bytes]:
|
|
34
|
+
position = start
|
|
35
|
+
try:
|
|
36
|
+
while position <= end:
|
|
37
|
+
chunk = os.pread(self.descriptor, min(chunk_size, end - position + 1), position)
|
|
38
|
+
if not chunk:
|
|
39
|
+
break
|
|
40
|
+
position += len(chunk)
|
|
41
|
+
yield chunk
|
|
42
|
+
finally:
|
|
43
|
+
os.close(self.descriptor)
|
|
44
|
+
|
|
45
|
+
def close(self) -> None:
|
|
46
|
+
os.close(self.descriptor)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class MediaPreviewRepository:
|
|
50
|
+
def __init__(self, projects: ProjectRepository) -> None:
|
|
51
|
+
self.projects = projects
|
|
52
|
+
|
|
53
|
+
def locate(self, project_id: str, version_id: str) -> tuple[Path, dict[int, dict]]:
|
|
54
|
+
"""The unchanged source file on disk and its probed streams, for handing to another editor."""
|
|
55
|
+
self.open(project_id, version_id).close()
|
|
56
|
+
with self.projects.connect(project_id) as database:
|
|
57
|
+
row = database.execute(
|
|
58
|
+
"SELECT assets.relative_path,directories.canonical_path FROM asset_versions AS versions "
|
|
59
|
+
"JOIN assets ON assets.asset_id=versions.asset_id "
|
|
60
|
+
"JOIN project_directories AS directories ON directories.role=assets.role "
|
|
61
|
+
"WHERE versions.version_id=? AND assets.project_id=?",
|
|
62
|
+
(version_id, project_id),
|
|
63
|
+
).fetchone()
|
|
64
|
+
streams = database.execute(
|
|
65
|
+
"SELECT stream_index,kind,details_json FROM media_streams WHERE version_id=?",
|
|
66
|
+
(version_id,),
|
|
67
|
+
).fetchall()
|
|
68
|
+
path = Path(row["canonical_path"]).joinpath(*PurePosixPath(row["relative_path"]).parts)
|
|
69
|
+
return path, {
|
|
70
|
+
stream["stream_index"]: {**json.loads(stream["details_json"]), "kind": stream["kind"]} for stream in streams
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
def open(self, project_id: str, version_id: str) -> MediaPreview:
|
|
74
|
+
validate_project_id(project_id)
|
|
75
|
+
if not isinstance(version_id, str) or _VERSION_ID.fullmatch(version_id) is None:
|
|
76
|
+
raise ProjectError("media_not_found", "找不到這個素材。", status_code=404)
|
|
77
|
+
try:
|
|
78
|
+
with self.projects.connect(project_id) as database:
|
|
79
|
+
row = database.execute(
|
|
80
|
+
"SELECT assets.role,assets.relative_path,versions.size_bytes,versions.mtime_ns,"
|
|
81
|
+
"directories.canonical_path,directories.device,directories.inode,directories.saved_at "
|
|
82
|
+
"FROM asset_versions AS versions "
|
|
83
|
+
"JOIN assets ON assets.asset_id=versions.asset_id "
|
|
84
|
+
"JOIN project_directories AS directories ON directories.role=assets.role "
|
|
85
|
+
"WHERE versions.version_id=? AND assets.project_id=?",
|
|
86
|
+
(version_id, project_id),
|
|
87
|
+
).fetchone()
|
|
88
|
+
streams = database.execute(
|
|
89
|
+
"SELECT stream_index,kind,details_json FROM media_streams WHERE version_id=? ORDER BY stream_index",
|
|
90
|
+
(version_id,),
|
|
91
|
+
).fetchall()
|
|
92
|
+
if row is None:
|
|
93
|
+
raise ProjectError("media_not_found", "找不到這個素材。", status_code=404)
|
|
94
|
+
audio_stream_indices = tuple(stream["stream_index"] for stream in streams if stream["kind"] == "audio")
|
|
95
|
+
video_streams = [stream for stream in streams if stream["kind"] == "video"]
|
|
96
|
+
primary_video_streams = tuple(
|
|
97
|
+
stream["stream_index"]
|
|
98
|
+
for stream in video_streams
|
|
99
|
+
if not json.loads(stream["details_json"]).get("attached_pic", False)
|
|
100
|
+
)
|
|
101
|
+
video_stream_indices = primary_video_streams or tuple(stream["stream_index"] for stream in video_streams)
|
|
102
|
+
root = InventoryRoot(
|
|
103
|
+
DirectoryRole(row["role"]),
|
|
104
|
+
row["canonical_path"],
|
|
105
|
+
row["device"],
|
|
106
|
+
row["inode"],
|
|
107
|
+
row["saved_at"],
|
|
108
|
+
)
|
|
109
|
+
descriptor = open_file_beneath(root, row["relative_path"])
|
|
110
|
+
details = os.fstat(descriptor)
|
|
111
|
+
if details.st_size != row["size_bytes"] or details.st_mtime_ns != row["mtime_ns"]:
|
|
112
|
+
os.close(descriptor)
|
|
113
|
+
raise ProjectError("media_changed", "素材已變更,請重新檢查素材。", status_code=409)
|
|
114
|
+
suffix = PurePosixPath(row["relative_path"]).suffix.lower()
|
|
115
|
+
media_type = _VIDEO_TYPES.get(suffix) or _AUDIO_TYPES.get(suffix)
|
|
116
|
+
if media_type is None:
|
|
117
|
+
media_type = mimetypes.guess_type(row["relative_path"])[0]
|
|
118
|
+
if media_type is None or not media_type.startswith(("video/", "audio/")):
|
|
119
|
+
os.close(descriptor)
|
|
120
|
+
raise ProjectError(
|
|
121
|
+
"media_preview_unsupported",
|
|
122
|
+
"這個素材無法在瀏覽器中直接播放。",
|
|
123
|
+
status_code=415,
|
|
124
|
+
)
|
|
125
|
+
return MediaPreview(
|
|
126
|
+
descriptor,
|
|
127
|
+
details.st_size,
|
|
128
|
+
media_type,
|
|
129
|
+
audio_stream_indices,
|
|
130
|
+
video_stream_indices,
|
|
131
|
+
)
|
|
132
|
+
except ProjectError:
|
|
133
|
+
raise
|
|
134
|
+
except DiscoveryError as error:
|
|
135
|
+
raise ProjectError("media_offline", "目前無法讀取素材,請確認外接硬碟已連接。", status_code=409) from error
|
|
136
|
+
except (json.JSONDecodeError, OSError, sqlite3.Error, TypeError, ValueError) as error:
|
|
137
|
+
raise ProjectError("media_unavailable", "Clipen 無法安全開啟這個素材。", status_code=500) from error
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Bounded ffprobe adapter operating on already-open regular file descriptors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import signal
|
|
11
|
+
import stat
|
|
12
|
+
import subprocess
|
|
13
|
+
import tempfile
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from decimal import Decimal, InvalidOperation
|
|
18
|
+
from fractions import Fraction
|
|
19
|
+
from typing import Any, Mapping
|
|
20
|
+
|
|
21
|
+
from .discovery import DiscoveredAsset, DiscoveryError, open_file_beneath
|
|
22
|
+
from .models import AssetKind, InventoryRoot, MediaStream
|
|
23
|
+
|
|
24
|
+
_MAX_CAPTURE_BYTES = 4 * 1024 * 1024
|
|
25
|
+
_MAX_STREAMS = 64
|
|
26
|
+
_POLL_SECONDS = 0.05
|
|
27
|
+
_CODEC = re.compile(r"[A-Za-z0-9_.-]{1,80}\Z")
|
|
28
|
+
_CAPTURE_TIME = re.compile(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:?\d{2})?\Z")
|
|
29
|
+
_ISO6709 = re.compile(r"([+-]\d{2,3}(?:\.\d+)?)([+-]\d{3}(?:\.\d+)?)(?:[+-]\d+(?:\.\d+)?)?/?\Z")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MediaProbeError(RuntimeError):
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
code: str,
|
|
36
|
+
*,
|
|
37
|
+
fingerprint: str | None = None,
|
|
38
|
+
size_bytes: int | None = None,
|
|
39
|
+
mtime_ns: int | None = None,
|
|
40
|
+
) -> None:
|
|
41
|
+
super().__init__(code)
|
|
42
|
+
self.code = code
|
|
43
|
+
self.fingerprint = fingerprint
|
|
44
|
+
self.size_bytes = size_bytes
|
|
45
|
+
self.mtime_ns = mtime_ns
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def has_version(self) -> bool:
|
|
49
|
+
return all(value is not None for value in (self.fingerprint, self.size_bytes, self.mtime_ns))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class MediaProbeResult:
|
|
54
|
+
kind: AssetKind
|
|
55
|
+
fingerprint: str
|
|
56
|
+
size_bytes: int
|
|
57
|
+
mtime_ns: int
|
|
58
|
+
summary: Mapping[str, object]
|
|
59
|
+
streams: tuple[MediaStream, ...]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FFprobeAdapter:
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
executable: str | None = None,
|
|
66
|
+
*,
|
|
67
|
+
timeout_seconds: float = 30,
|
|
68
|
+
) -> None:
|
|
69
|
+
resolved = executable or shutil.which("ffprobe")
|
|
70
|
+
if not resolved or not os.path.isabs(resolved):
|
|
71
|
+
raise MediaProbeError("probe_unavailable")
|
|
72
|
+
resolved = os.path.realpath(resolved)
|
|
73
|
+
if not os.path.isfile(resolved) or not os.access(resolved, os.X_OK):
|
|
74
|
+
raise MediaProbeError("probe_unavailable")
|
|
75
|
+
if timeout_seconds <= 0:
|
|
76
|
+
raise ValueError("ffprobe timeout must be positive")
|
|
77
|
+
self.executable = resolved
|
|
78
|
+
self.timeout_seconds = timeout_seconds
|
|
79
|
+
|
|
80
|
+
def version(self) -> str:
|
|
81
|
+
stdout, _, returncode = self._run((self.executable, "-version"), ())
|
|
82
|
+
if returncode != 0:
|
|
83
|
+
raise MediaProbeError("probe_unavailable")
|
|
84
|
+
first = stdout.decode("utf-8", "replace").splitlines()
|
|
85
|
+
if not first or not first[0].startswith("ffprobe version "):
|
|
86
|
+
raise MediaProbeError("probe_unsupported")
|
|
87
|
+
return first[0][:240]
|
|
88
|
+
|
|
89
|
+
def probe(
|
|
90
|
+
self,
|
|
91
|
+
root: InventoryRoot,
|
|
92
|
+
asset: DiscoveredAsset,
|
|
93
|
+
cancel: threading.Event | None = None,
|
|
94
|
+
) -> MediaProbeResult:
|
|
95
|
+
if not asset.should_probe:
|
|
96
|
+
raise ValueError("only recognized regular media can be probed")
|
|
97
|
+
try:
|
|
98
|
+
descriptor = open_file_beneath(root, asset.relative_path)
|
|
99
|
+
except DiscoveryError as error:
|
|
100
|
+
raise MediaProbeError(error.code) from error
|
|
101
|
+
try:
|
|
102
|
+
before = os.fstat(descriptor)
|
|
103
|
+
if not stat.S_ISREG(before.st_mode):
|
|
104
|
+
raise MediaProbeError("entry_not_regular")
|
|
105
|
+
if before.st_size != asset.size_bytes or before.st_mtime_ns != asset.mtime_ns:
|
|
106
|
+
raise MediaProbeError("changed")
|
|
107
|
+
fingerprint = bounded_file_fingerprint(descriptor, before.st_size)
|
|
108
|
+
command = (
|
|
109
|
+
self.executable,
|
|
110
|
+
"-v",
|
|
111
|
+
"error",
|
|
112
|
+
"-show_format",
|
|
113
|
+
"-show_streams",
|
|
114
|
+
"-of",
|
|
115
|
+
"json",
|
|
116
|
+
f"/dev/fd/{descriptor}",
|
|
117
|
+
)
|
|
118
|
+
try:
|
|
119
|
+
stdout, _, returncode = self._run(command, (descriptor,), cancel)
|
|
120
|
+
except MediaProbeError as error:
|
|
121
|
+
raise MediaProbeError(
|
|
122
|
+
error.code,
|
|
123
|
+
fingerprint=fingerprint,
|
|
124
|
+
size_bytes=before.st_size,
|
|
125
|
+
mtime_ns=before.st_mtime_ns,
|
|
126
|
+
) from error
|
|
127
|
+
after = os.fstat(descriptor)
|
|
128
|
+
if (
|
|
129
|
+
before.st_dev,
|
|
130
|
+
before.st_ino,
|
|
131
|
+
before.st_size,
|
|
132
|
+
before.st_mtime_ns,
|
|
133
|
+
) != (
|
|
134
|
+
after.st_dev,
|
|
135
|
+
after.st_ino,
|
|
136
|
+
after.st_size,
|
|
137
|
+
after.st_mtime_ns,
|
|
138
|
+
):
|
|
139
|
+
raise MediaProbeError(
|
|
140
|
+
"changed",
|
|
141
|
+
fingerprint=fingerprint,
|
|
142
|
+
size_bytes=before.st_size,
|
|
143
|
+
mtime_ns=before.st_mtime_ns,
|
|
144
|
+
)
|
|
145
|
+
if fingerprint != bounded_file_fingerprint(descriptor, after.st_size):
|
|
146
|
+
raise MediaProbeError(
|
|
147
|
+
"changed",
|
|
148
|
+
fingerprint=fingerprint,
|
|
149
|
+
size_bytes=before.st_size,
|
|
150
|
+
mtime_ns=before.st_mtime_ns,
|
|
151
|
+
)
|
|
152
|
+
if returncode != 0:
|
|
153
|
+
raise MediaProbeError(
|
|
154
|
+
"unreadable",
|
|
155
|
+
fingerprint=fingerprint,
|
|
156
|
+
size_bytes=before.st_size,
|
|
157
|
+
mtime_ns=before.st_mtime_ns,
|
|
158
|
+
)
|
|
159
|
+
try:
|
|
160
|
+
summary, streams = _parse_probe(stdout, asset.kind)
|
|
161
|
+
except MediaProbeError as error:
|
|
162
|
+
raise MediaProbeError(
|
|
163
|
+
error.code,
|
|
164
|
+
fingerprint=fingerprint,
|
|
165
|
+
size_bytes=before.st_size,
|
|
166
|
+
mtime_ns=before.st_mtime_ns,
|
|
167
|
+
) from error
|
|
168
|
+
return MediaProbeResult(
|
|
169
|
+
asset.kind,
|
|
170
|
+
fingerprint,
|
|
171
|
+
before.st_size,
|
|
172
|
+
before.st_mtime_ns,
|
|
173
|
+
summary,
|
|
174
|
+
streams,
|
|
175
|
+
)
|
|
176
|
+
finally:
|
|
177
|
+
os.close(descriptor)
|
|
178
|
+
|
|
179
|
+
def _run(
|
|
180
|
+
self,
|
|
181
|
+
command: tuple[str, ...],
|
|
182
|
+
pass_fds: tuple[int, ...],
|
|
183
|
+
cancel: threading.Event | None = None,
|
|
184
|
+
) -> tuple[bytes, bytes, int]:
|
|
185
|
+
deadline = time.monotonic() + self.timeout_seconds
|
|
186
|
+
with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:
|
|
187
|
+
try:
|
|
188
|
+
process = subprocess.Popen(
|
|
189
|
+
command,
|
|
190
|
+
cwd="/",
|
|
191
|
+
env={"LANG": "C", "LC_ALL": "C"},
|
|
192
|
+
stdin=subprocess.DEVNULL,
|
|
193
|
+
stdout=stdout_file,
|
|
194
|
+
stderr=stderr_file,
|
|
195
|
+
pass_fds=pass_fds,
|
|
196
|
+
start_new_session=os.name == "posix",
|
|
197
|
+
)
|
|
198
|
+
except OSError as error:
|
|
199
|
+
raise MediaProbeError("probe_unavailable") from error
|
|
200
|
+
while process.poll() is None:
|
|
201
|
+
if cancel is not None and cancel.is_set():
|
|
202
|
+
_terminate(process)
|
|
203
|
+
raise MediaProbeError("cancelled")
|
|
204
|
+
if time.monotonic() >= deadline:
|
|
205
|
+
_terminate(process)
|
|
206
|
+
raise MediaProbeError("timeout")
|
|
207
|
+
if (
|
|
208
|
+
os.fstat(stdout_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
209
|
+
or os.fstat(stderr_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
210
|
+
):
|
|
211
|
+
_terminate(process)
|
|
212
|
+
raise MediaProbeError("probe_output_too_large")
|
|
213
|
+
time.sleep(_POLL_SECONDS)
|
|
214
|
+
if (
|
|
215
|
+
os.fstat(stdout_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
216
|
+
or os.fstat(stderr_file.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
217
|
+
):
|
|
218
|
+
raise MediaProbeError("probe_output_too_large")
|
|
219
|
+
stdout_file.seek(0)
|
|
220
|
+
stderr_file.seek(0)
|
|
221
|
+
return stdout_file.read(), stderr_file.read(), process.returncode
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def bounded_file_fingerprint(descriptor: int, size: int) -> str:
|
|
225
|
+
chunk_size = 64 * 1024
|
|
226
|
+
first = os.pread(descriptor, min(size, chunk_size), 0)
|
|
227
|
+
last_offset = max(0, size - chunk_size)
|
|
228
|
+
last = os.pread(descriptor, min(size, chunk_size), last_offset)
|
|
229
|
+
digest = hashlib.sha256()
|
|
230
|
+
digest.update(b"clipen-bounded-file-fingerprint-v1\0")
|
|
231
|
+
digest.update(str(size).encode("ascii"))
|
|
232
|
+
digest.update(b"\0")
|
|
233
|
+
digest.update(first)
|
|
234
|
+
digest.update(b"\0")
|
|
235
|
+
digest.update(last)
|
|
236
|
+
return digest.hexdigest()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _parse_probe(raw: bytes, expected_kind: AssetKind) -> tuple[dict[str, object], tuple[MediaStream, ...]]:
|
|
240
|
+
try:
|
|
241
|
+
value = json.loads(raw.decode("utf-8"))
|
|
242
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
243
|
+
raise MediaProbeError("invalid_probe_output") from error
|
|
244
|
+
allowed_top_level = {"format", "streams", "chapters", "programs", "stream_groups"}
|
|
245
|
+
if not isinstance(value, dict) or set(value) - allowed_top_level:
|
|
246
|
+
raise MediaProbeError("invalid_probe_output")
|
|
247
|
+
raw_streams = value.get("streams", [])
|
|
248
|
+
if not isinstance(raw_streams, list) or len(raw_streams) > _MAX_STREAMS:
|
|
249
|
+
raise MediaProbeError("invalid_probe_output")
|
|
250
|
+
streams: list[MediaStream] = []
|
|
251
|
+
for raw_stream in raw_streams:
|
|
252
|
+
if not isinstance(raw_stream, dict):
|
|
253
|
+
raise MediaProbeError("invalid_probe_output")
|
|
254
|
+
kind = raw_stream.get("codec_type")
|
|
255
|
+
if kind not in {"video", "audio"}:
|
|
256
|
+
continue
|
|
257
|
+
index = _integer(raw_stream.get("index"), minimum=0, maximum=4096)
|
|
258
|
+
codec = raw_stream.get("codec_name")
|
|
259
|
+
if not isinstance(codec, str) or _CODEC.fullmatch(codec) is None:
|
|
260
|
+
raise MediaProbeError("invalid_probe_output")
|
|
261
|
+
details: dict[str, object] = {}
|
|
262
|
+
disposition = raw_stream.get("disposition", {})
|
|
263
|
+
if isinstance(disposition, dict):
|
|
264
|
+
details["attached_pic"] = disposition.get("attached_pic") == 1
|
|
265
|
+
details["timed_thumbnails"] = disposition.get("timed_thumbnails") == 1
|
|
266
|
+
for key in ("time_base", "avg_frame_rate", "r_frame_rate"):
|
|
267
|
+
candidate = raw_stream.get(key)
|
|
268
|
+
if candidate not in (None, "0/0"):
|
|
269
|
+
details[key] = _fraction(candidate, positive=True)
|
|
270
|
+
for key in ("start_pts", "duration_ts"):
|
|
271
|
+
candidate = raw_stream.get(key)
|
|
272
|
+
if candidate is not None:
|
|
273
|
+
details[key] = str(_integer(candidate, minimum=-(2**63), maximum=2**63 - 1))
|
|
274
|
+
if kind == "video":
|
|
275
|
+
details["width"] = _integer(raw_stream.get("width"), minimum=1, maximum=131_072)
|
|
276
|
+
details["height"] = _integer(raw_stream.get("height"), minimum=1, maximum=131_072)
|
|
277
|
+
rotation = _rotation(raw_stream)
|
|
278
|
+
if rotation is not None:
|
|
279
|
+
details["rotation"] = rotation
|
|
280
|
+
for key in ("color_space", "color_transfer", "color_primaries", "color_range"):
|
|
281
|
+
candidate = raw_stream.get(key)
|
|
282
|
+
if isinstance(candidate, str) and 1 <= len(candidate) <= 80:
|
|
283
|
+
details[key] = candidate
|
|
284
|
+
else:
|
|
285
|
+
details["sample_rate"] = _integer(raw_stream.get("sample_rate"), minimum=1, maximum=768_000)
|
|
286
|
+
details["channels"] = _integer(raw_stream.get("channels"), minimum=1, maximum=64)
|
|
287
|
+
streams.append(MediaStream(index, kind, codec, details))
|
|
288
|
+
if not streams:
|
|
289
|
+
raise MediaProbeError("unsupported")
|
|
290
|
+
if expected_kind is AssetKind.AUDIO and not any(stream.kind == "audio" for stream in streams):
|
|
291
|
+
raise MediaProbeError("unsupported")
|
|
292
|
+
if expected_kind in {AssetKind.VIDEO, AssetKind.IMAGE} and not any(stream.kind == "video" for stream in streams):
|
|
293
|
+
raise MediaProbeError("unsupported")
|
|
294
|
+
raw_format = value.get("format", {})
|
|
295
|
+
if not isinstance(raw_format, dict):
|
|
296
|
+
raise MediaProbeError("invalid_probe_output")
|
|
297
|
+
summary: dict[str, object] = {}
|
|
298
|
+
format_name = raw_format.get("format_name")
|
|
299
|
+
if isinstance(format_name, str) and 1 <= len(format_name) <= 240:
|
|
300
|
+
summary["format_names"] = [part for part in format_name.split(",") if part][:16]
|
|
301
|
+
for source, target in (("duration", "duration_seconds"), ("start_time", "start_seconds")):
|
|
302
|
+
candidate = raw_format.get(source)
|
|
303
|
+
if candidate not in (None, "N/A"):
|
|
304
|
+
summary[target] = _decimal(candidate, non_negative=(source == "duration"))
|
|
305
|
+
bit_rate = raw_format.get("bit_rate")
|
|
306
|
+
if bit_rate not in (None, "N/A"):
|
|
307
|
+
summary["bit_rate"] = _integer(bit_rate, minimum=0, maximum=10**13)
|
|
308
|
+
tags = []
|
|
309
|
+
if isinstance(raw_format.get("tags"), dict):
|
|
310
|
+
tags.append(raw_format["tags"])
|
|
311
|
+
for raw_stream in raw_streams:
|
|
312
|
+
if isinstance(raw_stream, dict) and isinstance(raw_stream.get("tags"), dict):
|
|
313
|
+
tags.append(raw_stream["tags"])
|
|
314
|
+
capture_time = _metadata_value(tags, ("creation_time", "com.apple.quicktime.creationdate"), 80)
|
|
315
|
+
if capture_time is not None and _CAPTURE_TIME.fullmatch(capture_time):
|
|
316
|
+
summary["capture_time"] = capture_time
|
|
317
|
+
location = _metadata_value(
|
|
318
|
+
tags,
|
|
319
|
+
("com.apple.quicktime.location.iso6709", "location", "location-eng", "gps_coordinates"),
|
|
320
|
+
160,
|
|
321
|
+
)
|
|
322
|
+
if location is not None:
|
|
323
|
+
coordinates = _ISO6709.fullmatch(location)
|
|
324
|
+
if coordinates is not None:
|
|
325
|
+
latitude = float(coordinates.group(1))
|
|
326
|
+
longitude = float(coordinates.group(2))
|
|
327
|
+
if -90 <= latitude <= 90 and -180 <= longitude <= 180:
|
|
328
|
+
summary["location"] = f"GPS {latitude:.6f}, {longitude:.6f}"
|
|
329
|
+
elif all(character >= " " and character != "\x7f" for character in location):
|
|
330
|
+
summary["location"] = location
|
|
331
|
+
return summary, tuple(streams)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _metadata_value(groups: list[Mapping[str, object]], keys: tuple[str, ...], maximum: int) -> str | None:
|
|
335
|
+
for key in keys:
|
|
336
|
+
lowered = key.casefold()
|
|
337
|
+
for group in groups:
|
|
338
|
+
for observed, value in group.items():
|
|
339
|
+
if (
|
|
340
|
+
isinstance(observed, str)
|
|
341
|
+
and observed.casefold() == lowered
|
|
342
|
+
and isinstance(value, str)
|
|
343
|
+
and 1 <= len(value.strip()) <= maximum
|
|
344
|
+
):
|
|
345
|
+
return value.strip()
|
|
346
|
+
return None
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _integer(value: object, *, minimum: int, maximum: int) -> int:
|
|
350
|
+
if isinstance(value, bool):
|
|
351
|
+
raise MediaProbeError("invalid_probe_output")
|
|
352
|
+
try:
|
|
353
|
+
result = int(value)
|
|
354
|
+
except (TypeError, ValueError) as error:
|
|
355
|
+
raise MediaProbeError("invalid_probe_output") from error
|
|
356
|
+
if str(result) != str(value).strip() or not minimum <= result <= maximum:
|
|
357
|
+
raise MediaProbeError("invalid_probe_output")
|
|
358
|
+
return result
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _fraction(value: object, *, positive: bool) -> str:
|
|
362
|
+
if not isinstance(value, str) or len(value) > 80:
|
|
363
|
+
raise MediaProbeError("invalid_probe_output")
|
|
364
|
+
try:
|
|
365
|
+
result = Fraction(value)
|
|
366
|
+
except (ValueError, ZeroDivisionError) as error:
|
|
367
|
+
raise MediaProbeError("invalid_probe_output") from error
|
|
368
|
+
if positive and result <= 0:
|
|
369
|
+
raise MediaProbeError("invalid_probe_output")
|
|
370
|
+
if abs(result) > 1_000_000:
|
|
371
|
+
raise MediaProbeError("invalid_probe_output")
|
|
372
|
+
return f"{result.numerator}/{result.denominator}"
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _decimal(value: object, *, non_negative: bool) -> str:
|
|
376
|
+
try:
|
|
377
|
+
result = Decimal(str(value))
|
|
378
|
+
except (InvalidOperation, ValueError) as error:
|
|
379
|
+
raise MediaProbeError("invalid_probe_output") from error
|
|
380
|
+
if not result.is_finite() or (non_negative and result < 0) or abs(result) > Decimal("1e12"):
|
|
381
|
+
raise MediaProbeError("invalid_probe_output")
|
|
382
|
+
return format(result.normalize(), "f")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _rotation(stream: Mapping[str, Any]) -> int | None:
|
|
386
|
+
tags = stream.get("tags")
|
|
387
|
+
if isinstance(tags, dict) and "rotate" in tags:
|
|
388
|
+
return _integer(tags["rotate"], minimum=-360_000, maximum=360_000) % 360
|
|
389
|
+
side_data = stream.get("side_data_list")
|
|
390
|
+
if isinstance(side_data, list):
|
|
391
|
+
for item in side_data[:16]:
|
|
392
|
+
if isinstance(item, dict) and "rotation" in item:
|
|
393
|
+
return _integer(item["rotation"], minimum=-360_000, maximum=360_000) % 360
|
|
394
|
+
return None
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _terminate(process: subprocess.Popen[bytes]) -> None:
|
|
398
|
+
if process.poll() is not None:
|
|
399
|
+
return
|
|
400
|
+
if os.name == "posix":
|
|
401
|
+
try:
|
|
402
|
+
os.killpg(process.pid, signal.SIGTERM)
|
|
403
|
+
except ProcessLookupError:
|
|
404
|
+
process.wait(timeout=2)
|
|
405
|
+
return
|
|
406
|
+
else:
|
|
407
|
+
process.terminate()
|
|
408
|
+
try:
|
|
409
|
+
process.wait(timeout=2)
|
|
410
|
+
except subprocess.TimeoutExpired:
|
|
411
|
+
if os.name == "posix":
|
|
412
|
+
try:
|
|
413
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
414
|
+
except ProcessLookupError:
|
|
415
|
+
pass
|
|
416
|
+
else:
|
|
417
|
+
process.kill()
|
|
418
|
+
process.wait(timeout=2)
|