@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
@@ -1,74 +1,136 @@
1
1
  """The review workbench: read the current film, restore a version, reword graphics, render and export it."""
2
- import threading
2
+
3
3
  import json
4
- from clipen.projects import ProjectError, DirectoryReference, DirectoryRole
4
+ import threading
5
+
6
+ from clipen.projects import DirectoryReference, DirectoryRole, ProjectError
5
7
  from clipen.projects.storage import utc_now
8
+
6
9
  from .agent_tools import EditAgentTools
7
10
  from .production_media import AgentAudioStore
8
11
  from .refinement_references import public_state, sent
9
12
 
10
13
  # Changes go through review notes to the AI; the user picks which version is current and edits graphics directly.
11
- USER_TOOLS = frozenset({'restore_revision','set_component_text','edit_component','edit_component_look','remove_program_component'})
14
+ USER_TOOLS = frozenset(
15
+ {"restore_revision", "set_component_text", "edit_component", "edit_component_look", "remove_program_component"}
16
+ )
17
+
12
18
 
13
19
  def idle(repository, project_id, run_id):
14
- run=repository.get(project_id,run_id)
15
- latest=repository.latest(project_id)
16
- if latest is None or latest.run_id!=run_id or run.state in {'queued','running'}:
17
- raise ProjectError('edit_agent_busy','請先停止 AI 製作,再還原或輸出目前版本。',status_code=409)
18
- if repository.production_session(project_id,run_id) is None:
19
- raise ProjectError('production_required','這個版本不是可編輯的影片製作。',status_code=409)
20
+ run = repository.get(project_id, run_id)
21
+ latest = repository.latest(project_id)
22
+ if latest is None or latest.run_id != run_id or run.state in {"queued", "running"}:
23
+ raise ProjectError("edit_agent_busy", "請先停止 AI 製作,再還原或輸出目前版本。", status_code=409)
24
+ if repository.production_session(project_id, run_id) is None:
25
+ raise ProjectError("production_required", "這個版本不是可編輯的影片製作。", status_code=409)
20
26
  return run
21
27
 
28
+
22
29
  def tools_for(repository, project_id, run_id):
23
- tools=EditAgentTools(repository,project_id,run_id)
24
- tools._user_edit=True
30
+ tools = EditAgentTools(repository, project_id, run_id)
31
+ tools._user_edit = True
25
32
  return tools
26
33
 
34
+
27
35
  def state(repository, project_id, run_id):
28
- revision=repository.current_revision(project_id,run_id)
36
+ revision = repository.current_revision(project_id, run_id)
29
37
  from .versions import film_usage, versions
38
+
30
39
  with repository.projects.connect(project_id) as db:
31
40
  # One entry per complete edit; the AI's per-step revisions stay internal.
32
41
  from .production_media import load_text_styles
33
- history=versions(db,run_id,repository.get(project_id,run_id).provider,load_text_styles(repository.projects,project_id),revision.revision_id)
34
- usage=film_usage(db,run_id)
42
+
43
+ history = versions(
44
+ db,
45
+ run_id,
46
+ repository.get(project_id, run_id).provider,
47
+ load_text_styles(repository.projects, project_id),
48
+ revision.revision_id,
49
+ )
50
+ usage = film_usage(db, run_id)
35
51
  for version in history:
36
- row=db.execute('SELECT payload_json FROM edit_agent_revisions WHERE revision_id=? AND run_id=?',(version['revision_id'],run_id)).fetchone()
52
+ row = db.execute(
53
+ "SELECT payload_json FROM edit_agent_revisions WHERE revision_id=? AND run_id=?",
54
+ (version["revision_id"], run_id),
55
+ ).fetchone()
37
56
  if row:
