@clipen/clipen-cli 1.0.7 → 1.0.8

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 (38) hide show
  1. package/README.md +3 -2
  2. package/apps/web/dist/assets/{index-CaxEZKLc.css → index-CJ80KHsQ.css} +1 -1
  3. package/apps/web/dist/assets/index-C_4u_hVf.js +16 -0
  4. package/apps/web/dist/index.html +2 -2
  5. package/bin/clipen.js +231 -61
  6. package/package.json +8 -2
  7. package/pyproject.toml +1 -1
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/qwen_worker.py +13 -4
  10. package/src/clipen/analysis/setup.py +2 -1
  11. package/src/clipen/analysis/setup_cli.py +58 -12
  12. package/src/clipen/bootstrap.py +389 -164
  13. package/src/clipen/cli.py +40 -15
  14. package/src/clipen/controller/app.py +37 -17
  15. package/src/clipen/controller/server.py +65 -27
  16. package/src/clipen/editing/agent_repository.py +8 -0
  17. package/src/clipen/editing/change_report.py +17 -0
  18. package/src/clipen/editing/coordinator.py +6 -0
  19. package/src/clipen/editing/evidence_jobs.py +3 -1
  20. package/src/clipen/editing/history_changes.py +56 -27
  21. package/src/clipen/editing/production_progress.py +46 -3
  22. package/src/clipen/editing/versions.py +53 -10
  23. package/src/clipen/i18n.py +155 -0
  24. package/src/clipen/locale_en.py +528 -0
  25. package/src/clipen/mcp_editing/__main__.py +8 -0
  26. package/src/clipen/projects/models.py +16 -1
  27. package/src/clipen/projects/picker.py +3 -1
  28. package/src/clipen/projects/storage.py +17 -1
  29. package/src/clipen/providers/claude_editing.py +3 -1
  30. package/src/clipen/providers/codex_editing.py +3 -1
  31. package/src/clipen/providers/editing_agent.py +36 -1
  32. package/src/clipen/providers/liveness.py +39 -0
  33. package/src/clipen/skills/builtin/display.en.json +89 -0
  34. package/src/clipen/skills/builtin/references/graphics.md +0 -1
  35. package/src/clipen/skills/catalog.py +22 -0
  36. package/src/clipen/terminal.py +344 -0
  37. package/src/clipen/workspace.py +97 -28
  38. package/apps/web/dist/assets/index-C3Zw0WaM.js +0 -14
@@ -7,8 +7,8 @@
7
7
  <meta name="description" content="Clipen 本機 AI 剪輯工作台" />
8
8
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
9
9
  <title>Clipen · 你的作品</title>
10
- <script type="module" crossorigin src="/assets/index-C3Zw0WaM.js"></script>
11
- <link rel="stylesheet" crossorigin href="/assets/index-CaxEZKLc.css">
10
+ <script type="module" crossorigin src="/assets/index-C_4u_hVf.js"></script>
11
+ <link rel="stylesheet" crossorigin href="/assets/index-CJ80KHsQ.css">
12
12
  </head>
13
13
  <body>
14
14
  <div id="root"></div>
package/bin/clipen.js CHANGED
@@ -6,16 +6,20 @@
6
6
  // its own fixed standalone Python, downloaded and checked into its folder: a Python the person
7
7
  // installed (system, Homebrew, pyenv) is never used, so changing or removing it cannot break Clipen. Fonts are not in the package; they are downloaded from the sources pinned in
8
8
  // fonts/manifest.json and checked against their SHA-256. Then the Python installer takes over.
