@clipen/clipen-cli 1.0.0 → 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.
Files changed (127) hide show
  1. package/README.md +60 -50
  2. package/package.json +7 -4
  3. package/pyproject.toml +18 -2
  4. package/requirements/dev.txt +2 -0
  5. package/src/clipen/__init__.py +1 -1
  6. package/src/clipen/analysis/__init__.py +7 -7
  7. package/src/clipen/analysis/artifacts.py +4 -10
  8. package/src/clipen/analysis/audio.py +10 -8
  9. package/src/clipen/analysis/evidence_service.py +345 -167
  10. package/src/clipen/analysis/image_similarity.py +5 -14
  11. package/src/clipen/analysis/keyframes.py +5 -17
  12. package/src/clipen/analysis/models.py +5 -7
  13. package/src/clipen/analysis/qwen_worker.py +19 -54
  14. package/src/clipen/analysis/resources.py +2 -1
  15. package/src/clipen/analysis/runtime.py +1 -3
  16. package/src/clipen/analysis/service.py +16 -48
  17. package/src/clipen/analysis/setup.py +11 -25
  18. package/src/clipen/analysis/setup_cli.py +5 -15
  19. package/src/clipen/analysis/storage.py +96 -278
  20. package/src/clipen/analysis/transcription.py +40 -82
  21. package/src/clipen/analysis/visual.py +109 -48
  22. package/src/clipen/annotations/__init__.py +5 -2
  23. package/src/clipen/annotations/models.py +1 -1
  24. package/src/clipen/annotations/storage.py +132 -84
  25. package/src/clipen/annotations/suggestions.py +3 -8
  26. package/src/clipen/asr_release.py +4 -11
  27. package/src/clipen/bootstrap.py +65 -54
  28. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  29. package/src/clipen/cli.py +2 -2
  30. package/src/clipen/controller/app.py +401 -214
  31. package/src/clipen/controller/server.py +28 -38
  32. package/src/clipen/domain/__init__.py +1 -1
  33. package/src/clipen/domain/media_time.py +3 -10
  34. package/src/clipen/domain/timeline.py +45 -47
  35. package/src/clipen/domain/validation.py +0 -1
  36. package/src/clipen/editing/__init__.py +1 -1
  37. package/src/clipen/editing/agent_models.py +4 -11
  38. package/src/clipen/editing/agent_repository.py +391 -170
  39. package/src/clipen/editing/agent_tools.py +180 -99
  40. package/src/clipen/editing/alignment.py +92 -52
  41. package/src/clipen/editing/alignment_setup.py +118 -70
  42. package/src/clipen/editing/alignment_worker.py +11 -9
  43. package/src/clipen/editing/change_report.py +95 -38
  44. package/src/clipen/editing/compiler.py +0 -1
  45. package/src/clipen/editing/component_looks.py +58 -34
  46. package/src/clipen/editing/component_review.py +34 -38
  47. package/src/clipen/editing/coordinator.py +213 -90
  48. package/src/clipen/editing/editorial_review.py +217 -95
  49. package/src/clipen/editing/evidence_jobs.py +457 -200
  50. package/src/clipen/editing/history_changes.py +129 -68
  51. package/src/clipen/editing/music_choices.py +8 -5
  52. package/src/clipen/editing/production_catalog.py +573 -136
  53. package/src/clipen/editing/production_limits.py +43 -17
  54. package/src/clipen/editing/production_media.py +376 -167
  55. package/src/clipen/editing/production_preview.py +322 -129
  56. package/src/clipen/editing/production_progress.py +164 -69
  57. package/src/clipen/editing/production_requirements.py +106 -39
  58. package/src/clipen/editing/production_tools.py +1064 -462
  59. package/src/clipen/editing/program_audio.py +211 -81
  60. package/src/clipen/editing/program_direction.py +59 -25
  61. package/src/clipen/editing/program_story.py +83 -45
  62. package/src/clipen/editing/program_subtitles.py +194 -96
  63. package/src/clipen/editing/programme_review.py +98 -50
  64. package/src/clipen/editing/prompt_history.py +64 -27
  65. package/src/clipen/editing/recut.py +65 -25
  66. package/src/clipen/editing/refinement_references.py +176 -86
  67. package/src/clipen/editing/resolve_export.py +449 -218
  68. package/src/clipen/editing/resolve_titles.py +162 -105
  69. package/src/clipen/editing/skill_tools.py +530 -154
  70. package/src/clipen/editing/source_dialogue.py +177 -67
  71. package/src/clipen/editing/speech_coverage.py +42 -22
  72. package/src/clipen/editing/speech_quality.py +6 -1
  73. package/src/clipen/editing/tool_receipts.py +78 -32
  74. package/src/clipen/editing/versions.py +122 -64
  75. package/src/clipen/editing/visual_preview.py +157 -61
  76. package/src/clipen/editing/workbench.py +104 -42
  77. package/src/clipen/finishing/audio.py +69 -30
  78. package/src/clipen/finishing/catalog.py +176 -93
  79. package/src/clipen/finishing/models.py +1 -1
  80. package/src/clipen/finishing/renderer.py +33 -14
  81. package/src/clipen/mcp_editing/__main__.py +3 -1
  82. package/src/clipen/mcp_editing/server.py +77 -34
  83. package/src/clipen/media/__init__.py +3 -3
  84. package/src/clipen/media/discovery.py +7 -20
  85. package/src/clipen/media/models.py +7 -18
  86. package/src/clipen/media/preview.py +14 -24
  87. package/src/clipen/media/probe.py +16 -44
  88. package/src/clipen/media/service.py +6 -19
  89. package/src/clipen/media/storage.py +33 -81
  90. package/src/clipen/music_vocabulary.py +33 -4
  91. package/src/clipen/power.py +8 -3
  92. package/src/clipen/projects/__init__.py +1 -1
  93. package/src/clipen/projects/deletion.py +19 -32
  94. package/src/clipen/projects/finishing_schema.py +3 -1
  95. package/src/clipen/projects/models.py +2 -5
  96. package/src/clipen/projects/picker.py +13 -37
  97. package/src/clipen/projects/service.py +8 -24
  98. package/src/clipen/projects/storage.py +226 -246
  99. package/src/clipen/provider_registry.py +4 -2
  100. package/src/clipen/providers/account.py +86 -35
  101. package/src/clipen/providers/claude.py +59 -25
  102. package/src/clipen/providers/claude_editing.py +14 -7
  103. package/src/clipen/providers/codex.py +73 -118
  104. package/src/clipen/providers/codex_editing.py +2 -2
  105. package/src/clipen/providers/editing_agent.py +19 -17
  106. package/src/clipen/providers/recovery.py +7 -8
  107. package/src/clipen/rendering/cover.py +18 -5
  108. package/src/clipen/rendering/custom_components.py +167 -79
  109. package/src/clipen/rendering/custom_render.py +62 -41
  110. package/src/clipen/rendering/production_effects.py +77 -45
  111. package/src/clipen/rendering/program_components.py +134 -73
  112. package/src/clipen/rendering/program_creator.py +432 -277
  113. package/src/clipen/rendering/program_identities.py +277 -182
  114. package/src/clipen/rendering/program_motion.py +140 -95
  115. package/src/clipen/rendering/program_studio.py +175 -116
  116. package/src/clipen/rendering/program_styles.py +231 -145
  117. package/src/clipen/rendering/program_subtitles.py +71 -34
  118. package/src/clipen/rendering/renderer.py +150 -121
  119. package/src/clipen/rendering/storage.py +9 -22
  120. package/src/clipen/rendering/titles.py +193 -86
  121. package/src/clipen/skills/__init__.py +1 -0
  122. package/src/clipen/skills/catalog.py +151 -55
  123. package/src/clipen/skills/library.py +13 -7
  124. package/src/clipen/skills/package.py +46 -23
  125. package/src/clipen/skills/visual_styles.py +29 -18
  126. package/src/clipen/workspace.py +15 -44
  127. package/src/clipen/planning/__init__.py +0 -9
