@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,110 +1,150 @@
1
1
  """Validated word boundaries from an installed, pinned local model; no estimated words."""
2
+
2
3
  import json
3
4
  import math
4
- from pathlib import Path
5
5
  import unicodedata
6
+ from pathlib import Path
6
7
 
7
8
  from clipen.projects import ProjectError
8
9
 
9
- MODEL = 'mlx-community/Qwen3-ForcedAligner-0.6B-8bit'
10
- REVISION = '0e1a68e91d815300c7c9754b2a7639378b23db15'
11
- FILES = {'chat_template.json':1161, 'config.json':6940, 'generation_config.json':115,
12
- 'merges.txt':1671853, 'model.safetensors':1271924386, 'model.safetensors.index.json':79108,
13
- 'preprocessor_config.json':330, 'tokenizer_config.json':12666, 'vocab.json':2776833}
10
+ MODEL = "mlx-community/Qwen3-ForcedAligner-0.6B-8bit"
11
+ REVISION = "0e1a68e91d815300c7c9754b2a7639378b23db15"
12
+ FILES = {
13
+ "chat_template.json": 1161,
14
+ "config.json": 6940,
15
+ "generation_config.json": 115,
16
+ "merges.txt": 1671853,
17
+ "model.safetensors": 1271924386,
18
+ "model.safetensors.index.json": 79108,
19
+ "preprocessor_config.json": 330,
20
+ "tokenizer_config.json": 12666,
21
+ "vocab.json": 2776833,
22
+ }
14
23
 
15
24
 
16
25
  def significant(text):
17
- return ''.join(c.casefold() for c in unicodedata.normalize('NFKC', text)
18
- if unicodedata.category(c)[0] not in 'PZC')
26
+ return "".join(c.casefold() for c in unicodedata.normalize("NFKC", text) if unicodedata.category(c)[0] not in "PZC")
19
27
 
20
28
 
21
29
  # The pinned aligner reports times on an 80 ms grid. A zero-width token one
22
30
  # step away from its neighbour still marks a boundary the model observed.
23
- FRAME = .1
31
+ FRAME = 0.1
24
32
  # A result where most characters collapse onto instants, or a run of them
25
33
  # share one instant, means the model lost the speech; keep it for repair.
26
- MAX_INSTANT_SHARE = .4
34
+ MAX_INSTANT_SHARE = 0.4
27
35
  MAX_INSTANT_RUN = 4
28
36
 
29
37
 
30
38
  def validate_alignment(words, text, duration):
31
39
  if not isinstance(words, list) or not 1 <= len(words) <= 1000:
32
- raise ProjectError('alignment_invalid', '對齊結果沒有有效字詞。', status_code=422)
40
+ raise ProjectError("alignment_invalid", "對齊結果沒有有效字詞。", status_code=422)
33
41
  # Quantized aligners can emit a zero-width token at, or one grid step from,
34
42
  # an adjacent word boundary. Keep the observed interval as a grouped word;
35
43
  # never assign an invented duration to the individual character or bridge
36
44
  # a gap longer than one grid step. A token away from any neighbour stays an
37
45
  # instant: its observed time, with no duration added.
38
- grouped=[];pending=[]
46
+ grouped = []
47
+ pending = []
39
48
  for raw in words:
40
- word=dict(raw);start,end=word.get('start'),word.get('end')
41
- if not significant(word.get('text','')):continue
42
- finite=all(not isinstance(v,bool) and isinstance(v,(int,float)) and math.isfinite(v) for v in (start,end))
43
- zero=finite and 0<=start==end<=duration
44
- last=grouped[-1] if grouped else None
45
- if (zero and last and not pending and isinstance(last.get('end'),(int,float)) and not isinstance(last.get('end'),bool)
46
- and 0<=start-last['end']<=FRAME and last.get('start',start)<start):
47
- last['text']+=word['text'];last['end']=start
49
+ word = dict(raw)
50
+ start, end = word.get("start"), word.get("end")
51
+ if not significant(word.get("text", "")):
52
+ continue
53
+ finite = all(not isinstance(v, bool) and isinstance(v, (int, float)) and math.isfinite(v) for v in (start, end))
54
+ zero = finite and 0 <= start == end <= duration
55
+ last = grouped[-1] if grouped else None
56
+ if (
57
+ zero
58
+ and last
59
+ and not pending
60
+ and isinstance(last.get("end"), (int, float))
61
+ and not isinstance(last.get("end"), bool)
62
+ and 0 <= start - last["end"] <= FRAME
63
+ and last.get("start", start) < start
64
+ ):
65
+ last["text"] += word["text"]
66
+ last["end"] = start
48
67
  elif zero:
49
68
  pending.append(word)
50
69
  else:
51
- if pending and finite and start<end and all(0<=start-w['end']<=FRAME for w in pending):
52
- word['text']=''.join(w['text'] for w in pending)+word['text']
53
- word['start']=min(start,pending[0]['start'])
70
+ if pending and finite and start < end and all(0 <= start - w["end"] <= FRAME for w in pending):
71
+ word["text"] = "".join(w["text"] for w in pending) + word["text"]
72
+ word["start"] = min(start, pending[0]["start"])
54
73
  else:
55
74
  grouped.extend(pending)
56
- pending=[];grouped.append(word)
57
- words=grouped+pending
75
+ pending = []
76
+ grouped.append(word)
77
+ words = grouped + pending
58
78
  positions = [(index, significant(character)) for index, character in enumerate(text) if significant(character)]
59
- normalized = ''.join(char for _, char in positions)
79
+ normalized = "".join(char for _, char in positions)
60
80
  # Require a stable one-to-one character normalization. Do not silently assign
61
81
  # fractional timing inside a word or fabricate missing/mismatched characters.
62
82
  if any(len(char) != 1 for _, char in positions):
63
- raise ProjectError('alignment_text_unsupported', '這段文字需要額外正規化核對。', status_code=422)
64
- cursor, previous, result = 0, 0., []
83
+ raise ProjectError("alignment_text_unsupported", "這段文字需要額外正規化核對。", status_code=422)
84
+ cursor, previous, result = 0, 0.0, []
65
85
  for word in words:
66
- token = significant(word.get('text', ''))
86
+ token = significant(word.get("text", ""))
67
87
  if not token:
68
88
  continue
69
- start, end = word.get('start'), word.get('end')
70
- if (any(isinstance(v, bool) or not isinstance(v, (int,float)) or not math.isfinite(v) for v in (start,end))
71
- or not 0 <= start <= end <= duration+.05 or start < previous-.02 or end < previous
72
- or normalized[cursor:cursor+len(token)] != token):
73
- raise ProjectError('alignment_invalid', '字詞對齊與文字或音訊範圍不符,已保留待修。', status_code=422)
74
- result.append({'text':word['text'], 'char_start':positions[cursor][0],
75
- 'char_end':positions[cursor+len(token)-1][0]+1, 'start_seconds':max(previous,start),
76
- 'end_seconds':min(duration,end)})
89
+ start, end = word.get("start"), word.get("end")
90
+ if (
91
+ any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) for v in (start, end))
92
+ or not 0 <= start <= end <= duration + 0.05
93
+ or start < previous - 0.02
94
+ or end < previous
95
+ or normalized[cursor : cursor + len(token)] != token
96
+ ):
97
+ raise ProjectError("alignment_invalid", "字詞對齊與文字或音訊範圍不符,已保留待修。", status_code=422)
98
+ result.append(
99
+ {
100
+ "text": word["text"],
101
+ "char_start": positions[cursor][0],
102
+ "char_end": positions[cursor + len(token) - 1][0] + 1,
103
+ "start_seconds": max(previous, start),
104
+ "end_seconds": min(duration, end),
105
+ }
106
+ )
77
107
  cursor += len(token)
78
- previous = min(duration,end)
108
+ previous = min(duration, end)
79
109
  if cursor != len(normalized) or not result:
80
- raise ProjectError('alignment_incomplete', '對齊未涵蓋完整文字。', status_code=422)
81
- instants = [w['start_seconds'] >= w['end_seconds'] for w in result]
110
+ raise ProjectError("alignment_incomplete", "對齊未涵蓋完整文字。", status_code=422)
111
+ instants = [w["start_seconds"] >= w["end_seconds"] for w in result]
82
112
  run = longest = 0
83
113
  for instant in instants:
84
114
  run = run + 1 if instant else 0
85
115
  longest = max(longest, run)
86
- if sum(instants) > len(result) * MAX_INSTANT_SHARE or longest >= MAX_INSTANT_RUN or not any(not i for i in instants):
87
- raise ProjectError('alignment_invalid', '對齊結果多數字詞沒有時間長度,已保留待修。', status_code=422)
116
+ if (
117
+ sum(instants) > len(result) * MAX_INSTANT_SHARE
118
+ or longest >= MAX_INSTANT_RUN
119
+ or not any(not i for i in instants)
120
+ ):
121
+ raise ProjectError("alignment_invalid", "對齊結果多數字詞沒有時間長度,已保留待修。", status_code=422)
88
122
  return result
89
123
 
90
124
 
91
125
  def run_alignment(data_root, audio, text, language, output, cancel):
92
126
  if data_root is None:
93
- raise ProjectError('alignment_unavailable', '本機字詞對齊環境尚未設定。', status_code=409)
127
+ raise ProjectError("alignment_unavailable", "本機字詞對齊環境尚未設定。", status_code=409)
94
128
  from .alignment_setup import root_for, verified_runtime
95
- binding=verified_runtime(root_for(data_root))
129
+
130
+ binding = verified_runtime(root_for(data_root))
96
131
  if binding is None:
97
- raise ProjectError('alignment_unavailable', '缺少固定版本的本機字詞對齊環境。', status_code=409)
98
- python,model=binding
132
+ raise ProjectError("alignment_unavailable", "缺少固定版本的本機字詞對齊環境。", status_code=409)
133
+ python, model = binding
99
134
  from clipen.finishing.audio import run_process
135
+
100
136
  from .production_media import atomic_json
101
- request = output.with_suffix('.request.json')
102
- atomic_json(request, {'model':str(model), 'audio':str(audio), 'text':text,
103
- 'language':language, 'output':str(output)})
137
+
138
+ request = output.with_suffix(".request.json")
139
+ atomic_json(
140
+ request, {"model": str(model), "audio": str(audio), "text": text, "language": language, "output": str(output)}
141
+ )
104
142
  try:
105
- run_process([str(python),str(Path(__file__).with_name('alignment_worker.py')),str(request)],cancel,timeout=180)
106
- if output.is_symlink() or not output.is_file() or output.stat().st_size>1024*1024:
107
- raise ProjectError('alignment_invalid', '無法讀取對齊結果。', status_code=409)
143
+ run_process(
144
+ [str(python), str(Path(__file__).with_name("alignment_worker.py")), str(request)], cancel, timeout=180
145
+ )
146
+ if output.is_symlink() or not output.is_file() or output.stat().st_size > 1024 * 1024:
147
+ raise ProjectError("alignment_invalid", "無法讀取對齊結果。", status_code=409)
108
148
  return json.loads(output.read_text())
109
149
  finally:
110
150
  request.unlink(missing_ok=True)
@@ -1,8 +1,8 @@
1
1
  """Cancellable installation of the fixed local alignment runtime, without source uploads."""
2
+
2
3
  import hashlib
3
4
  import json
4
5
  import os
5
- from pathlib import Path
6
6
  import platform
7
7
  import shutil
8
8
  import sys
@@ -10,99 +10,147 @@ import time
10
10
  import urllib.request
11
11
  import uuid
12
12
  import venv
13
+ from pathlib import Path
13
14
 
14
15
  from clipen.projects import ProjectError
16
+
15
17
  from .alignment import FILES, MODEL, REVISION
16
18
 
17
19
  HASHES = {
18
- 'chat_template.json':'75a8cfca24f00de72d796fbfed6858fc9614ef3dabd8696684cc3bc03a9c58ff',
19
- 'config.json':'8dc126e1a4ac001acb02f3a9ca6277c8a20a25485fde293bc99eeab3aedc604d',
20
- 'generation_config.json':'948d089b23bca1d214e768d59c4438365665f52ec6d33678f4062206b3fbbb8c',
21
- 'merges.txt':'8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5',
22
- 'model.safetensors':'be19ef8ac4326d032e7673342930b14c2df30bd68c1632493b0f563e30829f91',
23
- 'model.safetensors.index.json':'766eb50873855eeb4d95ab92def358cfd173bfc8c7aabd8635ababa1edf6db79',
24
- 'preprocessor_config.json':'45e120a4eda2c20c5d7f2ea9354e63536bf35e27aa573fb7cdf78017b378770d',
25
- 'tokenizer_config.json':'3ab80063f8511deb9566e6ad438d17b7a6277fcffd52d92854112f19d36bd81c',
26
- 'vocab.json':'ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910',
20
+ "chat_template.json": "75a8cfca24f00de72d796fbfed6858fc9614ef3dabd8696684cc3bc03a9c58ff",
21
+ "config.json": "8dc126e1a4ac001acb02f3a9ca6277c8a20a25485fde293bc99eeab3aedc604d",
22
+ "generation_config.json": "948d089b23bca1d214e768d59c4438365665f52ec6d33678f4062206b3fbbb8c",
23
+ "merges.txt": "8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5",
24
+ "model.safetensors": "be19ef8ac4326d032e7673342930b14c2df30bd68c1632493b0f563e30829f91",
25
+ "model.safetensors.index.json": "766eb50873855eeb4d95ab92def358cfd173bfc8c7aabd8635ababa1edf6db79",
26
+ "preprocessor_config.json": "45e120a4eda2c20c5d7f2ea9354e63536bf35e27aa573fb7cdf78017b378770d",
27
+ "tokenizer_config.json": "3ab80063f8511deb9566e6ad438d17b7a6277fcffd52d92854112f19d36bd81c",
28
+ "vocab.json": "ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910",
27
29
  }
28
- RECEIPT = {'model':MODEL,'revision':REVISION,'runtime':'mlx-audio-0.6.0'}
30
+ RECEIPT = {"model": MODEL, "revision": REVISION, "runtime": "mlx-audio-0.6.0"}
29
31
 
30
32
 
31
33
  def root_for(data_root):
32
- return Path(data_root)/'alignment'/'qwen3-0.6b-8bit-v1'
34
+ return Path(data_root) / "alignment" / "qwen3-0.6b-8bit-v1"
33
35
 
34
36
 
35
37
  def verified_runtime(root):
36
- root=Path(root);receipt=root/'ready.json';model=root/'model';python=root/'runtime/bin/python'
37
- if (any(p.is_symlink() for p in (root.parent,root,model,root/'runtime',root/'runtime/bin',receipt))
38
- or not receipt.is_file() or receipt.stat().st_size>4096 or not python.is_file()):
38
+ root = Path(root)
39
+ receipt = root / "ready.json"
40
+ model = root / "model"
41
+ python = root / "runtime/bin/python"
42
+ if (
43
+ any(p.is_symlink() for p in (root.parent, root, model, root / "runtime", root / "runtime/bin", receipt))
44
+ or not receipt.is_file()
45
+ or receipt.stat().st_size > 4096
46
+ or not python.is_file()
47
+ ):
39
48
  return None
40
49
  try:
41
- if json.loads(receipt.read_text())!=RECEIPT:return None
42
- for name,size in FILES.items():
43
- path=model/name
44
- if path.is_symlink() or not path.is_file() or path.stat().st_size!=size:return None
45
- value=hashlib.sha256()
46
- with path.open('rb') as source:
47
- while block:=source.read(1024*1024):value.update(block)
48
- if value.hexdigest()!=HASHES[name]:return None
49
- return python,model
50
- except (OSError,ValueError):return None
50
+ if json.loads(receipt.read_text()) != RECEIPT:
51
+ return None
52
+ for name, size in FILES.items():
53
+ path = model / name
54
+ if path.is_symlink() or not path.is_file() or path.stat().st_size != size:
55
+ return None
56
+ value = hashlib.sha256()
57
+ with path.open("rb") as source:
58
+ while block := source.read(1024 * 1024):
59
+ value.update(block)
60
+ if value.hexdigest() != HASHES[name]:
61
+ return None
62
+ return python, model
63
+ except (OSError, ValueError):
64
+ return None
51
65
 
52
66
 
53
- def install_runtime(data_root, cancel, progress=lambda _:None):
54
- if sys.platform!='darwin' or platform.machine()!='arm64':
55
- raise ProjectError('alignment_platform_unsupported','本機對齊目前支援 Apple Silicon Mac。',status_code=409)
56
- if data_root is None:raise ProjectError('alignment_unavailable','本機對齊目錄尚未設定。',status_code=409)
67
+ def install_runtime(data_root, cancel, progress=lambda _: None):
68
+ if sys.platform != "darwin" or platform.machine() != "arm64":
69
+ raise ProjectError("alignment_platform_unsupported", "本機對齊目前支援 Apple Silicon Mac。", status_code=409)
70
+ if data_root is None:
71
+ raise ProjectError("alignment_unavailable", "本機對齊目錄尚未設定。", status_code=409)
72
+ import fcntl
73
+
57
74
  from clipen.finishing.audio import run_process
75
+
58
76
  from .production_media import atomic_json
59
- import fcntl
60
- root=root_for(data_root)
77
+
78
+ root = root_for(data_root)
61
79
  if root.parent.is_symlink() or root.is_symlink():
62
- raise ProjectError('storage_unsafe','模型安裝路徑不安全。',status_code=409)
63
- root.parent.mkdir(mode=0o700,exist_ok=True,parents=True)
64
- lock_path=root.parent/'setup.lock'
65
- fd=os.open(lock_path,os.O_CREAT|os.O_RDWR|getattr(os,'O_NOFOLLOW',0),0o600)
66
- staging=None
80
+ raise ProjectError("storage_unsafe", "模型安裝路徑不安全。", status_code=409)
81
+ root.parent.mkdir(mode=0o700, exist_ok=True, parents=True)
82
+ lock_path = root.parent / "setup.lock"
83
+ fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
84
+ staging = None
67
85
  try:
68
- deadline=time.monotonic()+1800
86
+ deadline = time.monotonic() + 1800
69
87
  while True:
70
- if cancel.is_set():raise ProjectError('user_cancelled','已取消模型準備。',status_code=409)
71
- if time.monotonic()>deadline:raise ProjectError('alignment_setup_timeout','模型準備逾時。',status_code=409)
72
- try:fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB);break
73
- except BlockingIOError:cancel.wait(.2)
88
+ if cancel.is_set():
89
+ raise ProjectError("user_cancelled", "已取消模型準備。", status_code=409)
90
+ if time.monotonic() > deadline:
91
+ raise ProjectError("alignment_setup_timeout", "模型準備逾時。", status_code=409)
92
+ try:
93
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
94
+ break
95
+ except BlockingIOError:
96
+ cancel.wait(0.2)
74
97
  if verified_runtime(root):
75
- return {'ready':True,'model':MODEL,'revision':REVISION,'reused':True}
98
+ return {"ready": True, "model": MODEL, "revision": REVISION, "reused": True}
76
99
  if root.exists():
77
100
  # An invalid prior environment is preserved for diagnosis. Never
78
101
  # silently delete an existing user installation during a retry.
79
- raise ProjectError('alignment_install_invalid','現有對齊環境未通過驗證,請修復該本機環境。',status_code=409)
80
- if shutil.disk_usage(root.parent).free < sum(FILES.values())+1024**3:
81
- raise ProjectError('alignment_disk_space','準備對齊模型需要額外約 2.3 GB 可用空間。',status_code=409)
82
- staging=root.parent/('.setup-'+uuid.uuid4().hex)
83
- staging.mkdir(mode=0o700);(staging/'model').mkdir(mode=0o700)
84
- progress({'phase':'runtime'})
85
- venv.EnvBuilder(with_pip=True).create(staging/'runtime')
86
- run_process([str(staging/'runtime/bin/python'),'-m','pip','install','--disable-pip-version-check','mlx-audio==0.6.0'],cancel,timeout=900)
87
- total=sum(FILES.values());completed=0
88
- for name,size in FILES.items():
89
- path=staging/'model'/name
90
- request=urllib.request.Request(f'https://huggingface.co/{MODEL}/resolve/{REVISION}/{name}',headers={'User-Agent':'Clipen-local-alignment/1'})
91
- value=hashlib.sha256();count=0
92
- with urllib.request.urlopen(request,timeout=30) as response,path.open('xb') as output:
93
- while block:=response.read(1024*1024):
94
- if cancel.is_set():raise ProjectError('user_cancelled','已取消模型下載。',status_code=409)
95
- if time.monotonic()>deadline:raise ProjectError('alignment_setup_timeout','模型下載逾時。',status_code=409)
96
- count+=len(block)
97
- if count>size:raise ValueError('alignment download exceeds pinned size')
98
- output.write(block);value.update(block)
99
- progress({'phase':'model','completed_bytes':completed+count,'total_bytes':total})
100
- if count!=size or value.hexdigest()!=HASHES[name]:
101
- raise ProjectError('alignment_download_invalid','模型下載未通過固定版本校驗。',status_code=409)
102
- completed+=size
103
- atomic_json(staging/'ready.json',RECEIPT)
104
- os.rename(staging,root);staging=None
105
- return {'ready':True,'model':MODEL,'revision':REVISION,'reused':False}
102
+ raise ProjectError(
103
+ "alignment_install_invalid", "現有對齊環境未通過驗證,請修復該本機環境。", status_code=409
104
+ )
105
+ if shutil.disk_usage(root.parent).free < sum(FILES.values()) + 1024**3:
106
+ raise ProjectError("alignment_disk_space", "準備對齊模型需要額外約 2.3 GB 可用空間。", status_code=409)
107
+ staging = root.parent / (".setup-" + uuid.uuid4().hex)
108
+ staging.mkdir(mode=0o700)
109
+ (staging / "model").mkdir(mode=0o700)
110
+ progress({"phase": "runtime"})
111
+ venv.EnvBuilder(with_pip=True).create(staging / "runtime")
112
+ run_process(
113
+ [
114
+ str(staging / "runtime/bin/python"),
115
+ "-m",
116
+ "pip",
117
+ "install",
118
+ "--disable-pip-version-check",
119
+ "mlx-audio==0.6.0",
120
+ ],
121
+ cancel,
122
+ timeout=900,
123
+ )
124
+ total = sum(FILES.values())
125
+ completed = 0
126
+ for name, size in FILES.items():
127
+ path = staging / "model" / name
128
+ request = urllib.request.Request(
129
+ f"https://huggingface.co/{MODEL}/resolve/{REVISION}/{name}",
130
+ headers={"User-Agent": "Clipen-local-alignment/1"},
131
+ )
132
+ value = hashlib.sha256()
133
+ count = 0
134
+ with urllib.request.urlopen(request, timeout=30) as response, path.open("xb") as output:
135
+ while block := response.read(1024 * 1024):
136
+ if cancel.is_set():
137
+ raise ProjectError("user_cancelled", "已取消模型下載。", status_code=409)
138
+ if time.monotonic() > deadline:
139
+ raise ProjectError("alignment_setup_timeout", "模型下載逾時。", status_code=409)
140
+ count += len(block)
141
+ if count > size:
142
+ raise ValueError("alignment download exceeds pinned size")
143
+ output.write(block)
144
+ value.update(block)
145
+ progress({"phase": "model", "completed_bytes": completed + count, "total_bytes": total})
146
+ if count != size or value.hexdigest() != HASHES[name]:
147
+ raise ProjectError("alignment_download_invalid", "模型下載未通過固定版本校驗。", status_code=409)
148
+ completed += size
149
+ atomic_json(staging / "ready.json", RECEIPT)
150
+ os.rename(staging, root)
151
+ staging = None
152
+ return {"ready": True, "model": MODEL, "revision": REVISION, "reused": False}
106
153
  finally:
107
- if staging is not None:shutil.rmtree(staging,ignore_errors=True)
154
+ if staging is not None:
155
+ shutil.rmtree(staging, ignore_errors=True)
108
156
  os.close(fd)
@@ -1,22 +1,24 @@
1
1
  """Offline subprocess for the separately installed MLX forced-aligner."""
2
+
2
3
  import json
3
4
  import os
4
- from pathlib import Path
5
5
  import sys
6
+ from pathlib import Path
6
7
 
7
- os.environ['HF_HUB_OFFLINE'] = '1'
8
- os.environ['TRANSFORMERS_OFFLINE'] = '1'
8
+ os.environ["HF_HUB_OFFLINE"] = "1"
9
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
9
10
 
10
11
 
11
12
  def main():
12
13
  from mlx_audio.stt import load
14
+
13
15
  request = json.loads(Path(sys.argv[1]).read_text())
14
- model = load(request['model'])
15
- language = {'zh':'Chinese','en':'English','ja':'Japanese'}[request['language']]
16
- result = model.generate(audio=request['audio'], text=request['text'], language=language)
17
- words = [{'text':i.text, 'start':float(i.start_time), 'end':float(i.end_time)} for i in result]
18
- Path(request['output']).write_text(json.dumps(words, ensure_ascii=False))
16
+ model = load(request["model"])
17
+ language = {"zh": "Chinese", "en": "English", "ja": "Japanese"}[request["language"]]
18
+ result = model.generate(audio=request["audio"], text=request["text"], language=language)
19
+ words = [{"text": i.text, "start": float(i.start_time), "end": float(i.end_time)} for i in result]
20
+ Path(request["output"]).write_text(json.dumps(words, ensure_ascii=False))
19
21
 
20
22
 
21
- if __name__ == '__main__':
23
+ if __name__ == "__main__":
22
24
  main()