38
- value=json.loads(row['payload_json']);rate=value['frame_rate']
39
- version['duration_seconds']=value['duration_frames']*rate['den']/rate['num']
40
- preview=db.execute("SELECT render_id FROM preview_renders WHERE timeline_id=? AND state='succeeded' ORDER BY created_at DESC LIMIT 1",(version['revision_id'],)).fetchone()
41
- version['preview_url']=f"/api/projects/{project_id}/preview/{preview['render_id']}/media" if preview else None
42
- intent=(repository.production_session(project_id,run_id) or {}).get('intent',{})
43
- try:editing=tools_for(repository,project_id,run_id)._component_editing()
44
- except (ProjectError,KeyError,StopIteration):editing={'components':{},'visual_styles':[],'font_styles':[]}
45
- return {'revision':revision.to_public(include_timeline=True),'component_editing':editing,'history':history,'ai_usage':usage,'references':public_state(intent,revision.timeline),'sent_notes':sent(intent),'audio_assets':AgentAudioStore(repository.projects,project_id).public_assets()}
57
+ value = json.loads(row["payload_json"])
58
+ rate = value["frame_rate"]
59
+ version["duration_seconds"] = value["duration_frames"] * rate["den"] / rate["num"]
60
+ preview = db.execute(
61
+ "SELECT render_id FROM preview_renders WHERE timeline_id=? AND state='succeeded' ORDER BY created_at DESC LIMIT 1",
62
+ (version["revision_id"],),
63
+ ).fetchone()
64
+ version["preview_url"] = (
65
+ f"/api/projects/{project_id}/preview/{preview['render_id']}/media" if preview else None
66
+ )
67
+ intent = (repository.production_session(project_id, run_id) or {}).get("intent", {})
68
+ try:
69
+ editing = tools_for(repository, project_id, run_id)._component_editing()
70
+ except (ProjectError, KeyError, StopIteration):
71
+ editing = {"components": {}, "visual_styles": [], "font_styles": []}
72
+ return {
73
+ "revision": revision.to_public(include_timeline=True),
74
+ "component_editing": editing,
75
+ "history": history,
76
+ "ai_usage": usage,
77
+ "references": public_state(intent, revision.timeline),
78
+ "sent_notes": sent(intent),
79
+ "audio_assets": AgentAudioStore(repository.projects, project_id).public_assets(),
80
+ }
81
+
46
82
 
47
83
  def edit(repository, project_id, run_id, name, arguments, expected, mutation_id):
48
- idle(repository,project_id,run_id)
84
+ idle(repository, project_id, run_id)
49
85
  if name not in USER_TOOLS:
50
- raise ProjectError('tool_not_allowed','請用審片注記交給 AI 修改;這裡只能還原版本或編輯元件。',status_code=422)
51
- tools=tools_for(repository,project_id,run_id)
86
+ raise ProjectError(
87
+ "tool_not_allowed", "請用審片注記交給 AI 修改;這裡只能還原版本或編輯元件。", status_code=422
88
+ )
89
+ tools = tools_for(repository, project_id, run_id)
52
90
  try:
53
- result=tools.call(name,{**arguments,'expected_revision_id':expected,'mutation_id':mutation_id})
91
+ result = tools.call(name, {**arguments, "expected_revision_id": expected, "mutation_id": mutation_id})
54
92
  return result.payload
55
- finally:tools.close_production()
93
+ finally:
94
+ tools.close_production()
95
+
56
96
 
57
97
  def import_music(repository, project_id, path, display_name):
58
98
  from clipen.finishing.audio import inspect_library
59
- store=AgentAudioStore(repository.projects,project_id)
60
- directory=path.parent;info=directory.stat()
61
- reference=DirectoryReference(DirectoryRole.SOURCE,str(directory),directory.name,'使用者指定配樂',info.st_dev,info.st_ino,utc_now()).to_storage()
62
- assets,issues=inspect_library('music',reference,threading.Event(),lambda _:None)
63
- if len(assets)!=1:
64
- raise ProjectError('music_invalid','音樂檔無法解碼或沒有可用聲音。',status_code=422)
65
- asset=assets[0];asset['name']=display_name
66
- asset['provenance']={'source':'user_upload','title':display_name,'license':'user_supplied','rights_verified':False,'attribution':'使用者提供;系統未驗證授權。','changes':'將依剪輯需要截取、調整音量及淡入淡出。'}
67
- store.add(assets,reference)
68
- return next(a for a in store.public_assets() if a['asset_id']==asset['asset_id'])
99
+
100
+ store = AgentAudioStore(repository.projects, project_id)
101
+ directory = path.parent
102
+ info = directory.stat()
103
+ reference = DirectoryReference(
104
+ DirectoryRole.SOURCE, str(directory), directory.name, "使用者指定配樂", info.st_dev, info.st_ino, utc_now()
105
+ ).to_storage()
106
+ assets, issues = inspect_library("music", reference, threading.Event(), lambda _: None)
107
+ if len(assets) != 1:
108
+ raise ProjectError("music_invalid", "音樂檔無法解碼或沒有可用聲音。", status_code=422)
109
+ asset = assets[0]
110
+ asset["name"] = display_name
111
+ asset["provenance"] = {
112
+ "source": "user_upload",
113
+ "title": display_name,
114
+ "license": "user_supplied",
115
+ "rights_verified": False,
116
+ "attribution": "使用者提供;系統未驗證授權。",
117
+ "changes": "將依剪輯需要截取、調整音量及淡入淡出。",
118
+ }
119
+ store.add(assets, reference)
120
+ return next(a for a in store.public_assets() if a["asset_id"] == asset["asset_id"])
121
+
69
122
 
