@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.
Files changed (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +52 -4
  11. package/pyproject.toml +28 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/runtime.txt +20 -0
  14. package/src/clipen/__init__.py +3 -0
  15. package/src/clipen/analysis/__init__.py +89 -0
  16. package/src/clipen/analysis/artifacts.py +416 -0
  17. package/src/clipen/analysis/audio.py +392 -0
  18. package/src/clipen/analysis/evidence.py +102 -0
  19. package/src/clipen/analysis/evidence_service.py +751 -0
  20. package/src/clipen/analysis/image_similarity.py +143 -0
  21. package/src/clipen/analysis/keyframes.py +171 -0
  22. package/src/clipen/analysis/models.py +230 -0
  23. package/src/clipen/analysis/qwen_worker.py +629 -0
  24. package/src/clipen/analysis/resources.py +21 -0
  25. package/src/clipen/analysis/runtime.py +64 -0
  26. package/src/clipen/analysis/service.py +626 -0
  27. package/src/clipen/analysis/setup.py +935 -0
  28. package/src/clipen/analysis/setup_cli.py +117 -0
  29. package/src/clipen/analysis/storage.py +2046 -0
  30. package/src/clipen/analysis/transcription.py +948 -0
  31. package/src/clipen/analysis/visual.py +176 -0
  32. package/src/clipen/annotations/__init__.py +10 -0
  33. package/src/clipen/annotations/models.py +22 -0
  34. package/src/clipen/annotations/storage.py +380 -0
  35. package/src/clipen/annotations/suggestions.py +120 -0
  36. package/src/clipen/asr_release.py +139 -0
  37. package/src/clipen/bootstrap.py +967 -0
  38. package/src/clipen/cli.py +84 -0
  39. package/src/clipen/controller/__init__.py +17 -0
  40. package/src/clipen/controller/app.py +1470 -0
  41. package/src/clipen/controller/server.py +543 -0
  42. package/src/clipen/domain/__init__.py +30 -0
  43. package/src/clipen/domain/errors.py +5 -0
  44. package/src/clipen/domain/media_time.py +117 -0
  45. package/src/clipen/domain/timeline.py +584 -0
  46. package/src/clipen/domain/validation.py +15 -0
  47. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  48. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  49. package/src/clipen/editing/README.md +115 -0
  50. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  51. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  52. package/src/clipen/editing/__init__.py +15 -0
  53. package/src/clipen/editing/agent.py +13 -0
  54. package/src/clipen/editing/agent_models.py +134 -0
  55. package/src/clipen/editing/agent_repository.py +757 -0
  56. package/src/clipen/editing/agent_tools.py +532 -0
  57. package/src/clipen/editing/alignment.py +110 -0
  58. package/src/clipen/editing/alignment_setup.py +108 -0
  59. package/src/clipen/editing/alignment_worker.py +22 -0
  60. package/src/clipen/editing/change_report.py +71 -0
  61. package/src/clipen/editing/compiler.py +41 -0
  62. package/src/clipen/editing/component_looks.py +107 -0
  63. package/src/clipen/editing/component_review.py +78 -0
  64. package/src/clipen/editing/coordinator.py +374 -0
  65. package/src/clipen/editing/editorial_review.py +187 -0
  66. package/src/clipen/editing/evidence_jobs.py +295 -0
  67. package/src/clipen/editing/history_changes.py +131 -0
  68. package/src/clipen/editing/music_choices.py +15 -0
  69. package/src/clipen/editing/production_catalog.py +192 -0
  70. package/src/clipen/editing/production_limits.py +59 -0
  71. package/src/clipen/editing/production_media.py +226 -0
  72. package/src/clipen/editing/production_preview.py +180 -0
  73. package/src/clipen/editing/production_progress.py +141 -0
  74. package/src/clipen/editing/production_requirements.py +50 -0
  75. package/src/clipen/editing/production_tools.py +596 -0
  76. package/src/clipen/editing/program_audio.py +118 -0
  77. package/src/clipen/editing/program_direction.py +49 -0
  78. package/src/clipen/editing/program_story.py +53 -0
  79. package/src/clipen/editing/program_subtitles.py +134 -0
  80. package/src/clipen/editing/programme_review.py +73 -0
  81. package/src/clipen/editing/prompt_history.py +47 -0
  82. package/src/clipen/editing/recut.py +127 -0
  83. package/src/clipen/editing/refinement_references.py +188 -0
  84. package/src/clipen/editing/resolve_export.py +616 -0
  85. package/src/clipen/editing/resolve_titles.py +234 -0
  86. package/src/clipen/editing/skill_tools.py +575 -0
  87. package/src/clipen/editing/source_dialogue.py +82 -0
  88. package/src/clipen/editing/speech_coverage.py +30 -0
  89. package/src/clipen/editing/speech_quality.py +6 -0
  90. package/src/clipen/editing/tool_receipts.py +52 -0
  91. package/src/clipen/editing/versions.py +161 -0
  92. package/src/clipen/editing/visual_preview.py +93 -0
  93. package/src/clipen/editing/workbench.py +74 -0
  94. package/src/clipen/filesystem.py +25 -0
  95. package/src/clipen/finishing/README.md +103 -0
  96. package/src/clipen/finishing/__init__.py +1 -0
  97. package/src/clipen/finishing/audio.py +149 -0
  98. package/src/clipen/finishing/catalog.py +181 -0
  99. package/src/clipen/finishing/models.py +14 -0
  100. package/src/clipen/finishing/renderer.py +26 -0
  101. package/src/clipen/mcp_editing/__init__.py +5 -0
  102. package/src/clipen/mcp_editing/__main__.py +40 -0
  103. package/src/clipen/mcp_editing/server.py +353 -0
  104. package/src/clipen/media/__init__.py +50 -0
  105. package/src/clipen/media/discovery.py +266 -0
  106. package/src/clipen/media/models.py +360 -0
  107. package/src/clipen/media/preview.py +147 -0
  108. package/src/clipen/media/probe.py +446 -0
  109. package/src/clipen/media/service.py +317 -0
  110. package/src/clipen/media/storage.py +742 -0
  111. package/src/clipen/music_vocabulary.py +5 -0
  112. package/src/clipen/planning/__init__.py +9 -0
  113. package/src/clipen/planning/models.py +240 -0
  114. package/src/clipen/power.py +23 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +269 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +34 -0
  121. package/src/clipen/projects/models.py +192 -0
  122. package/src/clipen/projects/picker.py +256 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +175 -0
  125. package/src/clipen/projects/storage.py +1478 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +75 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +194 -0
  131. package/src/clipen/providers/claude.py +375 -0
  132. package/src/clipen/providers/claude_editing.py +111 -0
  133. package/src/clipen/providers/codex.py +1036 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +565 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +270 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +126 -0
  141. package/src/clipen/rendering/custom_components.py +240 -0
  142. package/src/clipen/rendering/custom_render.py +197 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +64 -0
  158. package/src/clipen/rendering/program_components.py +193 -0
  159. package/src/clipen/rendering/program_creator.py +649 -0
  160. package/src/clipen/rendering/program_identities.py +255 -0
  161. package/src/clipen/rendering/program_motion.py +141 -0
  162. package/src/clipen/rendering/program_studio.py +168 -0
  163. package/src/clipen/rendering/program_styles.py +235 -0
  164. package/src/clipen/rendering/program_subtitles.py +52 -0
  165. package/src/clipen/rendering/renderer.py +708 -0
  166. package/src/clipen/rendering/storage.py +243 -0
  167. package/src/clipen/rendering/titles.py +360 -0
  168. package/src/clipen/skills/__init__.py +4 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +218 -0
  228. package/src/clipen/skills/library.py +131 -0
  229. package/src/clipen/skills/package.py +231 -0
  230. package/src/clipen/skills/visual_styles.py +44 -0
  231. package/src/clipen/workspace.py +210 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,103 @@
1
+ # AI finishing, workflow v2
2
+
3
+ The user confirms a direction proof and optionally describes the desired feel or
4
+ revision. One operation produces a film: it understands the confirmed story, finds
5
+ public music, compares candidates, recuts the actual source spans, renders locally,
6
+ and publishes the playable result with its decisions and music credit. No music
7
+ folder, manual song selection, parameter editing, or separate render command is
8
+ required. A later natural-language revision includes the previous decisions.
9
+
10
+ ## AI and evidence
11
+
12
+ There are at most two bounded Codex attempts per operation:
13
+
14
+ 1. A creative brief uses the confirmed requirements/sections, source observations,
15
+ trusted transcript provenance, and up to eight explicitly consented midpoint
16
+ thumbnails. It chooses a story arc, essential shots, and generic musical tags.
17
+ 2. The edit decision uses that brief and actual acquired music candidates, including
18
+ source-provided tags/genres and locally measured volume/onsets. It selects music,
19
+ explains the fit and alternatives, and chooses each shot's source trim, order,
20
+ purpose and audio treatment, plus supported finishing elements.
21
+
22
+ Codex does **not** receive raw music or listen to it through this CLI interface.
23
+ Mood/instrument descriptions come from catalog metadata, not an inference from BPM.
24
+ Single-frame thumbnails do not establish continuous motion. Those limitations are
25
+ included in the prompts; production taste still needs real user footage and review.
26
+
27
+ Search terms are limited to an enum of generic musical vocabulary. Private project
28
+ text is not sent to the catalog. Thumbnails, transcript, analysis and feedback go to
29
+ Codex only after consent that states the two-call budget and image scope.
30
+
31
+ ## Music sourcing
32
+
33
+ `catalog.py` searches the public Openverse audio API and refreshes each candidate's
34
+ metadata before downloading. It accepts instrumental tracks with complete CC0 or
35
+ CC BY metadata, title, creator, source page and canonical license link. Unknown,
36
+ NC, ND and SA entries are excluded by this initial implementation. Metadata is an
37
+ index's license assertion, not independent verification of ownership or original
38
+ source terms; the UI identifies it as such and links the original source and terms.
39
+
40
+ Each operation downloads at most three candidates (24 MiB per file) through a fixed
41
+ HTTPS host allowlist with public-address checks, bounded redirects, timeouts and
42
+ response sizes. Cancellation stops acquisition. Search outages and unusable files
43
+ are explicit failures; there is no silent switch to manual music or unlicensed audio.
44
+
45
+ Local inspection decodes at most 90 seconds per candidate at 8 kHz mono. It records
46
+ volume, peak, observed energy onsets and estimated tempo. The selected source window
47
+ must lie inside analyzed audio. Flat music may still be selected; it cannot acquire
48
+ invented beat markers. Only explicitly marked aligned cuts are checked against
49
+ observed beats. Narrative cuts need not all fall on a beat.
50
+
51
+ ## Edit and render contracts
52
+
53
+ `models.py` validates schema v2. Every edit cites supplied shot evidence and stays
54
+ inside its accepted direction shot's source range. It can trim, omit and reorder
55
+ shots while protecting the brief's essential shots. The target is 45–60 seconds,
56
+ with a bounded 30–75 second allowance. The application compiles source spans using
57
+ rational PTS and rebuilds positions and subtitle timing from the resulting order.
58
+
59
+ Retained speech must remain complete; partial utterances can be excluded or muted
60
+ as B-roll. Captions correspond exactly to retained complete cues. Films without
61
+ speech do not need invented captions. Cards, emphasis, transitions, SFX and motion
62
+ are optional decisions serving the film, not minimum-count completion gates.
63
+
64
+ The renderer retains the fixed, local FFmpeg/Pillow compositor: source camera audio,
65
+ CJK overlays, AI-directed regional music levels with short gain ramps, music ducking,
66
+ supported motion and dips, SDR grade, normalization and
67
+ peak limiting. It verifies dimensions, codecs, duration, frame rate/count and full
68
+ decode before publication. Human review remains pending, not silently passed.
69
+
70
+ ## Persistence and tests
71
+
72
+ Project schema v17 adds the single `produce` operation while preserving v16 trial
73
+ rows and their files. The former parameter draft workflow cannot be invoked as a
74
+ new production operation; old trials are not relabeled as v2 results. Requests are
75
+ idempotent, source snapshots immutable, failed retries preserve the last successful
76
+ film, and restart never replays a paid attempt. Usage is recorded per AI stage;
77
+ partial/unknown usage is explicit, never represented as a known zero.
78
+
79
+ The output includes a playable MP4, a decisions/timeline/source JSON record, the
80
+ music catalog snapshot, and a text credit with author, source, license and changes.
81
+ New success replaces the UI's result pointer; earlier files remain in managed storage.
82
+
83
+ Concurrent cards retain their original text and timing and stack vertically in the
84
+ upper half of the frame, leaving room for dialogue captions. Temporal overlap does
85
+ not discard otherwise valid AI output. Production inputs and raw AI decisions are
86
+ saved before local validation. Failed local work can resume using those snapshots
87
+ through `POST /api/projects/{project_id}/finishing/{run_id}/commands/resume`, without
88
+ provider calls or new music searches. A changed source context blocks this retry;
89
+ the original usage totals stay attached to the same run.
90
+
91
+ Run `PYTHONPATH=tests/python .venv/bin/python -m unittest test_finishing test_finishing_catalog`.
92
+ The tests cover actual recuts/subtitle remapping, feedback, two-stage orchestration,
93
+ source/license filtering, cancellation, recovery, and real FFmpeg composition.
94
+ Default tests use provider/network doubles and spend no AI quota. Live catalog smoke
95
+ tests are separate and do not establish the aesthetic quality of real AI edits.
96
+
97
+ Current scope: a continuous direction video track and its camera audio, up to 1080p
98
+ at 24/25/30/60 fps, SDR, supported semantic effects. Full films, HDR mastering,
99
+ independent graphics/audio tracks, and final Resolve delivery remain outside this
100
+ branch. Source references and semantic decisions remain editable for later delivery.
101
+
102
+ Sources: [Openverse audio API](https://api.openverse.org/v1/),
103
+ [Openverse media metadata](https://docs.openverse.org/meta/media_properties/api.html).
@@ -0,0 +1 @@
1
+ """Music, sound and media helpers for the finished programme."""
@@ -0,0 +1,149 @@
1
+ """Read-only local music inspection and bounded subprocess execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from array import array
6
+ import math
7
+ import os
8
+ from pathlib import Path
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+
14
+ from clipen.media.discovery import MediaDiscovery, open_file_beneath
15
+ from clipen.media.models import AssetKind, InventoryRoot
16
+ from clipen.media.probe import FFprobeAdapter, bounded_file_fingerprint
17
+ from clipen.projects import DirectoryReference, ProjectError
18
+ from clipen.projects.picker import refresh_availability
19
+
20
+ from .models import digest
21
+
22
+
23
+ def run_process(command, cancel, *, pass_fds=(), timeout=300, max_bytes=8*1024*1024):
24
+ """Drain through bounded files, poll cancellation even if FFmpeg is silent."""
25
+ with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as errors:
26
+ try:
27
+ process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=errors, pass_fds=pass_fds)
28
+ except OSError as error:
29
+ raise ProjectError("finishing_runtime_missing", "找不到可用的 FFmpeg/ffprobe。", status_code=409) from error
30
+ deadline = time.monotonic() + timeout
31
+ try:
32
+ while process.poll() is None:
33
+ if cancel.is_set():
34
+ raise ProjectError("user_cancelled", "已取消製作。", status_code=409)
35
+ if time.monotonic() >= deadline:
36
+ raise ProjectError("finishing_timeout", "本機製作超過時間上限。", status_code=409)
37
+ if os.fstat(out.fileno()).st_size > max_bytes or os.fstat(errors.fileno()).st_size > max_bytes:
38
+ raise ProjectError("finishing_output_limit", "本機工具輸出超過上限。", status_code=409)
39
+ cancel.wait(0.05)
40
+ if cancel.is_set():
41
+ raise ProjectError("user_cancelled", "已取消製作。", status_code=409)
42
+ if process.returncode:
43
+ raise ProjectError("finishing_render_failed", "本機製作失敗,請檢查素材格式與磁碟。", status_code=409)
44
+ out.seek(0)
45
+ result = out.read(max_bytes + 1)
46
+ if len(result) > max_bytes:
47
+ raise ProjectError("finishing_output_limit", "本機工具輸出超過上限。", status_code=409)
48
+ return result
49
+ finally:
50
+ if process.poll() is None:
51
+ process.terminate()
52
+ try:
53
+ process.wait(timeout=2)
54
+ except subprocess.TimeoutExpired:
55
+ process.kill()
56
+ process.wait()
57
+
58
+
59
+ def inventory_root(reference):
60
+ ref = DirectoryReference.from_storage(reference)
61
+ if refresh_availability(ref).availability.value != "available":
62
+ raise ProjectError("finishing_library_offline", "音樂或音效資料夾已變更或離線,請重新選擇。", status_code=409)
63
+ return InventoryRoot(ref.role, ref.canonical_path, ref.device, ref.inode, ref.saved_at)
64
+
65
+
66
+ def inspect_library(role, reference, cancel, progress):
67
+ root = inventory_root(reference)
68
+ probe = FFprobeAdapter()
69
+ assets, issues = [], []
70
+ for entry in MediaDiscovery(maximum_files=1000, maximum_seconds=60).scan(root, cancel):
71
+ if entry.kind != AssetKind.AUDIO or not entry.should_probe:
72
+ continue
73
+ if len(assets) >= 24:
74
+ issues.append({"name": "", "code": "library_limit_24"})
75
+ break
76
+ try:
77
+ result = probe.probe(root, entry, cancel)
78
+ stream = next(s for s in result.streams if s.kind == "audio")
79
+ duration = float(result.summary.get("duration_seconds", 0))
80
+ if not math.isfinite(duration) or not 0.1 <= duration <= 3600:
81
+ raise ValueError("duration unsupported")
82
+ fd = open_file_beneath(root, entry.relative_path)
83
+ try:
84
+ # Inspect at most 90 seconds: enough for a one-minute proof.
85
+ pcm = run_process([
86
+ "ffmpeg", "-v", "error", "-nostdin", "-i", f"/dev/fd/{fd}",
87
+ "-map", f"0:{stream.stream_index}", "-t", "90", "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "pipe:1",
88
+ ], cancel, pass_fds=(fd,), timeout=45, max_bytes=2*1024*1024)
89
+ finally:
90
+ os.close(fd)
91
+ samples = array('h')
92
+ samples.frombytes(pcm)
93
+ if sys.byteorder != "little": samples.byteswap()
94
+ rms = math.sqrt(sum(v*v for v in samples) / max(1, len(samples))) / 32768
95
+ if rms < 0.0001:
96
+ raise ValueError("silent audio")
97
+ beats, bpm = detect_beats(samples)
98
+ asset = {
99
+ "asset_id": "fa_" + digest([role, reference, entry.relative_path, result.fingerprint])[:32],
100
+ "role": role, "name": Path(entry.relative_path).name,
101
+ "relative_path": entry.relative_path, "size_bytes": result.size_bytes,
102
+ "mtime_ns": result.mtime_ns, "fingerprint": result.fingerprint,
103
+ "stream_index": stream.stream_index, "duration_seconds": duration,
104
+ "rms_db": round(20*math.log10(rms), 2), "peak_db": round(20*math.log10(max(abs(v) for v in samples)/32768), 2),
105
+ "beats_seconds": beats, "bpm": bpm, "analyzed_seconds": len(samples)/8000,
106
+ }
107
+ assets.append(asset)
108
+ progress(min(0.95, len(assets)/24))
109
+ except Exception as error:
110
+ if cancel.is_set(): raise
111
+ issues.append({"name": Path(entry.relative_path).name, "code": getattr(error, "code", "audio_unusable")})
112
+ return assets, issues
113
+
114
+
115
+ def detect_beats(samples):
116
+ """Energy-onset autocorrelation, with no fabricated beats for flat audio."""
117
+ hop = 160 # 20 ms, 50 observations per second
118
+ energy = [math.sqrt(sum(v*v for v in samples[i:i+hop])/hop) for i in range(0, len(samples)-hop, hop)]
119
+ onsets = [max(0., energy[i]-energy[i-1]) for i in range(1, len(energy))]
120
+ if not onsets or max(onsets) < 30:
121
+ return [], None
122
+ scores = [(sum(onsets[i]*onsets[i-lag] for i in range(lag, len(onsets))), lag) for lag in range(17, 51)]
123
+ score, lag = max(scores)
124
+ if score <= 0: return [], None
125
+ # Return observed onset peaks near the periodic pulse; do not invent timestamps.
126
+ phase = max(range(lag), key=lambda p: sum(onsets[p::lag]))
127
+ beats = []
128
+ for index in range(phase, len(onsets), lag):
129
+ low, high = max(0,index-3), min(len(onsets),index+4)
130
+ peak = max(range(low,high), key=lambda i:onsets[i])
131
+ if onsets[peak] > max(onsets)*0.08:
132
+ value = round((peak+1)*hop/8000, 3)
133
+ if not beats or value-beats[-1] > .20: beats.append(value)
134
+ return beats[:300], round(3000/lag, 1)
135
+
136
+
137
+ def open_asset(context, asset_id):
138
+ asset = next((a for a in context["assets"] if a["asset_id"] == asset_id), None)
139
+ if asset is None:
140
+ raise ProjectError("finishing_asset_missing", "找不到指定的音樂或音效。", status_code=409)
141
+ fd = open_file_beneath(inventory_root(context["directories"][asset["role"]]), asset["relative_path"])
142
+ try:
143
+ info = os.fstat(fd)
144
+ if info.st_size != asset["size_bytes"] or info.st_mtime_ns != asset["mtime_ns"] or bounded_file_fingerprint(fd, info.st_size) != asset["fingerprint"]:
145
+ raise ProjectError("media_changed", "音樂或音效已變更,請重新檢查。", status_code=409)
146
+ return fd, asset
147
+ except Exception:
148
+ os.close(fd)
149
+ raise
@@ -0,0 +1,181 @@
1
+ """Bounded public music discovery with retained source and license evidence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import socket
7
+ import ipaddress
8
+ import time
9
+ from urllib.error import HTTPError, URLError
10
+ from urllib.parse import urlencode, urlsplit, urljoin
11
+ from urllib.request import Request, build_opener, HTTPRedirectHandler
12
+
13
+ from clipen.projects import DirectoryReference, DirectoryRole, ProjectError
14
+ from clipen.projects.storage import utc_now
15
+
16
+ from .audio import inspect_library
17
+ from clipen.music_vocabulary import MUSIC_TAGS
18
+
19
+ from .models import digest, encoded
20
+
21
+
22
+ _HOSTS = {'api.openverse.org', 'prod-1.storage.jamendo.com', 'prod-2.storage.jamendo.com',
23
+ 'cdn.freesound.org', 'freesound.org', 'www.jamendo.com', 'ccmixter.org',
24
+ 'dig.ccmixter.org', 'upload.wikimedia.org', 'commons.wikimedia.org'}
25
+ _USER_AGENT = 'Clipen/0.0 (+https://github.com/IMGMANISME/clipen)'
26
+
27
+
28
+ class NoRedirect(HTTPRedirectHandler):
29
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
30
+ return None
31
+
32
+
33
+ def checked_url(url):
34
+ if not isinstance(url, str) or len(url) > 2048:
35
+ raise ValueError('invalid catalog URL')
36
+ parsed = urlsplit(url)
37
+ if parsed.scheme != 'https' or parsed.hostname not in _HOSTS or parsed.username or parsed.password or parsed.port not in (None,443):
38
+ raise ValueError('unapproved catalog destination')
39
+ addresses = socket.getaddrinfo(parsed.hostname,443,type=socket.SOCK_STREAM)
40
+ if not addresses or any(not ipaddress.ip_address(a[4][0]).is_global for a in addresses):
41
+ raise ValueError('non-public catalog address')
42
+ return url
43
+
44
+
45
+ class PublicMusicCatalog:
46
+ """Only musical vocabulary is searched; private project text is never queried."""
47
+
48
+ def fetch(self, url, cancel, *, limit=2*1024*1024, destination=None):
49
+ opener = build_opener(NoRedirect)
50
+ deadline = time.monotonic()+60
51
+ for _ in range(4):
52
+ if cancel.is_set():
53
+ raise ProjectError('user_cancelled','已取消自動配樂。',status_code=409)
54
+ checked_url(url)
55
+ try:
56
+ response = opener.open(Request(url,headers={'User-Agent':_USER_AGENT,'Accept':'application/json, audio/*;q=0.9, text/html;q=0.5'}),timeout=15)
57
+ except HTTPError as error:
58
+ if error.code in {301,302,303,307,308} and error.headers.get('Location'):
59
+ url = urljoin(url,error.headers['Location'])
60
+ error.close()
61
+ continue
62
+ raise
63
+ with response:
64
+ length = response.headers.get('Content-Length')
65
+ if length and int(length) > limit:
66
+ raise ValueError('catalog response too large')
67
+ data = bytearray()
68
+ output = None if destination is None else destination.open('xb')
69
+ size = 0
70
+ try:
71
+ while True:
72
+ if cancel.is_set():
73
+ raise ProjectError('user_cancelled','已取消自動配樂。',status_code=409)
74
+ if time.monotonic() > deadline:
75
+ raise TimeoutError('music transfer exceeded its time bound')
76
+ block = response.read(65536)
77
+ if not block: break
78
+ size += len(block)
79
+ if size > limit: raise ValueError('catalog response too large')
80
+ if output is None: data.extend(block)
81
+ else: output.write(block)
82
+ finally:
83
+ if output is not None: output.close()
84
+ return bytes(data)
85
+ raise ValueError('too many catalog redirects')
86
+
87
+ def search_and_prepare(self, brief, directory, cancel, progress):
88
+ tags = brief['music_tags']
89
+ if not tags or any(t not in MUSIC_TAGS for t in tags):
90
+ raise ProjectError('finishing_music_query_invalid','AI 配樂方向無效。',status_code=422)
91
+ directory.mkdir(mode=0o700,exist_ok=False)
92
+ metadata = {}
93
+ issues = []
94
+ # Two bounded searches; choose music tagged instrumental, never field recordings.
95
+ queries = [tags[0]+' instrumental']
96
+ if len(tags)>1: queries.append(tags[1]+' instrumental')
97
+ for query in dict.fromkeys(queries):
98
+ try:
99
+ url = 'https://api.openverse.org/v1/audio/?'+urlencode({'q':query,'license':'cc0,by','page_size':8})
100
+ result = json.loads(self.fetch(url,cancel))
101
+ for raw in result.get('results',[])[:8]:
102
+ candidate = normalize_candidate(raw)
103
+ if candidate is not None:
104
+ metadata.setdefault(candidate['catalog_id'],candidate)
105
+ except (HTTPError,URLError,TimeoutError,OSError,ValueError):
106
+ issues.append({'code':'search_unavailable','query':query})
107
+ if not metadata:
108
+ raise ProjectError('finishing_catalog_unavailable','目前搜尋不到可用配樂,請稍後重試。',status_code=409)
109
+ # Metadata tags are catalog evidence, not a claim that Codex heard the music.
110
+ ranked = sorted(metadata.values(),key=lambda c:sum(t in c['tags'] for t in tags),reverse=True)
111
+ downloaded = {}
112
+ for candidate in ranked[:8]:
113
+ if len(downloaded) >= 3: break
114
+ path = None
115
+ try:
116
+ # Refresh the exact candidate immediately before acquisition.
117
+ raw = json.loads(self.fetch('https://api.openverse.org/v1/audio/'+candidate['catalog_id']+'/',cancel))
118
+ current = normalize_candidate(raw)
119
+ if current is None: continue
120
+ name = 'music-'+digest(current['catalog_id'])[:24]+'.mp3'
121
+ path = directory/name
122
+ self.fetch(current['download_url'],cancel,limit=24*1024*1024,destination=path)
123
+ downloaded[name] = current
124
+ progress(.25+len(downloaded)*.1)
125
+ except Exception as error:
126
+ if cancel.is_set(): raise
127
+ if path is not None: path.unlink(missing_ok=True)
128
+ issues.append({'code':'candidate_unavailable','title':candidate['title']})
129
+ if not downloaded:
130
+ raise ProjectError('finishing_music_unavailable','找不到可下載且有完整授權資料的配樂,請調整影片方向或稍後重試。',status_code=409)
131
+ info = directory.stat()
132
+ reference = DirectoryReference(DirectoryRole.SOURCE,str(directory.resolve()),directory.name,directory.name,
133
+ info.st_dev,info.st_ino,utc_now()).to_storage()
134
+ assets, audio_issues = inspect_library('music',reference,cancel,lambda value:progress(.55+value*.4))
135
+ prepared = []
136
+ for asset in assets:
137
+ item = downloaded.get(asset['name'])
138
+ if item is None or asset['duration_seconds'] < 30: continue
139
+ asset['name'] = item['title']
140
+ asset['tags'] = item['tags']
141
+ asset['genres'] = item['genres']
142
+ asset['provenance'] = {k:v for k,v in item.items() if k != 'download_url'} | {
143
+ 'retrieved_at':utc_now(), 'verification':'catalog_metadata',
144
+ 'changes':'Clipen 將本曲截取、調整音量並混入影片。',
145
+ }
146
+ prepared.append(asset)
147
+ if not prepared:
148
+ raise ProjectError('finishing_music_unusable','候選配樂無法解碼或長度不足,請重新搜尋。',status_code=409)
149
+ # Keep the exact metadata consulted; future index updates do not rewrite this record.
150
+ (directory/'sources.json').write_text(encoded({'queries':queries,'sources':[a['provenance'] for a in prepared],'issues':issues+audio_issues}))
151
+ return prepared, reference
152
+
153
+
154
+ def normalize_candidate(raw):
155
+ """Exclude restrictive/unknown license metadata rather than inventing rights."""
156
+ if not isinstance(raw,dict): return None
157
+ license_id = raw.get('license')
158
+ version = str(raw.get('license_version') or '')
159
+ expected = 'https://creativecommons.org/publicdomain/zero/1.0/' if license_id == 'cc0' else f'https://creativecommons.org/licenses/by/{version}/'
160
+ license_url = str(raw.get('license_url') or '').replace('http://','https://')
161
+ if license_id not in {'cc0','by'} or license_url != expected or (license_id=='by' and version not in {'1.0','2.0','2.5','3.0','4.0'}):
162
+ return None
163
+ from uuid import UUID
164
+ try:
165
+ identifier = str(UUID(raw['id']))
166
+ duration = float(raw.get('duration',0))/1000
167
+ download = urlsplit(raw['url'])
168
+ landing = urlsplit(raw['foreign_landing_url'])
169
+ tags = [t['name'].lower() for t in (raw.get('tags') or []) if isinstance(t,dict) and isinstance(t.get('name'),str)][:80]
170
+ if not 30 <= duration <= 3600 or 'instrumental' not in tags: return None
171
+ if download.scheme!='https' or download.hostname not in _HOSTS or landing.scheme not in {'http','https'} or landing.hostname not in _HOSTS: return None
172
+ if any(part.username or part.password or part.port not in (None,443) for part in (download,landing)): return None
173
+ title, creator = raw.get('title'), raw.get('creator')
174
+ if not isinstance(title,str) or not title.strip() or not isinstance(creator,str) or not creator.strip(): return None
175
+ return {'catalog_id':identifier,'title':title[:255],'creator':creator[:255],
176
+ 'source_url':raw['foreign_landing_url'].replace('http://','https://'),
177
+ 'download_url':raw['url'],'license':license_id,'license_version':version,'license_url':expected,
178
+ 'attribution':f'{title[:255]} — {creator[:255]}. {expected} {raw["foreign_landing_url"]}',
179
+ 'tags':tags,'genres':[str(g)[:80] for g in (raw.get('genres') or [])[:12]],
180
+ 'catalog_url':'https://api.openverse.org/v1/audio/'+identifier+'/'}
181
+ except (KeyError,TypeError,ValueError): return None
@@ -0,0 +1,14 @@
1
+ """Stable encodings shared by Clipen's music and production records."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+
8
+
9
+ def encoded(value):
10
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
11
+
12
+
13
+ def digest(value):
14
+ return hashlib.sha256(encoded(value).encode()).hexdigest()
@@ -0,0 +1,26 @@
1
+ """Check a rendered programme against its timeline before Clipen hands it over."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from clipen.projects import ProjectError
8
+
9
+ from .audio import run_process
10
+
11
+
12
+ def verify_output(path,timeline,cancel):
13
+ raw=run_process(['ffprobe','-v','error','-show_streams','-show_format','-of','json',str(path)],cancel,timeout=20)
14
+ value=json.loads(raw)
15
+ videos=[s for s in value['streams'] if s['codec_type']=='video']
16
+ audios=[s for s in value['streams'] if s['codec_type']=='audio']
17
+ fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
18
+ duration=timeline.duration_frames/fps
19
+ if len(videos)!=1 or len(audios)!=1 or (videos[0]['width'],videos[0]['height'])!=(timeline.width,timeline.height):
20
+ raise ProjectError('finishing_verification_failed','成片的影像或聲音規格不完整。',status_code=409)
21
+ from fractions import Fraction
22
+ if videos[0]['codec_name']!='h264' or audios[0]['codec_name']!='aac' or Fraction(videos[0]['avg_frame_rate']) != Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator) or abs(int(videos[0].get('nb_frames',0))-timeline.duration_frames)>1:
23
+ raise ProjectError('finishing_verification_failed',f'成片的編碼、格率或格數與時間軸不一致:{videos[0]["codec_name"]}/{audios[0]["codec_name"]},格率 {videos[0]["avg_frame_rate"]},格數 {videos[0].get("nb_frames",0)}(預期 {timeline.duration_frames})。',status_code=409)
24
+ if any(abs(float(s.get('duration',0))-duration)>max(.1,2/fps) for s in (videos[0],audios[0])):
25
+ raise ProjectError('finishing_verification_failed','成片的影音長度與時間軸不一致。',status_code=409)
26
+ run_process(['ffmpeg','-v','error','-xerror','-nostdin','-i',str(path),'-f','null','-'],cancel,timeout=90)
@@ -0,0 +1,5 @@
1
+ """Project-scoped MCP server for bounded AI editing."""
2
+
3
+ from .server import EditingMcpServer, run_stdio
4
+
5
+ __all__ = ["EditingMcpServer", "run_stdio"]
@@ -0,0 +1,40 @@
1
+ """Run the project-scoped Clipen editing MCP server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ from clipen.editing import EditAgentRepository, EditAgentTools
9
+ from clipen.projects import ProjectRepository
10
+
11
+ from .server import EditingMcpServer, run_stdio
12
+
13
+
14
+ def main() -> int:
15
+ parser = argparse.ArgumentParser(add_help=False)
16
+ parser.add_argument("--projects-root", required=True)
17
+ parser.add_argument("--project-id", required=True)
18
+ parser.add_argument("--run-id", required=True)
19
+ parser.add_argument("--data-root")
20
+ parser.add_argument("--asr-requirements")
21
+ arguments = parser.parse_args()
22
+ projects = ProjectRepository(Path(arguments.projects_root))
23
+ repository = EditAgentRepository(projects)
24
+ tools = EditAgentTools(repository, arguments.project_id, arguments.run_id)
25
+ setup = None
26
+ if arguments.data_root and arguments.asr_requirements:
27
+ from clipen.analysis.setup import ASRSetupManager
28
+ setup = ASRSetupManager(Path(arguments.data_root), Path(arguments.asr_requirements))
29
+ tools.local_data_root = Path(arguments.data_root)
30
+ tools.transcriber_binding = setup.runtime_binding
31
+ tools.asr_setup_manager = setup
32
+ try:
33
+ return run_stdio(EditingMcpServer(tools))
34
+ finally:
35
+ tools.close_production()
36
+ if setup:setup.close()
37
+
38
+
39
+ if __name__ == "__main__":
40
+ raise SystemExit(main())