@@ -2,27 +2,34 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import ipaddress
5
6
  import json
6
7
  import socket
7
- import ipaddress
8
8
  import time
9
9
  from urllib.error import HTTPError, URLError
10
- from urllib.parse import urlencode, urlsplit, urljoin
11
- from urllib.request import Request, build_opener, HTTPRedirectHandler
10
+ from urllib.parse import urlencode, urljoin, urlsplit
11
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
12
12
 
13
+ from clipen.music_vocabulary import MUSIC_TAGS
13
14
  from clipen.projects import DirectoryReference, DirectoryRole, ProjectError
14
15
  from clipen.projects.storage import utc_now
15
16
 
16
17
  from .audio import inspect_library
17
- from clipen.music_vocabulary import MUSIC_TAGS
18
-
19
18
  from .models import digest, encoded
20
19
 
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)'
20
+ _HOSTS = {
21
+ "api.openverse.org",
22
+ "prod-1.storage.jamendo.com",
23
+ "prod-2.storage.jamendo.com",
24
+ "cdn.freesound.org",
25
+ "freesound.org",
26
+ "www.jamendo.com",
27
+ "ccmixter.org",
28
+ "dig.ccmixter.org",
29
+ "upload.wikimedia.org",
30
+ "commons.wikimedia.org",
31
+ }
32
+ _USER_AGENT = "Clipen/0.0 (+https://github.com/IMGMANISME/clipen)"
26
33
 