70
123
  def music_choice(repository, project_id, asset_id):
71
- if asset_id is None:return None
72
- asset=next((a for a in AgentAudioStore(repository.projects,project_id).public_assets() if a['asset_id']==asset_id and a['role']=='music'),None)
73
- if asset is None:raise ProjectError('music_missing','指定的配樂不在本作品,請重新選擇。',status_code=422)
74
- return {'mode':'user','asset_id':asset_id,'name':asset['name']}
124
+ if asset_id is None:
125
+ return None
126
+ asset = next(
127
+ (
128
+ a
129
+ for a in AgentAudioStore(repository.projects, project_id).public_assets()
130
+ if a["asset_id"] == asset_id and a["role"] == "music"
131
+ ),
132
+ None,
133
+ )
134
+ if asset is None:
135
+ raise ProjectError("music_missing", "指定的配樂不在本作品,請重新選擇。", status_code=422)
136
+ return {"mode": "user", "asset_id": asset_id, "name": asset["name"]}
@@ -2,14 +2,14 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from array import array
6
5
  import math
7
6
  import os
8
- from pathlib import Path
9
7
  import subprocess
10
8
  import sys
11
9
  import tempfile
12
10
  import time
11
+ from array import array
12
+ from pathlib import Path
13
13
 
14
14
  from clipen.media.discovery import MediaDiscovery, open_file_beneath
15
15
  from clipen.media.models import AssetKind, InventoryRoot
@@ -20,13 +20,15 @@ from clipen.projects.picker import refresh_availability
20
20
  from .models import digest
21
21
 
22
22
 
23
- def run_process(command, cancel, *, pass_fds=(), timeout=300, max_bytes=8*1024*1024):
23
+ def run_process(command, cancel, *, pass_fds=(), timeout=300, max_bytes=8 * 1024 * 1024):
24
24
  """Drain through bounded files, poll cancellation even if FFmpeg is silent."""
25
25
  with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as errors:
26
26
  try:
27
27
  process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=errors, pass_fds=pass_fds)
28
28
  except OSError as error:
29
- raise ProjectError("finishing_runtime_missing", "找不到可用的 FFmpeg/ffprobe。", status_code=409) from error
29
+ raise ProjectError(
30
+ "finishing_runtime_missing", "找不到可用的 FFmpeg/ffprobe。", status_code=409
31
+ ) from error
30
32
  deadline = time.monotonic() + timeout
31
33
  try:
32
34
  while process.poll() is None:
@@ -82,32 +84,63 @@ def inspect_library(role, reference, cancel, progress):
82
84
  fd = open_file_beneath(root, entry.relative_path)
83
85
  try:
84
86
  # 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)
87
+ pcm = run_process(
88
+ [
89
+ "ffmpeg",
90
+ "-v",
91
+ "error",
92
+ "-nostdin",
93
+ "-i",
94
+ f"/dev/fd/{fd}",
95
+ "-map",
96
+ f"0:{stream.stream_index}",
97
+ "-t",
98
+ "90",
99
+ "-vn",
100
+ "-ac",
101
+ "1",
102
+ "-ar",
103
+ "8000",
104
+ "-f",
105
+ "s16le",
106
+ "pipe:1",
107
+ ],
108
+ cancel,
109
+ pass_fds=(fd,),
110
+ timeout=45,
111
+ max_bytes=2 * 1024 * 1024,
112
+ )
89
113
  finally:
90
114
  os.close(fd)
91
- samples = array('h')
115
+ samples = array("h")
92
116
  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
117
+ if sys.byteorder != "little":
118
+ samples.byteswap()
119
+ rms = math.sqrt(sum(v * v for v in samples) / max(1, len(samples))) / 32768
95
120
  if rms < 0.0001:
96
121
  raise ValueError("silent audio")
97
122
  beats, bpm = detect_beats(samples)
98
123
  asset = {
99
124
  "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,
125
+ "role": role,
126
+ "name": Path(entry.relative_path).name,
127
+ "relative_path": entry.relative_path,
128
+ "size_bytes": result.size_bytes,
129
+ "mtime_ns": result.mtime_ns,
130
+ "fingerprint": result.fingerprint,
131
+ "stream_index": stream.stream_index,
132
+ "duration_seconds": duration,
133
+ "rms_db": round(20 * math.log10(rms), 2),
134
+ "peak_db": round(20 * math.log10(max(abs(v) for v in samples) / 32768), 2),
135
+ "beats_seconds": beats,
136
+ "bpm": bpm,
137
+ "analyzed_seconds": len(samples) / 8000,
106
138
  }
107
139
  assets.append(asset)
108
- progress(min(0.95, len(assets)/24))
140
+ progress(min(0.95, len(assets) / 24))
109
141
  except Exception as error:
110
- if cancel.is_set(): raise
142
+ if cancel.is_set():
143
+ raise
111
144
  issues.append({"name": Path(entry.relative_path).name, "code": getattr(error, "code", "audio_unusable")})
112
145
  return assets, issues
113
146
 
@@ -115,23 +148,25 @@ def inspect_library(role, reference, cancel, progress):
115
148
  def detect_beats(samples):
116
149
  """Energy-onset autocorrelation, with no fabricated beats for flat audio."""
117
150
  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))]
151
+ energy = [math.sqrt(sum(v * v for v in samples[i : i + hop]) / hop) for i in range(0, len(samples) - hop, hop)]
152
+ onsets = [max(0.0, energy[i] - energy[i - 1]) for i in range(1, len(energy))]
120
153
  if not onsets or max(onsets) < 30:
121
154
  return [], None
122
- scores = [(sum(onsets[i]*onsets[i-lag] for i in range(lag, len(onsets))), lag) for lag in range(17, 51)]
155
+ scores = [(sum(onsets[i] * onsets[i - lag] for i in range(lag, len(onsets))), lag) for lag in range(17, 51)]
123
156
  score, lag = max(scores)
124
- if score <= 0: return [], None
157
+ if score <= 0:
158
+ return [], None
125
159
  # Return observed onset peaks near the periodic pulse; do not invent timestamps.
126
160
  phase = max(range(lag), key=lambda p: sum(onsets[p::lag]))
127
161
  beats = []
128
162
  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)
163
+ low, high = max(0, index - 3), min(len(onsets), index + 4)
164
+ peak = max(range(low, high), key=lambda i: onsets[i])
165
+ if onsets[peak] > max(onsets) * 0.08:
166
+ value = round((peak + 1) * hop / 8000, 3)
167
+ if not beats or value - beats[-1] > 0.20:
168
+ beats.append(value)
169
+ return beats[:300], round(3000 / lag, 1)
135
170
 
136
171
 
137
172
  def open_asset(context, asset_id):
@@ -141,7 +176,11 @@ def open_asset(context, asset_id):
141
176
  fd = open_file_beneath(inventory_root(context["directories"][asset["role"]]), asset["relative_path"])
142
177
  try:
143
178
  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"]:
179
+ if (
180
+ info.st_size != asset["size_bytes"]
181
+ or info.st_mtime_ns != asset["mtime_ns"]
182
+ or bounded_file_fingerprint(fd, info.st_size) != asset["fingerprint"]
183
+ ):
145
184
  raise ProjectError("media_changed", "音樂或音效已變更,請重新檢查。", status_code=409)
146
185
  return fd, asset
147
186
  except Exception: