@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,543 @@
|
|
|
1
|
+
"""Single-instance Uvicorn lifecycle for the local Clipen workspace."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
import errno
|
|
8
|
+
import http.client
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import secrets
|
|
13
|
+
import signal
|
|
14
|
+
import socket
|
|
15
|
+
import stat
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from typing import Callable
|
|
20
|
+
import webbrowser
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
import fcntl as _fcntl
|
|
24
|
+
except ImportError: # Windows does not provide POSIX advisory file locks.
|
|
25
|
+
_fcntl = None
|
|
26
|
+
|
|
27
|
+
import uvicorn
|
|
28
|
+
|
|
29
|
+
from clipen.analysis import (
|
|
30
|
+
ASRSetupManager,
|
|
31
|
+
ArtifactStore,
|
|
32
|
+
ManagedAnalysisRuntime,
|
|
33
|
+
PreparationRepository,
|
|
34
|
+
)
|
|
35
|
+
from clipen.media import InventoryCoordinator, InventoryRepository, MediaPreviewRepository
|
|
36
|
+
from clipen.editing import EditAgentCoordinator, EditAgentRepository
|
|
37
|
+
from clipen.providers import CodexExecAdapter, ProviderUnavailable
|
|
38
|
+
from clipen.providers.claude import ClaudeCliAdapter
|
|
39
|
+
from clipen.provider_registry import exec_adapter_factory
|
|
40
|
+
from clipen.analysis.evidence_service import EvidenceService
|
|
41
|
+
from clipen.annotations import AnnotationRepository
|
|
42
|
+
from clipen.projects import ProjectWorkspace
|
|
43
|
+
|
|
44
|
+
from .app import (
|
|
45
|
+
ControllerConfig,
|
|
46
|
+
LocalSessionAuthority,
|
|
47
|
+
ProviderState,
|
|
48
|
+
ProviderStatus,
|
|
49
|
+
create_app,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
HOST = "127.0.0.1"
|
|
54
|
+
PRIMARY_PORT = 4200
|
|
55
|
+
_INSTANCE_SCHEMA = 1
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class PortUnavailable(RuntimeError):
|
|
59
|
+
"""No loopback listener could be allocated for the local Clipen UI."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class ExistingController:
|
|
64
|
+
public_url: str
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _InstanceLease:
|
|
68
|
+
def __init__(self, lock_file, registry_path: Path, secret: str) -> None:
|
|
69
|
+
self._lock_file = lock_file
|
|
70
|
+
self.registry_path = registry_path
|
|
71
|
+
self.secret = secret
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def acquire(cls, root: Path) -> "_InstanceLease | None":
|
|
75
|
+
if _fcntl is None:
|
|
76
|
+
raise RuntimeError(
|
|
77
|
+
"這個開發版本尚不支援 Windows;本機工作台需要 POSIX 檔案鎖"
|
|
78
|
+
)
|
|
79
|
+
lock_path = root / ".controller.lock"
|
|
80
|
+
flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
|
|
81
|
+
descriptor = os.open(lock_path, flags, 0o600)
|
|
82
|
+
os.fchmod(descriptor, 0o600)
|
|
83
|
+
lock_file = os.fdopen(descriptor, "r+b")
|
|
84
|
+
try:
|
|
85
|
+
_fcntl.flock(lock_file.fileno(), _fcntl.LOCK_EX | _fcntl.LOCK_NB)
|
|
86
|
+
except BlockingIOError:
|
|
87
|
+
lock_file.close()
|
|
88
|
+
return None
|
|
89
|
+
except BaseException:
|
|
90
|
+
lock_file.close()
|
|
91
|
+
raise
|
|
92
|
+
return cls(lock_file, root / ".controller.json", secrets.token_urlsafe(32))
|
|
93
|
+
|
|
94
|
+
def publish(self, port: int) -> None:
|
|
95
|
+
payload = json.dumps(
|
|
96
|
+
{"schema": _INSTANCE_SCHEMA, "port": port, "secret": self.secret},
|
|
97
|
+
sort_keys=True,
|
|
98
|
+
separators=(",", ":"),
|
|
99
|
+
).encode("utf-8")
|
|
100
|
+
temporary = self.registry_path.with_name(
|
|
101
|
+
f".{self.registry_path.name}.tmp-{os.getpid()}-{secrets.token_hex(4)}"
|
|
102
|
+
)
|
|
103
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
|
|
104
|
+
descriptor = os.open(temporary, flags, 0o600)
|
|
105
|
+
try:
|
|
106
|
+
with os.fdopen(descriptor, "wb", closefd=False) as output:
|
|
107
|
+
output.write(payload)
|
|
108
|
+
output.flush()
|
|
109
|
+
os.fsync(output.fileno())
|
|
110
|
+
os.close(descriptor)
|
|
111
|
+
descriptor = -1
|
|
112
|
+
os.replace(temporary, self.registry_path)
|
|
113
|
+
finally:
|
|
114
|
+
if descriptor >= 0:
|
|
115
|
+
os.close(descriptor)
|
|
116
|
+
temporary.unlink(missing_ok=True)
|
|
117
|
+
|
|
118
|
+
def close(self) -> None:
|
|
119
|
+
try:
|
|
120
|
+
record = _read_instance_record(self.registry_path)
|
|
121
|
+
if record is not None and record[1] == self.secret:
|
|
122
|
+
self.registry_path.unlink(missing_ok=True)
|
|
123
|
+
finally:
|
|
124
|
+
try:
|
|
125
|
+
assert _fcntl is not None
|
|
126
|
+
_fcntl.flock(self._lock_file.fileno(), _fcntl.LOCK_UN)
|
|
127
|
+
finally:
|
|
128
|
+
self._lock_file.close()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True)
|
|
132
|
+
class ServerPaths:
|
|
133
|
+
static_root: Path
|
|
134
|
+
attempt_root: Path
|
|
135
|
+
projects_root: Path | None = None
|
|
136
|
+
instance_root: Path | None = None
|
|
137
|
+
asr_requirements: Path | None = None
|
|
138
|
+
|
|
139
|
+
def prepare(self) -> None:
|
|
140
|
+
if not self.static_root.resolve(strict=True).is_dir():
|
|
141
|
+
raise ValueError("Clipen UI production bundle is missing")
|
|
142
|
+
data_root = self.attempt_root.parent
|
|
143
|
+
data_root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
144
|
+
if data_root.is_symlink():
|
|
145
|
+
raise ValueError("Clipen data root cannot be a symbolic link")
|
|
146
|
+
data_root.chmod(0o700)
|
|
147
|
+
self.attempt_root.mkdir(mode=0o700, exist_ok=True)
|
|
148
|
+
if self.attempt_root.is_symlink():
|
|
149
|
+
raise ValueError("provider attempt root cannot be a symbolic link")
|
|
150
|
+
self.attempt_root.chmod(0o700)
|
|
151
|
+
if self.projects_root is not None and self.projects_root.is_symlink():
|
|
152
|
+
raise ValueError("projects root cannot be a symbolic link")
|
|
153
|
+
if self.instance_root is not None:
|
|
154
|
+
self.instance_root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
155
|
+
if self.instance_root.is_symlink() or not self.instance_root.is_dir():
|
|
156
|
+
raise ValueError("instance root cannot be a symbolic link")
|
|
157
|
+
self.instance_root.chmod(0o700)
|
|
158
|
+
if self.asr_requirements is not None and not self.asr_requirements.resolve(
|
|
159
|
+
strict=True
|
|
160
|
+
).is_file():
|
|
161
|
+
raise ValueError("ASR runtime requirements are missing")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def provider_account(provider_id: str, attempt_root: Path, ttl: float = 60.) -> Callable[[], dict]:
|
|
165
|
+
"""A cached, read-only lookup of the running model and remaining quota."""
|
|
166
|
+
from clipen.providers.account import claude_account, codex_account
|
|
167
|
+
lock, cache = threading.Lock(), {}
|
|
168
|
+
|
|
169
|
+
def lookup() -> dict:
|
|
170
|
+
if provider_id == "claude":
|
|
171
|
+
from clipen.providers.claude import claude_environment
|
|
172
|
+
return claude_account(attempt_root, claude_environment())
|
|
173
|
+
if provider_id != "codex":
|
|
174
|
+
return {"model": None, "quota": None}
|
|
175
|
+
try:
|
|
176
|
+
adapter = CodexExecAdapter(attempt_root)
|
|
177
|
+
except ProviderUnavailable:
|
|
178
|
+
return {"model": None, "quota": None}
|
|
179
|
+
return codex_account(adapter.binary, adapter._environment)
|
|
180
|
+
|
|
181
|
+
def cached() -> dict:
|
|
182
|
+
with lock:
|
|
183
|
+
if cache and time.monotonic() - cache["at"] < ttl:
|
|
184
|
+
return cache["value"]
|
|
185
|
+
value = lookup()
|
|
186
|
+
cache.update(at=time.monotonic(), value=value)
|
|
187
|
+
return value
|
|
188
|
+
|
|
189
|
+
return cached
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def probe_codex(attempt_root: Path) -> ProviderStatus:
|
|
193
|
+
try:
|
|
194
|
+
adapter = CodexExecAdapter(attempt_root)
|
|
195
|
+
result = adapter.probe()
|
|
196
|
+
except ProviderUnavailable:
|
|
197
|
+
return ProviderStatus("Codex", ProviderState.UNAVAILABLE, "找不到可用的 Codex CLI")
|
|
198
|
+
except Exception:
|
|
199
|
+
return ProviderStatus("Codex", ProviderState.UNAVAILABLE, "Codex 檢查無法完成")
|
|
200
|
+
|
|
201
|
+
if not result.authenticated:
|
|
202
|
+
return ProviderStatus("Codex", ProviderState.LOGIN_REQUIRED, "需要先完成 Codex 登入")
|
|
203
|
+
if not result.capabilities.supports_bounded_attempts:
|
|
204
|
+
return ProviderStatus("Codex", ProviderState.UNSUPPORTED, "Codex 版本需要更新")
|
|
205
|
+
if not result.confinement_verified:
|
|
206
|
+
return ProviderStatus(
|
|
207
|
+
"Codex", ProviderState.CONFINEMENT_FAILED, "Codex 安全檢查未通過"
|
|
208
|
+
)
|
|
209
|
+
return ProviderStatus("Codex", ProviderState.READY, "AI 已連接,可以開始使用")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def probe_claude(attempt_root: Path) -> ProviderStatus:
|
|
213
|
+
del attempt_root # Claude attempts are confined by tool allowlists, not a sandbox canary.
|
|
214
|
+
try:
|
|
215
|
+
result = ClaudeCliAdapter().probe()
|
|
216
|
+
except ProviderUnavailable:
|
|
217
|
+
return ProviderStatus("Claude", ProviderState.UNAVAILABLE, "找不到可用的 Claude Code CLI", "claude")
|
|
218
|
+
except Exception:
|
|
219
|
+
return ProviderStatus("Claude", ProviderState.UNAVAILABLE, "Claude Code 檢查無法完成", "claude")
|
|
220
|
+
if not result.authenticated:
|
|
221
|
+
return ProviderStatus("Claude", ProviderState.LOGIN_REQUIRED, "需要先完成 Claude Code 登入", "claude")
|
|
222
|
+
if not result.supports_bounded_attempts:
|
|
223
|
+
return ProviderStatus("Claude", ProviderState.UNSUPPORTED, "Claude Code 版本需要更新", "claude")
|
|
224
|
+
return ProviderStatus("Claude", ProviderState.READY, "AI 已連接,可以開始使用", "claude")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _bind_socket(
|
|
228
|
+
preferred_port: int = PRIMARY_PORT,
|
|
229
|
+
) -> tuple[socket.socket, int]:
|
|
230
|
+
# Keep the socket open through Uvicorn startup so another process cannot
|
|
231
|
+
# claim the selected port between discovery and serving requests.
|
|
232
|
+
for port in (preferred_port, 0):
|
|
233
|
+
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
234
|
+
try:
|
|
235
|
+
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
236
|
+
listener.bind((HOST, port))
|
|
237
|
+
listener.listen(2048)
|
|
238
|
+
return listener, listener.getsockname()[1]
|
|
239
|
+
except OSError as error:
|
|
240
|
+
listener.close()
|
|
241
|
+
if port == 0 or error.errno not in (errno.EADDRINUSE, errno.EACCES):
|
|
242
|
+
raise PortUnavailable("無法取得可用的本機連線埠,請稍後再試") from error
|
|
243
|
+
raise AssertionError("port allocation must return a listener or raise")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _read_instance_record(path: Path) -> tuple[int, str] | None:
|
|
247
|
+
descriptor = -1
|
|
248
|
+
try:
|
|
249
|
+
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
|
250
|
+
info = os.fstat(descriptor)
|
|
251
|
+
if (
|
|
252
|
+
not stat.S_ISREG(info.st_mode)
|
|
253
|
+
or info.st_size > 4096
|
|
254
|
+
or info.st_mode & 0o077
|
|
255
|
+
):
|
|
256
|
+
return None
|
|
257
|
+
raw = os.read(descriptor, 4097)
|
|
258
|
+
if len(raw) > 4096:
|
|
259
|
+
return None
|
|
260
|
+
value = json.loads(raw.decode("utf-8"))
|
|
261
|
+
port = value.get("port") if isinstance(value, dict) else None
|
|
262
|
+
secret = value.get("secret") if isinstance(value, dict) else None
|
|
263
|
+
if (
|
|
264
|
+
value.get("schema") != _INSTANCE_SCHEMA
|
|
265
|
+
or isinstance(port, bool)
|
|
266
|
+
or not isinstance(port, int)
|
|
267
|
+
or not 1 <= port <= 65535
|
|
268
|
+
or not isinstance(secret, str)
|
|
269
|
+
or not 32 <= len(secret) <= 256
|
|
270
|
+
):
|
|
271
|
+
return None
|
|
272
|
+
return port, secret
|
|
273
|
+
except (OSError, UnicodeError, json.JSONDecodeError, AttributeError):
|
|
274
|
+
return None
|
|
275
|
+
finally:
|
|
276
|
+
if descriptor >= 0:
|
|
277
|
+
os.close(descriptor)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _request_reopen(port: int, secret: str) -> ExistingController | None:
|
|
281
|
+
connection = http.client.HTTPConnection(HOST, port, timeout=0.5)
|
|
282
|
+
try:
|
|
283
|
+
connection.request(
|
|
284
|
+
"POST",
|
|
285
|
+
"/api/instance/reopen",
|
|
286
|
+
body=b"",
|
|
287
|
+
headers={
|
|
288
|
+
"Host": f"localhost:{port}",
|
|
289
|
+
"X-Clipen-Instance": secret,
|
|
290
|
+
"Content-Length": "0",
|
|
291
|
+
},
|
|
292
|
+
)
|
|
293
|
+
response = connection.getresponse()
|
|
294
|
+
body = response.read(4097)
|
|
295
|
+
if response.status != 200 or len(body) > 4096:
|
|
296
|
+
return None
|
|
297
|
+
value = json.loads(body.decode("utf-8"))
|
|
298
|
+
if not isinstance(value, dict) or value.get("running") is not True:
|
|
299
|
+
return None
|
|
300
|
+
public_url = f"http://localhost:{port}"
|
|
301
|
+
return ExistingController(public_url)
|
|
302
|
+
except (OSError, http.client.HTTPException, UnicodeError, json.JSONDecodeError):
|
|
303
|
+
return None
|
|
304
|
+
finally:
|
|
305
|
+
connection.close()
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _find_existing_controller(registry_path: Path) -> ExistingController | None:
|
|
309
|
+
for _ in range(20):
|
|
310
|
+
record = _read_instance_record(registry_path)
|
|
311
|
+
if record is not None:
|
|
312
|
+
existing = _request_reopen(*record)
|
|
313
|
+
if existing is not None:
|
|
314
|
+
return existing
|
|
315
|
+
time.sleep(0.05)
|
|
316
|
+
return None
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _print_ui_url(url: str, *, first_connection: bool = False) -> None:
|
|
320
|
+
label = "首次連線:" if first_connection else "UI:"
|
|
321
|
+
print(label, flush=True)
|
|
322
|
+
if sys.stdout.isatty():
|
|
323
|
+
print(f"\033]8;;{url}\033\\{url}\033]8;;\033\\", flush=True)
|
|
324
|
+
else:
|
|
325
|
+
print(url, flush=True)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _terminal_reopen_loop(
|
|
329
|
+
public_url: str,
|
|
330
|
+
browser_open: Callable[[str], bool],
|
|
331
|
+
should_stop: Callable[[], bool],
|
|
332
|
+
) -> None:
|
|
333
|
+
while not should_stop():
|
|
334
|
+
try:
|
|
335
|
+
line = sys.stdin.readline()
|
|
336
|
+
except (OSError, UnicodeError):
|
|
337
|
+
return
|
|
338
|
+
if line == "" or should_stop():
|
|
339
|
+
return
|
|
340
|
+
try:
|
|
341
|
+
opened = browser_open(public_url)
|
|
342
|
+
except Exception:
|
|
343
|
+
opened = False
|
|
344
|
+
if not opened:
|
|
345
|
+
print("瀏覽器未自動開啟。", flush=True)
|
|
346
|
+
_print_ui_url(public_url, first_connection=True)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
async def _serve(
|
|
350
|
+
paths: ServerPaths,
|
|
351
|
+
provider: ProviderStatus,
|
|
352
|
+
authority: LocalSessionAuthority,
|
|
353
|
+
*,
|
|
354
|
+
browser_open: Callable[[str], bool],
|
|
355
|
+
lease: _InstanceLease,
|
|
356
|
+
) -> None:
|
|
357
|
+
listener, port = _bind_socket()
|
|
358
|
+
public_url = f"http://localhost:{port}"
|
|
359
|
+
inventories = None
|
|
360
|
+
preparation_repository = None
|
|
361
|
+
analysis_runtime = None
|
|
362
|
+
evidence_service = None
|
|
363
|
+
annotations = None
|
|
364
|
+
media_previews = None
|
|
365
|
+
edit_agents = None
|
|
366
|
+
try:
|
|
367
|
+
lease.publish(port)
|
|
368
|
+
workspace = (
|
|
369
|
+
ProjectWorkspace(paths.projects_root)
|
|
370
|
+
if paths.projects_root is not None
|
|
371
|
+
else None
|
|
372
|
+
)
|
|
373
|
+
if workspace is not None:
|
|
374
|
+
annotations = AnnotationRepository(workspace.repository)
|
|
375
|
+
media_previews = MediaPreviewRepository(workspace.repository)
|
|
376
|
+
edit_agent_repository = EditAgentRepository(workspace.repository)
|
|
377
|
+
# Every schema-bound AI step uses the provider Clipen was started with.
|
|
378
|
+
exec_adapter = exec_adapter_factory(provider.provider_id)
|
|
379
|
+
if provider.state is ProviderState.READY:
|
|
380
|
+
edit_agents = EditAgentCoordinator(
|
|
381
|
+
edit_agent_repository,
|
|
382
|
+
paths.attempt_root,
|
|
383
|
+
provider_id=provider.provider_id,
|
|
384
|
+
local_runtime=(paths.attempt_root.parent, paths.asr_requirements) if paths.asr_requirements else None,
|
|
385
|
+
)
|
|
386
|
+
edit_agents.recover()
|
|
387
|
+
else:
|
|
388
|
+
for project in workspace.repository.list_projects():
|
|
389
|
+
edit_agent_repository.interrupt_incomplete(project.project_id)
|
|
390
|
+
repository = InventoryRepository(workspace.repository)
|
|
391
|
+
inventories = InventoryCoordinator(repository)
|
|
392
|
+
inventories.recover_incomplete(
|
|
393
|
+
project.project_id for project in workspace.repository.list_projects()
|
|
394
|
+
)
|
|
395
|
+
evidence_service = EvidenceService(workspace.repository, paths.attempt_root if provider.state is ProviderState.READY else None,
|
|
396
|
+
adapter_factory=exec_adapter)
|
|
397
|
+
evidence_service.recover()
|
|
398
|
+
preparation_repository = PreparationRepository(workspace.repository)
|
|
399
|
+
for project in workspace.repository.list_projects():
|
|
400
|
+
preparation_repository.interrupt_incomplete(project.project_id)
|
|
401
|
+
if paths.asr_requirements is not None:
|
|
402
|
+
analysis_runtime = ManagedAnalysisRuntime(
|
|
403
|
+
preparation_repository,
|
|
404
|
+
ArtifactStore(workspace.repository),
|
|
405
|
+
ASRSetupManager(
|
|
406
|
+
paths.attempt_root.parent,
|
|
407
|
+
paths.asr_requirements,
|
|
408
|
+
),
|
|
409
|
+
)
|
|
410
|
+
app = create_app(
|
|
411
|
+
ControllerConfig(
|
|
412
|
+
paths.static_root,
|
|
413
|
+
origin=public_url,
|
|
414
|
+
allowed_hosts=(f"localhost:{port}", f"127.0.0.1:{port}"),
|
|
415
|
+
instance_secret=lease.secret,
|
|
416
|
+
),
|
|
417
|
+
provider,
|
|
418
|
+
authority,
|
|
419
|
+
workspace,
|
|
420
|
+
inventories,
|
|
421
|
+
preparation_repository=preparation_repository,
|
|
422
|
+
analysis_runtime=analysis_runtime,
|
|
423
|
+
evidence_service=evidence_service,
|
|
424
|
+
annotations=annotations,
|
|
425
|
+
media_previews=media_previews,
|
|
426
|
+
edit_agents=edit_agents,
|
|
427
|
+
provider_account=provider_account(provider.provider_id, paths.attempt_root),
|
|
428
|
+
)
|
|
429
|
+
config = uvicorn.Config(
|
|
430
|
+
app,
|
|
431
|
+
host=HOST,
|
|
432
|
+
port=port,
|
|
433
|
+
log_level="critical",
|
|
434
|
+
access_log=False,
|
|
435
|
+
server_header=False,
|
|
436
|
+
date_header=False,
|
|
437
|
+
lifespan="off",
|
|
438
|
+
)
|
|
439
|
+
server = uvicorn.Server(config)
|
|
440
|
+
async def announce_when_started() -> None:
|
|
441
|
+
while not server.started and not server.should_exit:
|
|
442
|
+
await asyncio.sleep(0.02)
|
|
443
|
+
if server.started:
|
|
444
|
+
print("Clipen 已啟動", flush=True)
|
|
445
|
+
if provider.state is ProviderState.READY:
|
|
446
|
+
print(f"AI:{provider.name} 可用", flush=True)
|
|
447
|
+
else:
|
|
448
|
+
print(f"AI:{provider.name} 需要處理", flush=True)
|
|
449
|
+
_print_ui_url(public_url)
|
|
450
|
+
print("狀態:等待 UI 操作", flush=True)
|
|
451
|
+
try:
|
|
452
|
+
opened = browser_open(public_url)
|
|
453
|
+
except Exception:
|
|
454
|
+
opened = False
|
|
455
|
+
if not opened:
|
|
456
|
+
print("瀏覽器未自動開啟。", flush=True)
|
|
457
|
+
_print_ui_url(public_url, first_connection=True)
|
|
458
|
+
if sys.stdin.isatty():
|
|
459
|
+
print("按 Enter 重新開啟 UI · 按 Ctrl+C 關閉 Clipen", flush=True)
|
|
460
|
+
threading.Thread(
|
|
461
|
+
target=_terminal_reopen_loop,
|
|
462
|
+
args=(
|
|
463
|
+
public_url,
|
|
464
|
+
browser_open,
|
|
465
|
+
lambda: server.should_exit,
|
|
466
|
+
),
|
|
467
|
+
name="clipen-terminal-reopen",
|
|
468
|
+
daemon=True,
|
|
469
|
+
).start()
|
|
470
|
+
else:
|
|
471
|
+
print("按 Ctrl+C 關閉 Clipen", flush=True)
|
|
472
|
+
|
|
473
|
+
announcement = asyncio.create_task(announce_when_started())
|
|
474
|
+
previous_hup = None
|
|
475
|
+
if hasattr(signal, "SIGHUP"):
|
|
476
|
+
previous_hup = signal.getsignal(signal.SIGHUP)
|
|
477
|
+
signal.signal(signal.SIGHUP, lambda *_: setattr(server, "should_exit", True))
|
|
478
|
+
try:
|
|
479
|
+
await server.serve(sockets=[listener])
|
|
480
|
+
finally:
|
|
481
|
+
server.should_exit = True
|
|
482
|
+
await announcement
|
|
483
|
+
if hasattr(signal, "SIGHUP") and previous_hup is not None:
|
|
484
|
+
signal.signal(signal.SIGHUP, previous_hup)
|
|
485
|
+
finally:
|
|
486
|
+
if edit_agents is not None:
|
|
487
|
+
edit_agents.close()
|
|
488
|
+
if evidence_service is not None:
|
|
489
|
+
evidence_service.close()
|
|
490
|
+
if analysis_runtime is not None:
|
|
491
|
+
analysis_runtime.close()
|
|
492
|
+
if inventories is not None:
|
|
493
|
+
inventories.close()
|
|
494
|
+
listener.close()
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def run_server(
|
|
498
|
+
paths: ServerPaths,
|
|
499
|
+
provider: ProviderStatus,
|
|
500
|
+
authority: LocalSessionAuthority,
|
|
501
|
+
*,
|
|
502
|
+
browser_open: Callable[[str], bool] = webbrowser.open,
|
|
503
|
+
) -> int:
|
|
504
|
+
paths.prepare()
|
|
505
|
+
from clipen.skills import configure_library
|
|
506
|
+
# Custom skills live beside other Clipen data and are shared by all workspaces.
|
|
507
|
+
configure_library(paths.attempt_root.parent / "skills")
|
|
508
|
+
instance_root = paths.instance_root or paths.attempt_root.parent
|
|
509
|
+
lease = _InstanceLease.acquire(instance_root)
|
|
510
|
+
if lease is None:
|
|
511
|
+
existing = _find_existing_controller(instance_root / ".controller.json")
|
|
512
|
+
if existing is None:
|
|
513
|
+
print("Clipen 無法連接正在啟動的本機工作台。請稍後再試。")
|
|
514
|
+
return 1
|
|
515
|
+
print("Clipen 已在執行", flush=True)
|
|
516
|
+
_print_ui_url(existing.public_url)
|
|
517
|
+
try:
|
|
518
|
+
opened = browser_open(existing.public_url)
|
|
519
|
+
except Exception:
|
|
520
|
+
opened = False
|
|
521
|
+
if not opened:
|
|
522
|
+
print("瀏覽器未自動開啟。", flush=True)
|
|
523
|
+
_print_ui_url(existing.public_url, first_connection=True)
|
|
524
|
+
return 0
|
|
525
|
+
try:
|
|
526
|
+
asyncio.run(
|
|
527
|
+
_serve(
|
|
528
|
+
paths,
|
|
529
|
+
provider,
|
|
530
|
+
authority,
|
|
531
|
+
browser_open=browser_open,
|
|
532
|
+
lease=lease,
|
|
533
|
+
)
|
|
534
|
+
)
|
|
535
|
+
except PortUnavailable as error:
|
|
536
|
+
print(f"Clipen 無法啟動:{error}")
|
|
537
|
+
return 1
|
|
538
|
+
except KeyboardInterrupt:
|
|
539
|
+
pass
|
|
540
|
+
finally:
|
|
541
|
+
lease.close()
|
|
542
|
+
print("Clipen 已停止", flush=True)
|
|
543
|
+
return 0
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Pure product-domain types without transport or provider dependencies."""
|
|
2
|
+
|
|
3
|
+
from .media_time import Rational, SourceSpan
|
|
4
|
+
from .timeline import (
|
|
5
|
+
ClipSource,
|
|
6
|
+
EditTimeline,
|
|
7
|
+
EffectRequest,
|
|
8
|
+
GraphicClip,
|
|
9
|
+
Marker,
|
|
10
|
+
MediaClip,
|
|
11
|
+
TextClip,
|
|
12
|
+
Track,
|
|
13
|
+
TrackKind,
|
|
14
|
+
)
|
|
15
|
+
from .errors import InvalidTransition
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"InvalidTransition",
|
|
19
|
+
"ClipSource",
|
|
20
|
+
"EditTimeline",
|
|
21
|
+
"EffectRequest",
|
|
22
|
+
"GraphicClip",
|
|
23
|
+
"Marker",
|
|
24
|
+
"MediaClip",
|
|
25
|
+
"Rational",
|
|
26
|
+
"SourceSpan",
|
|
27
|
+
"TextClip",
|
|
28
|
+
"Track",
|
|
29
|
+
"TrackKind",
|
|
30
|
+
]
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Exact media time values shared by analysis, timelines, and exporters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any, Mapping
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
_DECIMAL_INTEGER = re.compile(r"-?(?:0|[1-9][0-9]*)\Z")
|
|
11
|
+
_VERSION_ID = re.compile(r"av_[0-9a-f]{32}\Z")
|
|
12
|
+
_MAX_TIME_BASE_COMPONENT = 1_000_000_000
|
|
13
|
+
_MAX_STREAM_INDEX = 2**31 - 1
|
|
14
|
+
_MIN_PTS = -(2**63)
|
|
15
|
+
_MAX_PTS = 2**63 - 1
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _pts(value: object, field: str) -> int:
|
|
19
|
+
if not isinstance(value, str) or _DECIMAL_INTEGER.fullmatch(value) is None:
|
|
20
|
+
raise ValueError(f"{field} must be a decimal integer string")
|
|
21
|
+
parsed = int(value)
|
|
22
|
+
if not _MIN_PTS <= parsed <= _MAX_PTS:
|
|
23
|
+
raise ValueError(f"{field} is outside supported bounds")
|
|
24
|
+
return parsed
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Rational:
|
|
29
|
+
"""A bounded positive rational that preserves the source representation."""
|
|
30
|
+
|
|
31
|
+
numerator: int
|
|
32
|
+
denominator: int
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
if any(
|
|
36
|
+
isinstance(value, bool) or not isinstance(value, int) or value < 1
|
|
37
|
+
for value in (self.numerator, self.denominator)
|
|
38
|
+
):
|
|
39
|
+
raise ValueError("time base must contain positive integers")
|
|
40
|
+
if (
|
|
41
|
+
self.numerator > _MAX_TIME_BASE_COMPONENT
|
|
42
|
+
or self.denominator > _MAX_TIME_BASE_COMPONENT
|
|
43
|
+
):
|
|
44
|
+
raise ValueError("time base is outside supported bounds")
|
|
45
|
+
|
|
46
|
+
def to_storage(self) -> dict[str, int]:
|
|
47
|
+
return {"num": self.numerator, "den": self.denominator}
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_storage(cls, value: Mapping[str, Any]) -> "Rational":
|
|
51
|
+
if not isinstance(value, Mapping) or set(value) != {"num", "den"}:
|
|
52
|
+
raise ValueError("stored time base is invalid")
|
|
53
|
+
return cls(value["num"], value["den"])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class SourceSpan:
|
|
58
|
+
"""A nonempty half-open PTS interval on one immutable media stream."""
|
|
59
|
+
|
|
60
|
+
version_id: str
|
|
61
|
+
stream_index: int
|
|
62
|
+
start_pts: str
|
|
63
|
+
end_pts: str
|
|
64
|
+
time_base: Rational
|
|
65
|
+
|
|
66
|
+
def __post_init__(self) -> None:
|
|
67
|
+
if (
|
|
68
|
+
not isinstance(self.version_id, str)
|
|
69
|
+
or _VERSION_ID.fullmatch(self.version_id) is None
|
|
70
|
+
):
|
|
71
|
+
raise ValueError("source span version is invalid")
|
|
72
|
+
if (
|
|
73
|
+
isinstance(self.stream_index, bool)
|
|
74
|
+
or not isinstance(self.stream_index, int)
|
|
75
|
+
or not 0 <= self.stream_index <= _MAX_STREAM_INDEX
|
|
76
|
+
):
|
|
77
|
+
raise ValueError("source stream index is invalid")
|
|
78
|
+
start = _pts(self.start_pts, "start_pts")
|
|
79
|
+
end = _pts(self.end_pts, "end_pts")
|
|
80
|
+
if end <= start:
|
|
81
|
+
raise ValueError("source span must be a non-empty half-open interval")
|
|
82
|
+
if not isinstance(self.time_base, Rational):
|
|
83
|
+
raise ValueError("source span time base is invalid")
|
|
84
|
+
|
|
85
|
+
def to_storage(self) -> dict[str, object]:
|
|
86
|
+
return {
|
|
87
|
+
"version_id": self.version_id,
|
|
88
|
+
"stream_index": self.stream_index,
|
|
89
|
+
"start_pts": self.start_pts,
|
|
90
|
+
"end_pts": self.end_pts,
|
|
91
|
+
"time_base": self.time_base.to_storage(),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def duration_pts(self) -> int:
|
|
96
|
+
return int(self.end_pts) - int(self.start_pts)
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_storage(cls, value: Mapping[str, Any]) -> "SourceSpan":
|
|
100
|
+
if not isinstance(value, Mapping) or set(value) != {
|
|
101
|
+
"version_id",
|
|
102
|
+
"stream_index",
|
|
103
|
+
"start_pts",
|
|
104
|
+
"end_pts",
|
|
105
|
+
"time_base",
|
|
106
|
+
}:
|
|
107
|
+
raise ValueError("stored source span is invalid")
|
|
108
|
+
raw_time_base = value["time_base"]
|
|
109
|
+
if not isinstance(raw_time_base, Mapping):
|
|
110
|
+
raise ValueError("stored time base is invalid")
|
|
111
|
+
return cls(
|
|
112
|
+
value["version_id"],
|
|
113
|
+
value["stream_index"],
|
|
114
|
+
value["start_pts"],
|
|
115
|
+
value["end_pts"],
|
|
116
|
+
Rational.from_storage(raw_time_base),
|
|
117
|
+
)
|