27
34
 
28
35
  class NoRedirect(HTTPRedirectHandler):
@@ -32,150 +39,226 @@ class NoRedirect(HTTPRedirectHandler):
32
39
 
33
40
  def checked_url(url):
34
41
  if not isinstance(url, str) or len(url) > 2048:
35
- raise ValueError('invalid catalog URL')
42
+ raise ValueError("invalid catalog URL")
36
43
  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)
44
+ if (
45
+ parsed.scheme != "https"
46
+ or parsed.hostname not in _HOSTS
47
+ or parsed.username
48
+ or parsed.password
49
+ or parsed.port not in (None, 443)
50
+ ):
51
+ raise ValueError("unapproved catalog destination")
52
+ addresses = socket.getaddrinfo(parsed.hostname, 443, type=socket.SOCK_STREAM)
40
53
  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')
54
+ raise ValueError("non-public catalog address")
42
55
  return url
43
56
 
44
57
 
45
58
  class PublicMusicCatalog:
46
59
  """Only musical vocabulary is searched; private project text is never queried."""
47
60
 
48
- def fetch(self, url, cancel, *, limit=2*1024*1024, destination=None):
61
+ def fetch(self, url, cancel, *, limit=2 * 1024 * 1024, destination=None):
49
62
  opener = build_opener(NoRedirect)
50
- deadline = time.monotonic()+60
63
+ deadline = time.monotonic() + 60
51
64
  for _ in range(4):
52
65
  if cancel.is_set():
53
- raise ProjectError('user_cancelled','已取消自動配樂。',status_code=409)
66
+ raise ProjectError("user_cancelled", "已取消自動配樂。", status_code=409)
54
67
  checked_url(url)
55
68
  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)
69
+ response = opener.open(
70
+ Request(
71
+ url,
72
+ headers={
73
+ "User-Agent": _USER_AGENT,
74
+ "Accept": "application/json, audio/*;q=0.9, text/html;q=0.5",
75
+ },
76
+ ),
77
+ timeout=15,
78
+ )
57
79
  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'])
80
+ if error.code in {301, 302, 303, 307, 308} and error.headers.get("Location"):
81
+ url = urljoin(url, error.headers["Location"])
60
82
  error.close()
61
83
  continue
62
84
  raise
63
85
  with response:
64
- length = response.headers.get('Content-Length')
86
+ length = response.headers.get("Content-Length")
65
87
  if length and int(length) > limit:
66
- raise ValueError('catalog response too large')
88
+ raise ValueError("catalog response too large")
67
89
  data = bytearray()
68
- output = None if destination is None else destination.open('xb')
90
+ output = None if destination is None else destination.open("xb")
69
91
  size = 0
70
92
  try:
71
93
  while True:
72
94
  if cancel.is_set():
73
- raise ProjectError('user_cancelled','已取消自動配樂。',status_code=409)
95
+ raise ProjectError("user_cancelled", "已取消自動配樂。", status_code=409)
74
96
  if time.monotonic() > deadline:
75
- raise TimeoutError('music transfer exceeded its time bound')
97
+ raise TimeoutError("music transfer exceeded its time bound")
76
98
  block = response.read(65536)
77
- if not block: break
99
+ if not block:
100
+ break
78
101
  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)
102
+ if size > limit:
103
+ raise ValueError("catalog response too large")
104
+ if output is None:
105
+ data.extend(block)
106
+ else:
107
+ output.write(block)
82
108
  finally:
83
- if output is not None: output.close()
109
+ if output is not None:
110
+ output.close()
84
111
  return bytes(data)
85
- raise ValueError('too many catalog redirects')
112
+ raise ValueError("too many catalog redirects")
86
113
 
87
114
  def search_and_prepare(self, brief, directory, cancel, progress):
88
- tags = brief['music_tags']
115
+ tags = brief["music_tags"]
89
116
  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)
117
+ raise ProjectError("finishing_music_query_invalid", "AI 配樂方向無效。", status_code=422)
118
+ directory.mkdir(mode=0o700, exist_ok=False)
92
119
  metadata = {}
93
120
  issues = []
94
121
  # 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')
122
+ queries = [tags[0] + " instrumental"]
123
+ if len(tags) > 1:
124
+ queries.append(tags[1] + " instrumental")
97
125
  for query in dict.fromkeys(queries):
98
126
  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]:
127
+ url = "https://api.openverse.org/v1/audio/?" + urlencode(
128
+ {"q": query, "license": "cc0,by", "page_size": 8}
129
+ )
130
+ result = json.loads(self.fetch(url, cancel))
131
+ for raw in result.get("results", [])[:8]:
102
132
  candidate = normalize_candidate(raw)
103
133
  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})
134
+ metadata.setdefault(candidate["catalog_id"], candidate)
135
+ except (HTTPError, URLError, TimeoutError, OSError, ValueError):
136
+ issues.append({"code": "search_unavailable", "query": query})
107
137
  if not metadata:
108
- raise ProjectError('finishing_catalog_unavailable','目前搜尋不到可用配樂,請稍後重試。',status_code=409)
138
+ raise ProjectError("finishing_catalog_unavailable", "目前搜尋不到可用配樂,請稍後重試。", status_code=409)
109
139
  # 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)
140
+ ranked = sorted(metadata.values(), key=lambda c: sum(t in c["tags"] for t in tags), reverse=True)
111
141
  downloaded = {}
112
142
  for candidate in ranked[:8]:
113
- if len(downloaded) >= 3: break
143
+ if len(downloaded) >= 3:
144
+ break
114
145
  path = None
115
146
  try:
116
147
  # Refresh the exact candidate immediately before acquisition.
117
- raw = json.loads(self.fetch('https://api.openverse.org/v1/audio/'+candidate['catalog_id']+'/',cancel))
148
+ raw = json.loads(
149
+ self.fetch("https://api.openverse.org/v1/audio/" + candidate["catalog_id"] + "/", cancel)
150
+ )
118
151
  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)
152
+ if current is None:
153
+ continue
154
+ name = "music-" + digest(current["catalog_id"])[:24] + ".mp3"
155
+ path = directory / name
156
+ self.fetch(current["download_url"], cancel, limit=24 * 1024 * 1024, destination=path)
123
157
  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']})
158
+ progress(0.25 + len(downloaded) * 0.1)
159
+ except Exception:
160
+ if cancel.is_set():
161
+ raise
162
+ if path is not None:
163
+ path.unlink(missing_ok=True)
164
+ issues.append({"code": "candidate_unavailable", "title": candidate["title"]})
129
165
  if not downloaded:
130
- raise ProjectError('finishing_music_unavailable','找不到可下載且有完整授權資料的配樂,請調整影片方向或稍後重試。',status_code=409)
166
+ raise ProjectError(
167
+ "finishing_music_unavailable",
168
+ "找不到可下載且有完整授權資料的配樂,請調整影片方向或稍後重試。",
169
+ status_code=409,
170
+ )
131
171
  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))
172
+ reference = DirectoryReference(
173
+ DirectoryRole.SOURCE,
174
+ str(directory.resolve()),
175
+ directory.name,
176
+ directory.name,
177
+ info.st_dev,
178
+ info.st_ino,
179
+ utc_now(),
180
+ ).to_storage()
181
+ assets, audio_issues = inspect_library("music", reference, cancel, lambda value: progress(0.55 + value * 0.4))
135
182
  prepared = []
136
183
  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 將本曲截取、調整音量並混入影片。',
184
+ item = downloaded.get(asset["name"])
185
+ if item is None or asset["duration_seconds"] < 30:
186
+ continue
187
+ asset["name"] = item["title"]
188
+ asset["tags"] = item["tags"]
189
+ asset["genres"] = item["genres"]
190
+ asset["provenance"] = {k: v for k, v in item.items() if k != "download_url"} | {
191
+ "retrieved_at": utc_now(),
192
+ "verification": "catalog_metadata",
193
+ "changes": "Clipen 將本曲截取、調整音量並混入影片。",
145
194
  }
146
195
  prepared.append(asset)
147
196
  if not prepared:
148
- raise ProjectError('finishing_music_unusable','候選配樂無法解碼或長度不足,請重新搜尋。',status_code=409)
197
+ raise ProjectError("finishing_music_unusable", "候選配樂無法解碼或長度不足,請重新搜尋。", status_code=409)
149
198
  # 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}))
199
+ (directory / "sources.json").write_text(
200
+ encoded(
201
+ {"queries": queries, "sources": [a["provenance"] for a in prepared], "issues": issues + audio_issues}
202
+ )
203
+ )
151
204
  return prepared, reference
152
205
 
153
206
 
154
207
  def normalize_candidate(raw):
155
208
  """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'}):
209
+ if not isinstance(raw, dict):
210
+ return None
211
+ license_id = raw.get("license")
212
+ version = str(raw.get("license_version") or "")
213
+ expected = (
214
+ "https://creativecommons.org/publicdomain/zero/1.0/"
215
+ if license_id == "cc0"
216
+ else f"https://creativecommons.org/licenses/by/{version}/"
217
+ )
218
+ license_url = str(raw.get("license_url") or "").replace("http://", "https://")
219
+ if (
220
+ license_id not in {"cc0", "by"}
221
+ or license_url != expected
222
+ or (license_id == "by" and version not in {"1.0", "2.0", "2.5", "3.0", "4.0"})
223
+ ):
162
224
  return None
163
225
  from uuid import UUID
226
+
164
227
  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
228
+ identifier = str(UUID(raw["id"]))
229
+ duration = float(raw.get("duration", 0)) / 1000
230
+ download = urlsplit(raw["url"])
231
+ landing = urlsplit(raw["foreign_landing_url"])
232
+ tags = [
233
+ t["name"].lower() for t in (raw.get("tags") or []) if isinstance(t, dict) and isinstance(t.get("name"), str)
234
+ ][:80]
235
+ if not 30 <= duration <= 3600 or "instrumental" not in tags:
236
+ return None
237
+ if (
238
+ download.scheme != "https"
239
+ or download.hostname not in _HOSTS
240
+ or landing.scheme not in {"http", "https"}
241
+ or landing.hostname not in _HOSTS
242
+ ):
243
+ return None
244
+ if any(part.username or part.password or part.port not in (None, 443) for part in (download, landing)):
245
+ return None
246
+ title, creator = raw.get("title"), raw.get("creator")
247
+ if not isinstance(title, str) or not title.strip() or not isinstance(creator, str) or not creator.strip():
248
+ return None
249
+ return {
250
+ "catalog_id": identifier,
251
+ "title": title[:255],
252
+ "creator": creator[:255],
253
+ "source_url": raw["foreign_landing_url"].replace("http://", "https://"),
254
+ "download_url": raw["url"],
255
+ "license": license_id,
256
+ "license_version": version,
257
+ "license_url": expected,
258
+ "attribution": f"{title[:255]} — {creator[:255]}. {expected} {raw['foreign_landing_url']}",
259
+ "tags": tags,
260
+ "genres": [str(g)[:80] for g in (raw.get("genres") or [])[:12]],
261
+ "catalog_url": "https://api.openverse.org/v1/audio/" + identifier + "/",
262
+ }
263
+ except (KeyError, TypeError, ValueError):
264
+ return None
@@ -7,7 +7,7 @@ import json
7
7
 
8
8
 
9
9
  def encoded(value):
10
- return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
10
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
11
11
 
12
12
 
13
13
  def digest(value):
@@ -9,18 +9,37 @@ from clipen.projects import ProjectError
9
9
  from .audio import run_process
10
10
 
11
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)
12
+ def verify_output(path, timeline, cancel):
13
+ raw = run_process(
14
+ ["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(path)], cancel, timeout=20
15
+ )
16
+ value = json.loads(raw)
17
+ videos = [s for s in value["streams"] if s["codec_type"] == "video"]
18
+ audios = [s for s in value["streams"] if s["codec_type"] == "audio"]
19
+ fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
20
+ duration = timeline.duration_frames / fps
21
+ if (
22
+ len(videos) != 1
23
+ or len(audios) != 1
24
+ or (videos[0]["width"], videos[0]["height"]) != (timeline.width, timeline.height)
25
+ ):
26
+ raise ProjectError("finishing_verification_failed", "成片的影像或聲音規格不完整。", status_code=409)
21
27
  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)
28
+
29
+ if (
30
+ videos[0]["codec_name"] != "h264"
31
+ or audios[0]["codec_name"] != "aac"
32
+ or Fraction(videos[0]["avg_frame_rate"])
33
+ != Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
34
+ or abs(int(videos[0].get("nb_frames", 0)) - timeline.duration_frames) > 1
35
+ ):
36
+ raise ProjectError(
37
+ "finishing_verification_failed",
38
+ f"成片的編碼、格率或格數與時間軸不一致:{videos[0]['codec_name']}/{audios[0]['codec_name']},格率 {videos[0]['avg_frame_rate']},格數 {videos[0].get('nb_frames', 0)}(預期 {timeline.duration_frames})。",
39
+ status_code=409,
40
+ )
41
+ if any(abs(float(s.get("duration", 0)) - duration) > max(0.1, 2 / fps) for s in (videos[0], audios[0])):
42
+ raise ProjectError("finishing_verification_failed", "成片的影音長度與時間軸不一致。", status_code=409)
43
+ run_process(
44
+ ["ffmpeg", "-v", "error", "-xerror", "-nostdin", "-i", str(path), "-f", "null", "-"], cancel, timeout=90
45
+ )
@@ -25,6 +25,7 @@ def main() -> int:
25
25
  setup = None
26
26
  if arguments.data_root and arguments.asr_requirements:
27
27
  from clipen.analysis.setup import ASRSetupManager
28
+
28
29
  setup = ASRSetupManager(Path(arguments.data_root), Path(arguments.asr_requirements))
29
30
  tools.local_data_root = Path(arguments.data_root)
30
31
  tools.transcriber_binding = setup.runtime_binding
@@ -33,7 +34,8 @@ def main() -> int:
33
34
  return run_stdio(EditingMcpServer(tools))
34
35
  finally:
35
36
  tools.close_production()
36
- if setup:setup.close()
37
+ if setup:
38
+ setup.close()
37
39
 
38
40
 
39
41
  if __name__ == "__main__":
@@ -3,18 +3,17 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import base64
6
+ import json
7
+ import sys
6
8
  from copy import deepcopy
7
9
  from io import BytesIO
8
- import json
9
10
  from pathlib import Path
10
- import sys
11
11
  from typing import BinaryIO, Mapping
12
12
 
13
13
  from clipen.editing import EditAgentTools, ToolResult
14
- from clipen.projects import ProjectError
15
14
  from clipen.editing.production_catalog import AGENT_TOOLS
16
15
  from clipen.editing.tool_receipts import TIMELINE_MUTATIONS
17
-
16
+ from clipen.projects import ProjectError
18
17
 
19
18
  _MAX_MESSAGE_BYTES = 1024 * 1024
20
19
  _MAX_IMAGE_BYTES = 96 * 1024
@@ -50,7 +49,7 @@ _TOOLS = (
50
49
  {
51
50
  "query": {"type": "string", "maxLength": 200},
52
51
  "limit": {"type": "integer", "minimum": 1, "maximum": 50},
53
- "offset": {"type":"integer","minimum":0,"maximum":100000},
52
+ "offset": {"type": "integer", "minimum": 0, "maximum": 100000},
54
53
  },
55
54
  ),
56
55
  _tool(
@@ -97,7 +96,12 @@ _TOOLS = (
97
96
  "maxItems": 180,
98
97
  },
99
98
  "summary": {"type": "string", "maxLength": 500},
100
- "reprise_reason": {"type":"string","minLength":1,"maxLength":500,"description":"Explicit editorial reason for intentionally repeating a source range as a cold open/callback. Without this, duplicate source ranges are rejected."},
99
+ "reprise_reason": {
100
+ "type": "string",
101
+ "minLength": 1,
102
+ "maxLength": 500,
103
+ "description": "Explicit editorial reason for intentionally repeating a source range as a cold open/callback. Without this, duplicate source ranges are rejected.",
104
+ },
101
105
  },
102
106
  ("clips", "summary"),
103
107
  ),
@@ -147,31 +151,73 @@ _TOOLS = (
147
151
  "and not_done. Anything your tools can do is done before finishing, never left in not_done. not_done and a "
148
152
  "partly/not_done note need reason needs_you (detail: what the person must decide or supply) or cannot "
149
153
  "(detail: which tool limit stops it). Do not list limits that hold every time, such as not hearing audio.",
150
- {"summary": {"type": "string", "maxLength": 1000},
151
- "changes": {"type": "array", "minItems": 1, "maxItems": 20, "items": {"type": "object", "properties": {
152
- "what": {"type": "string", "maxLength": 200}, "why": {"type": "string", "maxLength": 300}}, "required": ["what", "why"], "additionalProperties": False}},
153
- "notes": {"type": "array", "maxItems": 40, "items": {"type": "object", "properties": {
154
- "reference_id": {"type": "string", "maxLength": 160}, "outcome": {"enum": ["done", "partly", "not_done", "kept"]},
155
- "explanation": {"type": "string", "maxLength": 300}, "reason": {"enum": ["needs_you", "cannot"]}},
156
- "required": ["reference_id", "outcome", "explanation"], "additionalProperties": False}},
157
- "not_done": {"type": "array", "maxItems": 10, "items": {"type": "object", "properties": {
158
- "what": {"type": "string", "maxLength": 200}, "reason": {"enum": ["needs_you", "cannot"]},
159
- "detail": {"type": "string", "maxLength": 300}}, "required": ["what", "reason", "detail"], "additionalProperties": False}}},
154
+ {
155
+ "summary": {"type": "string", "maxLength": 1000},
156
+ "changes": {
157
+ "type": "array",
158
+ "minItems": 1,
159
+ "maxItems": 20,
160
+ "items": {
161
+ "type": "object",
162
+ "properties": {
163
+ "what": {"type": "string", "maxLength": 200},
164
+ "why": {"type": "string", "maxLength": 300},
165
+ },
166
+ "required": ["what", "why"],
167
+ "additionalProperties": False,
168
+ },
169
+ },
170
+ "notes": {
171
+ "type": "array",
172
+ "maxItems": 40,
173
+ "items": {
174
+ "type": "object",
175
+ "properties": {
176
+ "reference_id": {"type": "string", "maxLength": 160},
177
+ "outcome": {"enum": ["done", "partly", "not_done", "kept"]},
178
+ "explanation": {"type": "string", "maxLength": 300},
179
+ "reason": {"enum": ["needs_you", "cannot"]},
180
+ },
181
+ "required": ["reference_id", "outcome", "explanation"],
182
+ "additionalProperties": False,
183
+ },
184
+ },
185
+ "not_done": {
186
+ "type": "array",
187
+ "maxItems": 10,
188
+ "items": {
189
+ "type": "object",
190
+ "properties": {
191
+ "what": {"type": "string", "maxLength": 200},
192
+ "reason": {"enum": ["needs_you", "cannot"]},
193
+ "detail": {"type": "string", "maxLength": 300},
194
+ },
195
+ "required": ["what", "reason", "detail"],
196
+ "additionalProperties": False,
197
+ },
198
+ },
199
+ },
160
200
  ("summary", "changes"),
161
201
  ),
162
202
  ) + AGENT_TOOLS
163
- _TOOL_NAMES = frozenset(entry['name'] for entry in _TOOLS)
203
+ _TOOL_NAMES = frozenset(entry["name"] for entry in _TOOLS)
164
204
 
165
205
  # The same optional compare-and-swap guard applies to every independent tool.
166
206
  # Tools strip it before domain argument validation; actual revision writes also
167
207
  # check inside the SQLite transaction.
168
208
  for _entry in _TOOLS:
169
- if _entry['name'] in TIMELINE_MUTATIONS:
170
- _entry['inputSchema']['properties']['expected_revision_id'] = {
171
- 'type':'string', 'pattern':'^editrev_[0-9a-f]{32}$',
172
- 'description':'Current revision guard. A stale value fails without overwriting newer edits.'}
173
- _entry['inputSchema']['properties']['mutation_id'] = {'type':'string','minLength':1,'maxLength':160,
174
- 'description':'Unique operation key; reuse with identical arguments only when retrying the same operation.'}
209
+ if _entry["name"] in TIMELINE_MUTATIONS:
210
+ _entry["inputSchema"]["properties"]["expected_revision_id"] = {
211
+ "type": "string",
212
+ "pattern": "^editrev_[0-9a-f]{32}$",
213
+ "description": "Current revision guard. A stale value fails without overwriting newer edits.",
214
+ }
215
+ _entry["inputSchema"]["properties"]["mutation_id"] = {
216
+ "type": "string",
217
+ "minLength": 1,
218
+ "maxLength": 160,
219
+ "description": "Unique operation key; reuse with identical arguments only when retrying the same operation.",
220
+ }
175
221
 
176
222
 
177
223
  class EditingMcpServer:
@@ -210,13 +256,15 @@ class EditingMcpServer:
210
256
  if method == "ping":
211
257
  return self._result(identifier, {})
212
258
  if method == "tools/list":
213
- entries=deepcopy(list(_TOOLS))
259
+ entries = deepcopy(list(_TOOLS))
214
260
  for entry in entries:
215
- if entry['name'] in TIMELINE_MUTATIONS:
261
+ if entry["name"] in TIMELINE_MUTATIONS:
216
262
  # Rebind instead of extending: tools may share one required
217
263
  # list, and duplicates make the schema invalid for strict providers.
218
- required=entry['inputSchema'].get('required',[])
219
- entry['inputSchema']['required']=required+[k for k in ('expected_revision_id','mutation_id') if k not in required]
264
+ required = entry["inputSchema"].get("required", [])
265
+ entry["inputSchema"]["required"] = required + [
266
+ k for k in ("expected_revision_id", "mutation_id") if k not in required
267
+ ]
220
268
  return self._result(identifier, {"tools": entries})
221
269
  if method == "tools/call":
222
270
  return self._call_tool(identifier, params)
@@ -267,9 +315,7 @@ class EditingMcpServer:
267
315
 
268
316
  @staticmethod
269
317
  def _content(result: ToolResult) -> dict[str, object]:
270
- content: list[dict[str, object]] = [
271
- {"type": "text", "text": json.dumps(result.payload, ensure_ascii=False)}
272
- ]
318
+ content: list[dict[str, object]] = [{"type": "text", "text": json.dumps(result.payload, ensure_ascii=False)}]
273
319
  for path in result.images:
274
320
  encoded = _bounded_image(path)
275
321
  if encoded is None:
@@ -345,9 +391,6 @@ def run_stdio(
345
391
  except (UnicodeDecodeError, json.JSONDecodeError):
346
392
  response = server._error(None, -32700, "Parse error")
347
393
  if response is not None:
348
- output_stream.write(
349
- json.dumps(response, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
350
- + b"\n"
351
- )
394
+ output_stream.write(json.dumps(response, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n")
352
395
  output_stream.flush()
353
396
  return 0