9
- 'use strict'
10
- const { spawnSync } = require('node:child_process')
11
- const crypto = require('node:crypto')
12
- const fs = require('node:fs')
13
- const os = require('node:os')
14
- const path = require('node:path')
15
- const readline = require('node:readline')
16
-
17
- const PACKAGE = path.resolve(__dirname, '..')
18
- const VERSION = require(path.join(PACKAGE, 'package.json')).version
9
+ import * as p from '@clack/prompts'
10
+ import chalk from 'chalk'
11
+ import { Command, CommanderError } from 'commander'
12
+ import { execFile, spawnSync } from 'node:child_process'
13
+ import crypto from 'node:crypto'
14
+ import { once } from 'node:events'
15
+ import fs from 'node:fs'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+ import { promisify } from 'node:util'
20
+
21
+ const PACKAGE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
22
+ const { version: VERSION, description: DESCRIPTION } = JSON.parse(fs.readFileSync(path.join(PACKAGE, 'package.json'), 'utf8'))
19
23
  const PYTHON = {
20
24
  tag: '3.12.16+20261026',
21
25
  url: 'https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.12.16%2B20261026-aarch64-apple-darwin-install_only_stripped.tar.gz',
@@ -25,37 +29,99 @@ const PYTHON = {
25
29
  // What the program needs at run time; the rest of the package (this launcher) stays in npx's cache.
26
30
  const PROGRAM = ['src', 'apps/web/dist', 'requirements', 'pyproject.toml', 'clipen', 'README.md', 'LICENSE']
27
31
  const FONTS = 'src/clipen/rendering/fonts'
32
+ const COMMANDS = [
33
+ ['install', ['安裝或更新 Clipen(預設)', 'Install or update Clipen (default)']],
34
+ ['codex', ['在目前目錄用 Codex 開啟 Clipen', 'Open Clipen here with Codex']],
35
+ ['claude', ['在目前目錄用 Claude Code 開啟 Clipen', 'Open Clipen here with Claude Code']],
36
+ ['uninstall', ['移除 Clipen 程式與執行環境(作品資料保留)', 'Remove the Clipen program and runtime (projects are kept)']],
37
+ ]
38
+ const brand = chalk.hex('#e9b44c')
39
+ // The same wordmark the Python side draws (src/clipen/terminal.py), gold warming to amber.
40
+ const LOGO = [
41
+ ' ██████╗██╗ ██╗██████╗ ███████╗███╗ ██╗',
42
+ '██╔════╝██║ ██║██╔══██╗██╔════╝████╗ ██║',
43
+ '██║ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║',
44
+ '██║ ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║',
45
+ '╚██████╗███████╗██║██║ ███████╗██║ ╚████║',
46
+ ' ╚═════╝╚══════╝╚═╝╚═╝ ╚══════╝╚═╝ ╚═══╝',
47
+ ]
48
+ const LOGO_COLOURS = [[246, 211, 122], [240, 198, 100], [233, 180, 76], [226, 160, 62], [218, 140, 52], [208, 120, 44]]
49
+ const ENGLISH_DESCRIPTION = 'Let AI edit your videos with Claude Code or Codex, then revise them with review notes on the timeline'
50
+ const megabytes = (bytes) => Math.round(bytes / 1e6)
28
51
 
29
- function dataRoot() {
30
- return path.join(os.homedir(), 'Library', 'Application Support', 'Clipen')
52
+ class SetupError extends Error {}
53
+
54
+ // The language Clipen speaks, chosen as the Python side chooses it (src/clipen/i18n.py): CLIPEN_LANG,
55
+ // then the choice saved with `clipen language`, then the Mac's preferred language, then LANG.
56
+ function normalize(value) {
57
+ const lower = String(value ?? '').trim().toLowerCase().replaceAll('_', '-')
58
+ return lower.startsWith('zh') ? 'zh-TW' : lower.startsWith('en') ? 'en' : null
31
59
  }
60
+ function settingsPath() { return path.join(dataRoot(), 'settings.json') }
61
+ function savedLanguage() {
62
+ try { return normalize(JSON.parse(fs.readFileSync(settingsPath(), 'utf8')).language) } catch { return null }
63
+ }
64
+ function macLanguage() {
65
+ if (process.platform !== 'darwin') return null
66
+ const read = spawnSync('/usr/bin/defaults', ['read', '-g', 'AppleLanguages'], { encoding: 'utf8', timeout: 2000 })
67
+ for (const entry of (read.stdout ?? '').replace(/[()]/g, ' ').split(',')) {
68
+ const found = normalize(entry.trim().replace(/^"|"$/g, ''))
69
+ if (found) return found
70
+ }
71
+ return null
72
+ }
73
+ const LANGUAGE = normalize(process.env.CLIPEN_LANG) ?? savedLanguage() ?? macLanguage()
74
+ ?? normalize(process.env.LC_ALL) ?? normalize(process.env.LC_MESSAGES) ?? normalize(process.env.LANG) ?? 'en'
75
+ const t = (zh, en) => (LANGUAGE === 'en' ? en : zh)
76
+
77
+ // The spinner or progress bar on screen, so a failure can close it before the message is shown.
78
+ let active = null
32
79
 
33
- function fail(message) {
34
- console.error(`Clipen 安裝失敗:${message}`)
35
- process.exit(1)
80
+ function begin(indicator, message) {
81
+ indicator.start(message)
82
+ active = indicator
83
+ return indicator
36
84
  }
37
85
 
38
- function sha256(file) {
39
- return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
86
+ function finish(message) {
87
+ active.stop(message)
88
+ active = null
40
89
  }
41
90
 
42
- async function ask(question) {
43
- if (!process.stdin.isTTY) fail('第一次設定需要在互動式 Terminal 中確認。')
44
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
45
- const answer = await new Promise((resolve) => rl.question(question, resolve))
46
- rl.close()
47
- return ['', 'y', 'yes'].includes(answer.trim().toLowerCase())
91
+ /** The wordmark, where colour and width allow. */
92
+ function logo() {
93
+ if (!chalk.level || (process.stdout.columns ?? 80) < 50) return
94
+ console.log()
95
+ LOGO.forEach((line, index) => console.log(` ${chalk.rgb(...LOGO_COLOURS[index])(line)}`))
96
+ console.log(` ${chalk.dim(`v${VERSION} · ${t('AI 剪輯工作台', 'AI video editing studio')}`)}\n`)
97
+ }
98
+
99
+ function dataRoot() {
100
+ return path.join(os.homedir(), 'Library', 'Application Support', 'Clipen')
48
101
  }
49
102
 
50
103
  /** Download to a file and check it; nothing unchecked is ever kept. */
51
- async function download(url, target, expected) {
104
+ async function download(url, target, expected, onProgress = () => {}) {
52
105
  const response = await fetch(url, { redirect: 'follow' })
53
- if (!response.ok) fail(`無法下載 ${url}(HTTP ${response.status})`)
106
+ if (!response.ok) throw new SetupError(t(`無法下載 ${url}(HTTP ${response.status})`, `Could not download ${url} (HTTP ${response.status})`))
107
+ const total = Number(response.headers.get('content-length')) || 0
54
108
  const partial = `${target}.part`
55
- fs.writeFileSync(partial, Buffer.from(await response.arrayBuffer()))
56
- if (sha256(partial) !== expected) {
109
+ const hash = crypto.createHash('sha256')
110
+ const file = fs.createWriteStream(partial)
111
+ let received = 0
112
+ try {
113
+ for await (const chunk of response.body) {
114
+ hash.update(chunk)
115
+ if (!file.write(chunk)) await once(file, 'drain')
116
+ received += chunk.length
117
+ onProgress(received, total)
118
+ }
119
+ } finally {
120
+ await new Promise((resolve) => file.end(resolve))
121
+ }
122
+ if (hash.digest('hex') !== expected) {
57
123
  fs.rmSync(partial, { force: true })
58
- fail(`${path.basename(target)} 的檢查碼不符,已刪除下載的檔案;請稍後再試或回報問題。`)
124
+ throw new SetupError(t(`${path.basename(target)} 的檢查碼不符,已刪除下載的檔案;請稍後再試或回報問題。`, `${path.basename(target)} failed its checksum and was deleted; try again later or report the problem.`))
59
125
  }
60
126
  fs.renameSync(partial, target)
61
127
  }
@@ -71,16 +137,29 @@ async function standalonePython() {
71
137
  const target = path.join(root, PYTHON.tag)
72
138
  fs.mkdirSync(root, { recursive: true, mode: 0o700 })
73
139
  const archive = path.join(root, `cpython-${PYTHON.tag}.tar.gz`)
74
- console.log(`正在下載 Python ${PYTHON.tag.split('+')[0]}(約 ${Math.round(PYTHON.bytes / 1e6)} MB)…`)
75
- await download(PYTHON.url, archive, PYTHON.sha256)
140
+ const label = t('正在下載 Clipen 安裝程式', 'Downloading the Clipen installer')
141
+ const bar = begin(p.progress({ max: 100, style: 'heavy' }), label)
142
+ let shown = 0
143
+ await download(PYTHON.url, archive, PYTHON.sha256, (received, total) => {
144
+ const percent = Math.floor((received * 100) / (total || PYTHON.bytes))
145
+ if (percent > shown && percent <= 100) {
146
+ bar.advance(percent - shown, `${label} ${chalk.dim(`${megabytes(received)} / ${megabytes(total || PYTHON.bytes)} MB`)}`)
147
+ shown = percent
148
+ }
149
+ })
150
+ bar.message(t('正在解壓縮', 'Unpacking'))
76
151
  const staging = `${target}.staging-${process.pid}`
77
152
  fs.rmSync(staging, { recursive: true, force: true })
78
153
  fs.mkdirSync(staging)
79
- const unpacked = spawnSync('tar', ['-xzf', archive, '-C', staging, '--strip-components', '1'], { stdio: 'inherit' })
80
- fs.rmSync(archive, { force: true })
81
- if (unpacked.status !== 0) fail('Python 解壓縮失敗。')
154
+ try {
155
+ await promisify(execFile)('tar', ['-xzf', archive, '-C', staging, '--strip-components', '1'])
156
+ } catch (error) {
157
+ throw new SetupError(t('Python 解壓縮失敗。', 'Unpacking Python failed.') + (error.stderr ? `\n${error.stderr.trim()}` : ''))
158
+ } finally {
159
+ fs.rmSync(archive, { force: true })
160
+ }
82
161
  fs.renameSync(staging, target)
83
- console.log('✓ Python 準備完成')
162
+ finish(t('安裝程式下載完成', 'Installer downloaded'))
84
163
  return path.join(target, 'bin', 'python3')
85
164
  }
86
165
 
@@ -92,21 +171,22 @@ async function program() {
92
171
  fs.mkdirSync(root, { recursive: true, mode: 0o700 })
93
172
  const staging = `${target}.staging-${process.pid}`
94
173
  fs.rmSync(staging, { recursive: true, force: true })
174
+ const spin = begin(p.spinner(), t(`正在準備 Clipen ${VERSION}`, `Preparing Clipen ${VERSION}`))
95
175
  for (const entry of PROGRAM) {
96
176
  const from = path.join(PACKAGE, entry)
97
- if (!fs.existsSync(from)) fail(`套件缺少 ${entry}。`)
98
- fs.cpSync(from, path.join(staging, entry), { recursive: true, filter: (file) => !file.includes('__pycache__') })
177
+ if (!fs.existsSync(from)) throw new SetupError(t(`套件缺少 ${entry}。`, `The package is missing ${entry}.`))
178
+ await fs.promises.cp(from, path.join(staging, entry), { recursive: true, filter: (file) => !file.includes('__pycache__') })
99
179
  }
100
180
  const fonts = path.join(staging, FONTS)
101
181
  const manifest = JSON.parse(fs.readFileSync(path.join(fonts, 'manifest.json'), 'utf8'))
102
182
  const missing = Object.values(manifest).filter((font) => !fs.existsSync(path.join(fonts, font.file)))
103
- if (missing.length) {
104
- console.log(`正在下載 Clipen 內附字型(${missing.length} 套,開源授權)…`)
105
- for (const font of missing) await download(font.download_url, path.join(fonts, font.file), font.sha256)
106
- console.log('✓ 字型準備完成')
183
+ for (const [index, font] of missing.entries()) {
184
+ spin.message(`${t('正在下載字型', 'Downloading fonts')} ${chalk.dim(`${index + 1} / ${missing.length}`)}`)
185
+ await download(font.download_url, path.join(fonts, font.file), font.sha256)
107
186
  }
108
187
  fs.writeFileSync(path.join(staging, '.clipen-npm'), `${VERSION}\n`)
109
188
  fs.renameSync(staging, target)
189
+ finish(t(`Clipen ${VERSION} 準備完成`, `Clipen ${VERSION} ready`))
110
190
  return target
111
191
  }
112
192
 
@@ -114,33 +194,123 @@ function tools() {
114
194
  const has = (name) => spawnSync('/bin/sh', ['-c', `command -v ${name}`], { env: { ...process.env, PATH: `${process.env.PATH}:/opt/homebrew/bin:/usr/local/bin` } }).status === 0
115
195
  const missing = ['ffmpeg', 'ffprobe'].filter((name) => !has(name))
116
196
  if (!missing.length) return
117
- console.log('\n⚠ 找不到 ffmpeg:Clipen 輸出影片需要它。')
118
- console.log(has('brew') ? ' 安裝方式:brew install ffmpeg' : ' 先安裝 Homebrew(https://brew.sh),再執行:brew install ffmpeg')
119
- console.log(' 安裝好之後再執行 clipen codex 或 clipen claude 即可。\n')
197
+ p.log.warn([
198
+ t('還缺 ffmpeg(輸出影片需要它)', 'ffmpeg is missing (films need it to render)'),
199
+ has('brew') ? `${t('請另外執行:', 'Run: ')}${brand('brew install ffmpeg')}` : `${t('請先安裝 Homebrew(https://brew.sh),再執行:', 'Install Homebrew (https://brew.sh), then run: ')}${brand('brew install ffmpeg')}`,
200
+ ].join('\n'))
120
201
  }
121
202
 
122
- async function main() {
123
- if (process.platform !== 'darwin' || process.arch !== 'arm64') fail('目前只支援 Apple 晶片(M 系列)的 Mac。')
124
- const args = process.argv.slice(2)
125
- const command = args.length ? args : ['install']
203
+ async function launch(command) {
204
+ if (process.platform !== 'darwin' || process.arch !== 'arm64') throw new SetupError(t('目前只支援 Apple 晶片(M 系列)的 Mac。', 'Clipen runs only on Apple silicon (M-series) Macs.'))
126
205
  let python = findPython()
127
- const app = path.join(dataRoot(), 'app', VERSION)
128
- const needs = [
129
- ...(python ? [] : [`Python ${PYTHON.tag.split('+')[0]}(約 ${Math.round(PYTHON.bytes / 1e6)} MB,Clipen 專用,來自 python-build-standalone,下載後核對檢查碼)`]),
130
- ...(fs.existsSync(path.join(app, '.clipen-npm')) ? [] : [`Clipen ${VERSION} 程式(放在 ${app})與內附字型(約 40 MB,開源授權,下載後核對檢查碼)`]),
131
- ]
132
- if (needs.length) {
133
- console.log('Clipen 會先準備:')
134
- for (const item of needs) console.log(` • ${item}`)
135
- console.log('全部放在 Clipen 自己的資料夾;不會使用或修改你電腦上原有的 Python,也不會使用 sudo。')
136
- if (!(await ask('繼續?[Y/n] '))) { console.log('已取消,沒有下載任何東西。'); return }
206
+ const programReady = fs.existsSync(path.join(dataRoot(), 'app', VERSION, '.clipen-npm'))
207
+ const download = (python ? 0 : PYTHON.bytes) + (programReady ? 0 : 40e6)
208
+ // Starting Clipen when everything is in place goes straight to the program, without a frame.
209
+ const framed = command === 'install' || download > 0
210
+ if (framed) {
211
+ logo()
212
+ p.intro(chalk.bgHex('#e9b44c').black(` Clipen ${VERSION} `))
213
+ }
214
+ // Asking to install is already the yes; only a download the person did not ask for is confirmed here.
215
+ if (download && command !== 'install') {
216
+ if (!process.stdin.isTTY) throw new SetupError(t('第一次設定需要在互動式 Terminal 中確認。', 'First-time setup needs confirming in an interactive Terminal.'))
217
+ const proceed = await p.confirm({ message: t(`需要先下載 Clipen 程式(約 ${megabytes(download)} MB),要繼續嗎?`, `Clipen needs to download its program first (about ${megabytes(download)} MB). Continue?`), active: t('是', 'Yes'), inactive: t('否', 'No'), initialValue: true })
218
+ if (p.isCancel(proceed) || !proceed) {
219
+ p.cancel(t('已取消,沒有下載任何東西。', 'Cancelled; nothing was downloaded.'))
220
+ return 0
221
+ }
137
222
  }
138
223
  if (!python) python = await standalonePython()
139
224
  const target = await program()
140
- if (command[0] === 'install') tools()
225
+ if (command === 'install') tools()
226
+ else if (framed) p.outro(chalk.dim(t(`正在開啟 clipen ${command}…`, `Opening clipen ${command}…`)))
227
+ // The installer continues this frame instead of drawing its own logo.
228
+ const env = command === 'install' ? { ...process.env, CLIPEN_FRAME_OPEN: '1' } : process.env
141
229
  // -I: the person's PYTHONPATH, PYTHONHOME and user site never reach Clipen's Python.
142
- const run = spawnSync(python, ['-I', path.join(target, 'clipen'), ...command], { stdio: 'inherit' })
143
- process.exit(run.status ?? 1)
230
+ const run = spawnSync(python, ['-I', path.join(target, 'clipen'), command], { stdio: 'inherit', env })
231
+ return run.status ?? 1
232
+ }
233
+
234
+
235
+ /** `clipen language`: say which language Clipen speaks; with en, zh-TW or auto, change it for every Clipen command. */
236
+ function language(choice) {
237
+ if (choice !== undefined) {
238
+ const chosen = choice.trim().toLowerCase() === 'auto' ? null : normalize(choice)
239
+ if (chosen === null && choice.trim().toLowerCase() !== 'auto') {
240
+ console.error(`${chalk.red('✗')} ${t('請選 en、zh-TW 或 auto', 'Choose en, zh-TW or auto')}`)
241
+ return 2
242
+ }
243
+ let settings = {}
244
+ try { settings = JSON.parse(fs.readFileSync(settingsPath(), 'utf8')) } catch { /* A first setting starts the file. */ }
245
+ if (chosen) settings.language = chosen
246
+ else delete settings.language
247
+ fs.mkdirSync(dataRoot(), { recursive: true, mode: 0o700 })
248
+ fs.writeFileSync(settingsPath(), `${JSON.stringify(settings, null, 2)}\n`)
249
+ }
250
+ const now = normalize(process.env.CLIPEN_LANG) ?? savedLanguage() ?? macLanguage() ?? normalize(process.env.LANG) ?? 'en'
251
+ const speak = (zh, en) => (now === 'en' ? en : zh)
252
+ const name = now === 'en' ? 'English' : '繁體中文'
253
+ console.log(`${chalk.green('◇')} ${speak(`Clipen 使用 ${name}`, `Clipen speaks ${name}`)} ${chalk.dim(savedLanguage() ? speak('(手動設定)', '(set by you)') : speak('(跟著系統)', '(following the system)'))}`)
254
+ return 0
255
+ }
256
+
257
+ function formatHelp(command, helper) {
258
+ const rows = (items, term, describe) => {
259
+ const width = Math.max(...items.map((item) => term(item).length))
260
+ return items.map((item) => ` ${brand(term(item).padEnd(width))} ${describe(item)}`)
261
+ }
262
+ return [
263
+ `${chalk.bold(t('用法:', 'Usage: '))}clipen ${chalk.dim(t('[指令]', '[command]'))}`,
264
+ '',
265
+ command.description(),
266
+ '',
267
+ chalk.bold(t('指令:', 'Commands:')),
268
+ ...rows(helper.visibleCommands(command), (sub) => sub.name(), (sub) => sub.description()),
269
+ '',
270
+ chalk.bold(t('選項:', 'Options:')),
271
+ ...rows(helper.visibleOptions(command), (option) => option.flags, (option) => option.description),
272
+ '',
273
+ chalk.dim(t('第一次使用:npx @clipen/clipen-cli', 'First time: npx @clipen/clipen-cli')),
274
+ '',
275
+ ].join('\n')
144
276
  }
145
277
 
146
- main().catch((error) => fail(error instanceof Error ? error.message : String(error)))
278
+ async function main() {
279
+ let status = 0
280
+ const cli = new Command('clipen')
281
+ .description(t(DESCRIPTION, ENGLISH_DESCRIPTION))
282
+ .version(VERSION, '-v, --version', t('顯示版本', 'Show the version'))
283
+ .helpOption('-h, --help', t('顯示說明', 'Show help'))
284
+ .helpCommand(false)
285
+ .configureHelp({ formatHelp })
286
+ .configureOutput({ outputError: () => {} })
287
+ .exitOverride()
288
+ .action(async () => { status = await launch('install') })
289
+ for (const [name, summary] of COMMANDS) {
290
+ cli.command(name).description(t(...summary)).helpOption(false).action(async () => { status = await launch(name) })
291
+ }
292
+ cli.command('language').argument('[choice]').description(t('顯示或設定介面語言:en、zh-TW 或 auto', 'Show or set the language: en, zh-TW or auto')).helpOption(false)
293
+ .action((choice) => { status = language(choice) })
294
+ try {
295
+ await cli.parseAsync()
296
+ } catch (error) {
297
+ if (!(error instanceof CommanderError)) throw error
298
+ if (error.exitCode === 0) return 0
299
+ const given = process.argv.slice(2)
300
+ // An unknown word reaches the bare `clipen` action as an extra argument, not as an unknown command.
301
+ const reason = error.code === 'commander.unknownOption' ? t('沒有這個選項', 'No such option')
302
+ : COMMANDS.some(([name]) => name === given[0]) ? t('多了不需要的參數', 'Unexpected argument') : t('沒有這個指令', 'No such command')
303
+ console.error(`${chalk.red('✗')} ${reason}${t(':', ': ')}${chalk.bold(given.join(' '))}`)
304
+ console.error(chalk.dim(t('執行 clipen --help 查看可用指令。', 'Run clipen --help to see the commands.')))
305
+ return 1
306
+ }
307
+ return status
308
+ }
309
+
310
+ try {
311
+ process.exitCode = await main()
312
+ } catch (error) {
313
+ active?.error(t('失敗', 'Failed'))
314
+ p.cancel(`${t('Clipen 安裝失敗:', 'Clipen install failed: ')}${error instanceof Error ? error.message : String(error)}`)
315
+ process.exitCode = 1
316
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipen/clipen-cli",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "讓 AI 用 Claude Code 或 Codex 幫你剪影片,再用時間線上的審片注記修改",
5
5
  "keywords": [
6
6
  "video-editing",
@@ -20,6 +20,7 @@
20
20
  "url": "https://github.com/IMGMANISME/clipen/issues"
21
21
  },
22
22
  "license": "MIT",
23
+ "type": "module",
23
24
  "bin": {
24
25
  "clipen": "bin/clipen.js"
25
26
  },
@@ -36,7 +37,7 @@
36
37
  "LICENSE"
37
38
  ],
38
39
  "engines": {
39
- "node": ">=18"
40
+ "node": ">=20.12"
40
41
  },
41
42
  "os": [
42
43
  "darwin"
@@ -51,5 +52,10 @@
51
52
  },
52
53
  "publishConfig": {
53
54
  "access": "public"
55
+ },
56
+ "dependencies": {
57
+ "@clack/prompts": "1.9.0",
58
+ "chalk": "5.6.2",
59
+ "commander": "14.0.3"
54
60
  }
55
61
  }
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "clipen"
7
- version = "1.0.7"
7
+ version = "1.0.8"
8
8
  description = "Let AI cut your video with Claude Code or Codex, and review it with notes on the timeline"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,3 +1,3 @@
1
1
  """Clipen product package."""
2
2
 
3
- __version__ = "1.0.7"
3
+ __version__ = "1.0.8"
@@ -392,7 +392,7 @@ def _transcribe(runtime, audio) -> tuple[str, list[float], bool]:
392
392
 
393
393
  features = runtime.processor.feature_extractor(audio, sample_rate=16_000)
394
394
  audio_length = int(features.audio_lengths.reshape(-1)[0])
395
- prompt = runtime.processor.build_prompt(context="", audio_length=audio_length, language="Chinese")
395
+ prompt = runtime.processor.build_prompt(context="", audio_length=audio_length, language=_SPOKEN[_language])
396
396
  audio_features = runtime.model.get_audio_features(
397
397
  mx.array(features.input_features, dtype=mx.float32),
398
398
  feature_attention_mask=mx.array(features.feature_attention_mask, dtype=mx.int32),
@@ -530,12 +530,17 @@ def _result(runtime, convert, audio: Path) -> dict[str, object]:
530
530
  }
531
531
  )
532
532
  return {
533
- "language": "zh",
533
+ "language": _language,
534
534
  "text": "\n".join(str(segment["text"]) for segment in segments),
535
535
  "segments": segments,
536
536
  }
537
537
 
538
538
 
539
+ # The language each request is recognised in; the worker serves one request at a time.
540
+ _SPOKEN = {"zh": "Chinese", "en": "English"}
541
+ _language = "zh"
542
+
543
+
539
544
  def _load_runtime(model: Path):
540
545
  import mlx_speech
541
546
 
@@ -543,10 +548,12 @@ def _load_runtime(model: Path):
543
548
 
544
549
 
545
550
  def _serve(model: Path) -> int:
551
+ global _language
546
552
  from opencc import OpenCC
547
553
 
548
554
  runtime = _load_runtime(model)
549
- convert = OpenCC("s2twp").convert
555
+ # Chinese is written in Traditional characters; other languages stay as recognised.
556
+ traditional = OpenCC("s2twp").convert
550
557
  _response({"type": "ready", "qwen3_asr_runtime": "mlx-speech-0.5.2"})
551
558
  while line := sys.stdin.buffer.readline(_MAX_REQUEST_BYTES + 1):
552
559
  if len(line) > _MAX_REQUEST_BYTES or not line.endswith(b"\n"):
@@ -560,8 +567,10 @@ def _serve(model: Path) -> int:
560
567
  "output",
561
568
  }:
562
569
  raise ValueError("invalid request")
563
- if request["language"] != "zh" or request["initial_prompt"] is not None:
570
+ if request["language"] not in _SPOKEN or request["initial_prompt"] is not None:
564
571
  raise ValueError("unsupported request")
572
+ _language = request["language"]
573
+ convert = traditional if _language == "zh" else str
565
574
  audio = _regular(request["audio"])
566
575
  output = _regular(request["output"])
567
576
  if output.stat().st_size != 0:
@@ -41,6 +41,7 @@ from clipen.asr_release import (
41
41
  RELEASE_ID,
42
42
  SUPERSEDED_RELEASE_IDS,
43
43
  )
44
+ from clipen.i18n import tr
44
45
 
45
46
  from .transcription import LocalModelSnapshot, Qwen3ASRAdapter
46
47
 
@@ -83,7 +84,7 @@ class ASRSetupStatus:
83
84
  return {
84
85
  "state": self.state.value,
85
86
  "phase": self.phase,
86
- "message": self.message,
87
+ "message": tr(self.message),
87
88
  "error_code": self.error_code,
88
89
  "completed_units": self.completed_units,
89
90
  "total_units": self.total_units,
@@ -8,6 +8,7 @@ import time
8
8
  from pathlib import Path
9
9
 
10
10
  from clipen.asr_release import NOTICE_VERSION, PROGRESS_RECORD_PREFIX
11
+ from clipen.i18n import speaking, system_language, tr
11
12
 
12
13
  from .setup import ASRSetupError, ASRSetupManager, ASRSetupState, ASRSetupStatus
13
14
 
@@ -26,14 +27,23 @@ def _progress_line(status: ASRSetupStatus, elapsed: int) -> str:
26
27
  percent = max(0, min(100, status.progress_percent))
27
28
  width = 24
28
29
  filled = min(width, percent * width // 100)
29
- bar = "█" * filled + "░" * (width - filled)
30
+ bar = "━" * filled + "─" * (width - filled)
30
31
  detail = ""
31
32
  if status.detail_total_bytes > 0:
32
33
  detail = f" · {_format_bytes(status.detail_completed_bytes)} / {_format_bytes(status.detail_total_bytes)}"
33
- return f"[{bar}] {percent:3d}% {status.message}{detail} · {elapsed // 60} 分 {elapsed % 60} 秒"
34
+ return tr(
35
+ f"{bar} {percent:3d}% {status.message}{detail} · {elapsed // 60} 分 {elapsed % 60} 秒",
36
+ f"{bar} {percent:3d}% {tr(status.message)}{detail} · {elapsed // 60}m {elapsed % 60}s",
37
+ )
34
38
 
35
39
 
36
40
  def main(arguments: list[str] | None = None) -> int:
41
+ # The installer runs this in its own process; it speaks the same language.
42
+ with speaking(system_language()):
43
+ return _main(arguments)
44
+
45
+
46
+ def _main(arguments: list[str] | None) -> int:
37
47
  parser = argparse.ArgumentParser(add_help=False)
38
48
  parser.add_argument("--data-root", required=True)
39
49
  parser.add_argument("--requirements", required=True)
@@ -44,21 +54,44 @@ def main(arguments: list[str] | None = None) -> int:
44
54
  Path(options.requirements),
45
55
  )
46
56
  except (OSError, ValueError, ASRSetupError) as error:
47
- print(f"無法準備本機語音辨識:{error}", file=sys.stderr, flush=True)
57
+ print(
58
+ tr(f"無法準備本機語音辨識:{error}", f"Cannot prepare local speech recognition: {error}"),
59
+ file=sys.stderr,
60
+ flush=True,
61
+ )
48
62
  return 1
49
63
 
50
64
  try:
51
65
  state = manager.status().state
52
66
  if state is ASRSetupState.READY:
53
- print("正在確認語音辨識環境使用 Clipen 自己的 Python…", flush=True)
67
+ print(
68
+ tr(
69
+ "正在確認語音辨識環境使用 Clipen 自己的 Python…",
70
+ "Checking speech recognition runs on Clipen's own Python…",
71
+ ),
72
+ flush=True,
73
+ )
54
74
  if manager.reseat_runtime():
55
- print("✓ 已改用 Clipen 自己的 Python 重建語音辨識環境(模型沿用)", flush=True)
56
- print("✓ 本機語音辨識已準備完成", flush=True)
75
+ print(
76
+ tr(
77
+ "✓ 已改用 Clipen 自己的 Python 重建語音辨識環境(模型沿用)",
78
+ "✓ Rebuilt speech recognition on Clipen's own Python (model kept)",
79
+ ),
80
+ flush=True,
81
+ )
82
+ print(tr("✓ 本機語音辨識已準備完成", "✓ Local speech recognition is ready"), flush=True)
57
83
  return 0
58
84
  if state is ASRSetupState.FAILED:
59
85
  removed = manager.remove()
60
86
  if removed.state is not ASRSetupState.SETUP_REQUIRED:
61
- print("無法安全清除不完整的語音辨識安裝", file=sys.stderr, flush=True)
87
+ print(
88
+ tr(
89
+ "無法安全清除不完整的語音辨識安裝",
90
+ "Cannot safely clear the incomplete speech recognition install",
91
+ ),
92
+ file=sys.stderr,
93
+ flush=True,
94
+ )
62
95
  return 1
63
96
  manager.start_install(NOTICE_VERSION)
64
97
  last_phase = None
@@ -81,26 +114,39 @@ def main(arguments: list[str] | None = None) -> int:
81
114
  last_percent = status.progress_percent
82
115
  last_reported_at = now
83
116
  if status.state is ASRSetupState.READY:
84
- print("✓ 本機語音辨識與固定模型安裝完成", flush=True)
117
+ print(
118
+ tr(
119
+ "✓ 本機語音辨識與固定模型安裝完成",
120
+ "✓ Local speech recognition and its pinned model are installed",
121
+ ),
122
+ flush=True,
123
+ )
85
124
  return 0
86
125
  if status.state is not ASRSetupState.INSTALLING:
87
126
  diagnostics = manager.diagnostic_lines()
88
127
  if diagnostics:
89
- print("安裝器最後訊息:", file=sys.stderr, flush=True)
128
+ print(tr("安裝器最後訊息:", "Last installer output:"), file=sys.stderr, flush=True)
90
129
  for line in diagnostics:
91
130
  print(f" {line}", file=sys.stderr, flush=True)
92
131
  print(
93
- f"本機語音辨識設定失敗:{status.error_code or status.phase}",
132
+ tr(
133
+ f"本機語音辨識設定失敗:{status.error_code or status.phase}",
134
+ f"Setting up local speech recognition failed: {status.error_code or status.phase}",
135
+ ),
94
136
  file=sys.stderr,
95
137
  flush=True,
96
138
  )
97
139
  return 1
98
140
  time.sleep(0.1)
99
141
  except KeyboardInterrupt:
100
- print("正在取消本機語音辨識設定…", flush=True)
142
+ print(tr("正在取消本機語音辨識設定…", "Cancelling the speech recognition setup…"), flush=True)
101
143
  return 130
102
144
  except ASRSetupError as error:
103
- print(f"本機語音辨識設定失敗:{error.code}", file=sys.stderr, flush=True)
145
+ print(
146
+ tr(f"本機語音辨識設定失敗:{error.code}", f"Setting up local speech recognition failed: {error.code}"),
147
+ file=sys.stderr,
148
+ flush=True,
149
+ )
104
150
  return 1
105
151
  finally:
106
152
  manager.close(timeout=10)