@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
@@ -4,6 +4,8 @@ Compares stored timeline payloads, so it works for every version ever saved,
4
4
  whoever made the change.
5
5
  """
6
6
 
7
+ from clipen.i18n import tr
8
+
7
9
 
8
10
  def _components(payload):
9
11
  return {
@@ -45,7 +47,10 @@ def _media(payload, kind):
45
47
 
46
48
  def _name(item):
47
49
  first = (item.get("text") or "").split("\n", 1)[0].strip()
48
- return f"「{first[:18]}{'…' if len(first) > 18 else ''}」" if first else "一個元件"
50
+ if not first:
51
+ return tr("一個元件", "a graphic")
52
+ shown = f"{first[:18]}{'…' if len(first) > 18 else ''}"
53
+ return tr(f"「{shown}」", f"“{shown}”")
49
54
 
50
55
 
51
56
  def _clock(frames, payload):
@@ -58,12 +63,16 @@ def _graphic_change(before, after, styles, recut=False):
58
63
  """One sentence for one graphic that is in both versions, or None when it did not change."""
59
64
  if before.get("text") != after.get("text"):
60
65
  old, new = (item.get("text", "").split("\n", 1)[0] for item in (before, after))
61
- return f"把「{old}」改成「{new}」" if old != new else f"改了{_name(after)}的補充文字"
66
+ if old != new:
67
+ return tr(f"把「{old}」改成「{new}」", f"Changed “{old}” to “{new}”")
68
+ return tr(f"改了{_name(after)}的補充文字", f"Changed the supporting text of {_name(after)}")
62
69
  if before.get("style_id") != after.get("style_id"):
63
70
  old, new = styles.get(before.get("style_id"), {}), styles.get(after.get("style_id"), {})
64
71
  old_look, new_look = old.get("look") or {}, new.get("look") or {}
65
72
  if new_look and old_look.get("look_id") != new_look.get("look_id") and old.get("html") == new.get("html"):
66
- return f"把{_name(after)}換成「{new_look['name']}」外觀"
73
+ return tr(
74
+ f"把{_name(after)}換成「{new_look['name']}」外觀", f"Gave {_name(after)} the “{new_look['name']}” look"
75
+ )
67
76
  if new_look and old_look != new_look and old.get("html") == new.get("html"):
68
77
  # Said once per look, not once per graphic that follows it.
69
78
  return (
@@ -73,33 +82,44 @@ def _graphic_change(before, after, styles, recut=False):
73
82
  old_look.get("colors") != new_look.get("colors"),
74
83
  )
75
84
  if old.get("html") != new.get("html") and new.get("html"):
76
- return f"重新設計{_name(after)}"
85
+ return tr(f"重新設計{_name(after)}", f"Redesigned {_name(after)}")
77
86
  if old.get("edits") != new.get("edits") and new.get("html"):
78
87
  before_edits, after_edits = old.get("edits") or {}, new.get("edits") or {}
79
88
  words = (before_edits.get("texts") or {}) != (after_edits.get("texts") or {})
80
89
  colours = (before_edits.get("colors") or {}) != (after_edits.get("colors") or {})
81
- return f"改了{_name(after)}的" + ("文字和顏色" if words and colours else "文字" if words else "顏色")
90
+ what = (
91
+ tr("文字和顏色", "text and colours")
92
+ if words and colours
93
+ else tr("文字", "text")
94
+ if words
95
+ else tr("顏色", "colours")
96
+ )
97
+ return tr(f"改了{_name(after)}的{what}", f"Changed the {what} of {_name(after)}")
82
98
  if (old.get("x"), old.get("y")) != (new.get("x"), new.get("y")) and old and new:
83
- return f"移動{_name(after)}"
99
+ return tr(f"移動{_name(after)}", f"Moved {_name(after)}")
84
100
  if old.get("scale", 1) != new.get("scale", 1):
85
- return f"{'放大' if new.get('scale', 1) > old.get('scale', 1) else '縮小'}{_name(after)}"
101
+ larger = new.get("scale", 1) > old.get("scale", 1)
102
+ return tr(
103
+ f"{'放大' if larger else '縮小'}{_name(after)}",
104
+ f"Made {_name(after)} {'larger' if larger else 'smaller'}",
105
+ )
86
106
  if old.get("colors") != new.get("colors"):
87
- return f"換了{_name(after)}的顏色"
107
+ return tr(f"換了{_name(after)}的顏色", f"Changed the colours of {_name(after)}")
88
108
  if old.get("visual_style_id") != new.get("visual_style_id"):
89
- return f"{_name(after)}換了樣式"
109
+ return tr(f"{_name(after)}換了樣式", f"Changed the style of {_name(after)}")
90
110
  if old.get("font_style_id") != new.get("font_style_id"):
91
- return f"{_name(after)}換了字體"
111
+ return tr(f"{_name(after)}換了字體", f"Changed the fonts of {_name(after)}")
92
112
  if (old.get("start_offset_frames"), old.get("anchor_item_id")) == (
93
113
  new.get("start_offset_frames"),
94
114
  new.get("anchor_item_id"),
95
115
  ) and not recut:
96
- return f"調整{_name(after)}"
116
+ return tr(f"調整{_name(after)}", f"Adjusted {_name(after)}")
97
117
  # After a new cut every graphic shifts with its shot; that is part of the cut, not news of its own.
98
118
  if not recut and (before["start_frame"], before["duration_frames"]) != (
99
119
  after["start_frame"],
100
120
  after["duration_frames"],
101
121
  ):
102
- return f"調整{_name(after)}出現的時間"
122
+ return tr(f"調整{_name(after)}出現的時間", f"Retimed {_name(after)}")
103
123
  return None
104
124
 
105
125
 
@@ -115,15 +135,14 @@ def describe(before, after, styles=None):
115
135
  (i["start_frame"], i["duration_frames"], i.get("source")) for i in new_cut
116
136
  ]:
117
137
  if before["duration_frames"] != after["duration_frames"]:
118
- changes.append(
119
- f"重新剪輯,片長 {_clock(before['duration_frames'], before)} → {_clock(after['duration_frames'], after)}"
120
- )
138
+ lengths = f"{_clock(before['duration_frames'], before)} → {_clock(after['duration_frames'], after)}"
139
+ changes.append(tr(f"重新剪輯,片長 {lengths}", f"Recut, length {lengths}"))
121
140
  else:
122
- changes.append("調整剪輯")
141
+ changes.append(tr("調整剪輯", "Adjusted the cut"))
123
142
  elif [[e for e in i.get("effects", []) if not e.get("effect_id", "").startswith("audio.")] for i in old_cut] != [
124
143
  [e for e in i.get("effects", []) if not e.get("effect_id", "").startswith("audio.")] for i in new_cut
125
144
  ]:
126
- changes.append("調整畫面效果或轉場")
145
+ changes.append(tr("調整畫面效果或轉場", "Adjusted effects or transitions"))
127
146
 
128
147
  def music(cut):
129
148
  return sorted(
@@ -149,18 +168,18 @@ def describe(before, after, styles=None):
149
168
 
150
169
  # A new cut moves the music with it; only a different song, or new levels on the same cut, is news.
151
170
  if music(old_cut) != music(new_cut):
152
- changes.append("換了配樂")
171
+ changes.append(tr("換了配樂", "Changed the music"))
153
172
  elif not changes and (
154
173
  sound(old_cut) != sound(new_cut)
155
174
  or [e for i in old_cut for e in i.get("effects", []) if e.get("effect_id") == "audio.layers"]
156
175
  != [e for i in new_cut for e in i.get("effects", []) if e.get("effect_id") == "audio.layers"]
157
176
  ):
158
- changes.append("調整配樂或聲音")
177
+ changes.append(tr("調整配樂或聲音", "Adjusted the music or sound"))
159
178
  old, new = _components(before), _components(after)
160
179
  for key in new.keys() - old.keys():
161
- changes.append(f"新增{_name(new[key])}")
180
+ changes.append(tr(f"新增{_name(new[key])}", f"Added {_name(new[key])}"))
162
181
  for key in old.keys() - new.keys():
163
- changes.append(f"刪除{_name(old[key])}")
182
+ changes.append(tr(f"刪除{_name(old[key])}", f"Removed {_name(old[key])}"))
164
183
  looks = {}
165
184
  for key in sorted(old.keys() & new.keys(), key=lambda k: new[k]["start_frame"]):
166
185
  sentence = _graphic_change(old[key], new[key], styles, recut)
@@ -168,12 +187,17 @@ def describe(before, after, styles=None):
168
187
  _, name, fonts, colours = sentence
169
188
  if name not in looks:
170
189
  looks[name] = True
171
- changes.append(
172
- f"換了「{name}」外觀的" + ("字型和配色" if fonts and colours else "字型" if fonts else "配色")
190
+ what = (
191
+ tr("字型和配色", "fonts and colours")
192
+ if fonts and colours
193
+ else tr("字型", "fonts")
194
+ if fonts
195
+ else tr("配色", "colours")
173
196
  )
197
+ changes.append(tr(f"換了「{name}」外觀的{what}", f"Changed the {what} of the “{name}” look"))
174
198
  continue
175
199
  if sentence is None and not recut and _lanes(before)[key] != _lanes(after)[key]:
176
- sentence = f"把{_name(new[key])}移到另一軌"
200
+ sentence = tr(f"把{_name(new[key])}移到另一軌", f"Moved {_name(new[key])} to another lane")
177
201
  if sentence:
178
202
  changes.append(sentence)
179
203
  old_subtitles, new_subtitles = _subtitles(before), _subtitles(after)
@@ -181,12 +205,17 @@ def describe(before, after, styles=None):
181
205
  changed = len(old_subtitles.keys() ^ new_subtitles.keys()) + sum(
182
206
  old_subtitles[k] != new_subtitles[k] for k in old_subtitles.keys() & new_subtitles.keys()
183
207
  )
184
- changes.append(f"修改 {changed} 句字幕" if changed else "調整字幕")
208
+ changes.append(
209
+ tr(f"修改 {changed} 句字幕", f"Changed {changed} {'caption' if changed == 1 else 'captions'}")
210
+ if changed
211
+ else tr("調整字幕", "Adjusted the captions")
212
+ )
185
213
  return changes
186
214
 
187
215
 
188
216
  def summary(changes, limit=2):
189
217
  if not changes:
190
218
  return None
191
- shown = "、".join(changes[:limit])
192
- return shown + (f",還有 {len(changes) - limit} 處" if len(changes) > limit else "")
219
+ shown = tr("、", ", ").join(changes[:limit])
220
+ more = len(changes) - limit
221
+ return shown + (tr(f",還有 {more} 處", f", and {more} more") if more > 0 else "")
@@ -6,6 +6,8 @@ work: an agent revisits steps and has no fixed number of them.
6
6
 
7
7
  import json
8
8
 
9
+ from clipen.i18n import english, tr
10
+
9
11
  _TOOL_GROUPS = (
10
12
  (
11
13
  "理解製作需求與影片風格",
@@ -111,6 +113,37 @@ _FAILURE_LABELS = {
111
113
  "provider_usage_limit": "AI 額度不足,暫停製作",
112
114
  "provider_timed_out": "超過製作時間上限,暫停製作",
113
115
  }
116
+ # What each label says in English; the Chinese label stays the key that stages are read from.
117
+ _ENGLISH = {
118
+ "理解製作需求與影片風格": "Reading the brief and the style",
119
+ "尋找與檢視來源素材": "Finding and viewing footage",
120
+ "準備本機語音模型": "Preparing the local speech model",
121
+ "辨識與對齊來源口語": "Recognising and aligning speech",
122
+ "安排故事與剪輯": "Shaping the story and the cut",
123
+ "製作字幕與畫面設計": "Making captions and graphics",
124
+ "尋找與安排配樂、音效": "Finding and placing music and effects",
125
+ "輸出樣片預覽": "Rendering a preview",
126
+ "檢查畫面、字幕與聲音": "Checking picture, captions and sound",
127
+ "等待或處理本機工作結果": "Waiting on local work",
128
+ "整理交付檔案": "Preparing the delivery",
129
+ "AI 正在操作剪輯工具": "The AI is using the editing tools",
130
+ "製作工作已建立": "Production created",
131
+ "AI 已開始製作": "The AI started",
132
+ "收到你的修改要求": "Got your change request",
133
+ "接續上次的草稿": "Continuing the last draft",
134
+ "換另一個 AI 接手": "Another AI took over",
135
+ "草稿已儲存": "Draft saved",
136
+ "已提交預覽合成": "Preview render submitted",
137
+ "樣片製作已完成,等待你觀看": "The film is ready for you to watch",
138
+ "AI 這次沒有完成製作": "The AI did not finish this time",
139
+ "製作已停止": "Production stopped",
140
+ "製作已中斷": "Production interrupted",
141
+ "本次工作已達操作上限": "This job reached its operation limit",
142
+ "AI 做完草稿,但還有項目沒通過檢查": "The AI made a draft, but some checks have not passed",
143
+ "AI 先停下來了,請看 AI 的說明": "The AI stopped early; read what it says",
144
+ "AI 額度不足,暫停製作": "Out of AI usage; paused",
145
+ "超過製作時間上限,暫停製作": "Past the time limit; paused",
146
+ }
114
147
  # The furthest stage reached moves only forward. Checking the cut before any
115
148
  # preview is part of editing; reviewing only counts once a film was rendered.
116
149
  STAGES = ("understand", "sources", "edit", "graphics", "music", "render", "review")
@@ -152,7 +185,9 @@ _SHOWN = 10
152
185
 
153
186
  def _duration(seconds):
154
187
  minutes = max(1, round(seconds / 60))
155
- return f"{minutes} 分鐘" if minutes < 60 else f"{minutes // 60} 小時 {minutes % 60} 分鐘"
188
+ if minutes < 60:
189
+ return tr(f"{minutes} 分鐘", f"{minutes} min")
190
+ return tr(f"{minutes // 60} 小時 {minutes % 60} 分鐘", f"{minutes // 60} h {minutes % 60} min")
156
191
 
157
192
 
158
193
  def _provider_name(provider_id):
@@ -202,9 +237,15 @@ def production_activity(database, run_id):
202
237
  elif kind == "machine_slept":
203
238
  if row["sequence"] >= boundary:
204
239
  slept += payload.get("seconds", 0)
205
- label = f"Mac 睡眠約 {_duration(payload.get('seconds', 0))},製作暫停"
240
+ label = tr(
241
+ f"Mac 睡眠約 {_duration(payload.get('seconds', 0))},製作暫停",
242
+ f"The Mac slept for about {_duration(payload.get('seconds', 0))}; paused",
243
+ )
206
244
  elif kind == "provider_switched":
207
- label = f"改由 {_provider_name(payload.get('to'))} 接手修改"
245
+ label = tr(
246
+ f"改由 {_provider_name(payload.get('to'))} 接手修改",
247
+ f"{_provider_name(payload.get('to'))} took over the revision",
248
+ )
208
249
  else:
209
250
  label = _EVENT_LABELS[kind]
210
251
  labels.append(label)
@@ -225,6 +266,8 @@ def production_activity(database, run_id):
225
266
  }
226
267
  )
227
268
  activity = activity[-_SHOWN:]
269
+ if english():
270
+ activity = [{**entry, "label": _ENGLISH.get(entry["label"], entry["label"])} for entry in activity]
228
271
  return {
229
272
  "activity": activity,
230
273
  "updated_at": activity[-1]["created_at"] if activity else None,
@@ -9,6 +9,7 @@ Projects from before review notes may also hold manual edits, still labelled bel
9
9
  import json
10
10
  import sqlite3
11
11
 
12
+ from clipen.i18n import english, tr
12
13
  from clipen.provider_registry import get_provider
13
14
 
14
15
  _STOPS = {"provider_failed", "run_cancelled", "run_interrupted", "budget_exhausted"}
@@ -20,6 +21,14 @@ _STOP_REASONS = {
20
21
  "delivery_blocked": "交付檢查未通過",
21
22
  "provider_network_error": "連線中斷時停下",
22
23
  }
24
+ _STOP_REASONS_EN = {
25
+ "provider_usage_limit": "stopped at a usage limit",
26
+ "provider_timed_out": "stopped at the time limit",
27
+ "provider_authentication_required": "stopped when the sign-in expired",
28
+ "provider_stopped_early": "the AI stopped early",
29
+ "delivery_blocked": "delivery checks not passed",
30
+ "provider_network_error": "stopped when the connection dropped",
31
+ }
23
32
  # Labels for manual edits: rewording a graphic now, and the edits earlier Clipen versions allowed.
24
33
  _MANUAL = {
25
34
  "edit_text": "文字與時間",
@@ -46,6 +55,31 @@ _MANUAL = {
46
55
  "edit_component_look": "元件外觀",
47
56
  }
48
57
 
58
+ _MANUAL_EN = {
59
+ "edit_text": "text and timing",
60
+ "configure_text_style": "text look",
61
+ "remove_item": "removed an element",
62
+ "trim_clip": "trimmed a clip",
63
+ "reorder_clips": "reordered clips",
64
+ "split_clip": "split a clip",
65
+ "replace_clip_source": "replaced a source",
66
+ "insert_clip": "inserted a clip",
67
+ "set_source_audio": "original sound",
68
+ "set_color_grade": "colour",
69
+ "set_mosaic": "mosaic",
70
+ "set_transition": "transition",
71
+ "set_fade": "fade",
72
+ "remove_clip_effect": "removed an effect",
73
+ "place_audio": "music and effects",
74
+ "remove_audio": "removed sound",
75
+ "remove_program_component": "removed a graphic",
76
+ "add_custom_component": "added a custom graphic",
77
+ "update_custom_component": "changed a custom graphic",
78
+ "set_component_text": "graphic text",
79
+ "edit_component": "edited a graphic",
80
+ "edit_component_look": "graphic look",
81
+ }
82
+
49
83
 
50
84
  def _name(provider_id):
51
85
  try:
@@ -113,7 +147,10 @@ def versions(database, run_id, provider, styles=None, current=None):
113
147
  elif kind == "provider_switched":
114
148
  current_ai = payload.get("to", current_ai)
115
149
  elif kind == "run_finished":
116
- label = f"{_name(current_ai)} {'打磨' if request else '製作'}完成"
150
+ label = tr(
151
+ f"{_name(current_ai)} {'打磨' if request else '製作'}完成",
152
+ f"{_name(current_ai)} {'revision' if request else 'first cut'} finished",
153
+ )
117
154
  add("ai_complete", label, row["created_at"], request)
118
155
  if result and result[-1]["revision_id"] == latest:
119
156
  # A stopped request that was continued and then finished without further changes ends
@@ -125,14 +162,22 @@ def versions(database, run_id, provider, styles=None, current=None):
125
162
  elif kind in _STOPS:
126
163
  # A stop that changed nothing is not a version.
127
164
  if latest != start:
128
- reason = _STOP_REASONS.get(payload.get("error_code"), "製作中斷")
129
- add("ai_partial", f"{_name(current_ai)} 未完成({reason})", row["created_at"], request)
165
+ reasons = _STOP_REASONS_EN if english() else _STOP_REASONS
166
+ reason = reasons.get(payload.get("error_code"), tr("製作中斷", "interrupted"))
167
+ add(
168
+ "ai_partial",
169
+ tr(f"{_name(current_ai)} 未完成({reason})", f"{_name(current_ai)} unfinished ({reason})"),
170
+ row["created_at"],
171
+ request,
172
+ )
130
173
  start = latest
131
174
  elif kind == "tool_completed" and payload.get("authority") == "user":
132
175
  tool = payload.get("tool")
133
176
  add(
134
177
  "restore" if tool == "restore_revision" else "manual",
135
- "還原版本" if tool == "restore_revision" else f"手動修改:{_MANUAL.get(tool, '編輯')}",
178
+ tr("還原版本", "Restored a version")
179
+ if tool == "restore_revision"
180
+ else tr(f"手動修改:{_MANUAL.get(tool, '編輯')}", f"Your edit: {_MANUAL_EN.get(tool, 'edit')}"),
136
181
  row["created_at"],
137
182
  )
138
183
  start = latest
@@ -148,29 +193,27 @@ def versions(database, run_id, provider, styles=None, current=None):
148
193
 
149
194
  def _report(payload, sent):
150
195
  """What the AI said it changed, with each answer placed next to the note it answers."""
151
- from .change_report import OUTCOMES
196
+ from .change_report import outcome_label, reason_label
152
197
 
153
198
  report = payload.get("report") or {}
154
199
  notes = [
155
200
  {
156
201
  **note,
157
- "outcome_label": OUTCOMES.get(note.get("outcome"), ""),
202
+ "outcome_label": outcome_label(note.get("outcome")),
158
203
  "kind": (sent.get(note.get("reference_id")) or {}).get("kind"),
159
204
  "note": (sent.get(note.get("reference_id")) or {}).get("note", ""),
160
205
  }
161
206
  for note in report.get("notes", [])
162
207
  ]
163
- from .change_report import REASONS
164
-
165
208
  # Reports written before reasons were required hold plain lines.
166
209
  left = [
167
210
  {"what": item, "reason": None, "reason_label": "", "detail": ""}
168
211
  if isinstance(item, str)
169
- else {**item, "reason_label": REASONS.get(item.get("reason"), "")}
212
+ else {**item, "reason_label": reason_label(item.get("reason"))}
170
213
  for item in report.get("not_done", [])
171
214
  ]
172
215
  for note in notes:
173
- note["reason_label"] = REASONS.get(note.get("reason"), "")
216
+ note["reason_label"] = reason_label(note.get("reason"))
174
217
  return {
175
218
  "summary": payload.get("summary") or "",
176
219
  "changes": report.get("changes", []),
@@ -0,0 +1,155 @@
1
+ """The language Clipen speaks: Traditional Chinese (``zh-TW``) or English (``en``).
2
+
3
+ Chinese is the source text everywhere. A string shown to people is written ``tr("中文", "English")``
4
+ where it is used; error messages keep their Chinese text and find their English in
5
+ :mod:`clipen.locale_en`, keyed by that text, so a raise site needs no change.
6
+
7
+ Each command line entry point speaks the system language for its run: ``CLIPEN_LANG``, then the
8
+ choice saved with ``clipen language``, then the Mac's preferred language, then ``LANG``. Each
9
+ browser request names its own language (``X-Clipen-Locale``), so the page and the terminal may
10
+ differ. The AI's attempt inherits the language of the request that started it through
11
+ ``CLIPEN_LANG``.
12
+
13
+ Standard library only: the installer reads it before any dependency exists.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import sys
22
+ from contextlib import contextmanager
23
+ from contextvars import ContextVar
24
+ from pathlib import Path
25
+ from typing import Iterator
26
+
27
+ LOCALES = ("zh-TW", "en")
28
+ ENVIRONMENT = "CLIPEN_LANG"
29
+ _SETTINGS = "settings.json"
30
+
31
+
32
+ def normalize(value: object) -> str | None:
33
+ """``zh``, ``zh_TW.UTF-8``, ``zh-Hant-TW`` and the like read as zh-TW; ``en…`` as en."""
34
+ if not isinstance(value, str):
35
+ return None
36
+ lower = value.strip().lower().replace("_", "-")
37
+ if lower.startswith("zh"):
38
+ return "zh-TW"
39
+ if lower.startswith("en"):
40
+ return "en"
41
+ return None
42
+
43
+
44
+ def data_root() -> Path:
45
+ if sys.platform == "darwin":
46
+ return Path.home() / "Library" / "Application Support" / "Clipen"
47
+ xdg_data = os.environ.get("XDG_DATA_HOME")
48
+ return Path(xdg_data) / "clipen" if xdg_data else Path.home() / ".local" / "share" / "clipen"
49
+
50
+
51
+ def saved_language(root: Path | None = None) -> str | None:
52
+ """The language saved with ``clipen language``; None means follow the system."""
53
+ try:
54
+ value = json.loads((root or data_root()).joinpath(_SETTINGS).read_text(encoding="utf-8"))
55
+ except (OSError, ValueError):
56
+ return None
57
+ return normalize(value.get("language")) if isinstance(value, dict) else None
58
+
59
+
60
+ def save_language(language: str | None, root: Path | None = None) -> None:
61
+ """Save a language, or None to follow the system again."""
62
+ folder = root or data_root()
63
+ path = folder / _SETTINGS
64
+ try:
65
+ settings = json.loads(path.read_text(encoding="utf-8"))
66
+ except (OSError, ValueError):
67
+ settings = {}
68
+ if not isinstance(settings, dict):
69
+ settings = {}
70
+ if language is None:
71
+ settings.pop("language", None)
72
+ else:
73
+ settings["language"] = language
74
+ folder.mkdir(mode=0o700, parents=True, exist_ok=True)
75
+ staging = path.with_name(path.name + ".tmp")
76
+ staging.write_text(json.dumps(settings, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
77
+ os.replace(staging, path)
78
+
79
+
80
+ def _mac_language() -> str | None:
81
+ if sys.platform != "darwin":
82
+ return None
83
+ try:
84
+ result = subprocess.run(
85
+ ["/usr/bin/defaults", "read", "-g", "AppleLanguages"],
86
+ capture_output=True,
87
+ text=True,
88
+ timeout=2,
89
+ check=False,
90
+ )
91
+ except (OSError, subprocess.SubprocessError):
92
+ return None
93
+ # The list prints as ( "en-TW", "zh-Hant-TW" ); the first one Clipen speaks wins.
94
+ for entry in result.stdout.replace("(", " ").replace(")", " ").split(","):
95
+ found = normalize(entry.strip().strip('"'))
96
+ if found:
97
+ return found
98
+ return None
99
+
100
+
101
+ def system_language() -> str:
102
+ """The language this process speaks when nothing more specific asks for one."""
103
+ for value in (os.environ.get(ENVIRONMENT), saved_language()):
104
+ found = normalize(value)
105
+ if found:
106
+ return found
107
+ # A Terminal often says en_US.UTF-8 whatever the person reads, so the Mac's own setting comes first.
108
+ found = _mac_language()
109
+ if found:
110
+ return found
111
+ for name in ("LC_ALL", "LC_MESSAGES", "LANG"):
112
+ found = normalize(os.environ.get(name))
113
+ if found:
114
+ return found
115
+ return "en"
116
+
117
+
118
+ # Chinese unless something asks otherwise: an entry point speaking the system language for its
119
+ # run, or a request naming its own. Library code never guesses, so tests read the same anywhere.
120
+ _current: ContextVar[str] = ContextVar("clipen_locale", default="zh-TW")
121
+
122
+
123
+ def current() -> str:
124
+ return _current.get()
125
+
126
+
127
+ def english() -> bool:
128
+ return current() == "en"
129
+
130
+
131
+ @contextmanager
132
+ def speaking(language: str | None) -> Iterator[None]:
133
+ """Speak this language inside the block (for one request, say); None keeps the current one."""
134
+ token = _current.set(normalize(language) or current())
135
+ try:
136
+ yield
137
+ finally:
138
+ _current.reset(token)
139
+
140
+
141
+ def tr(zh: str, en: str | None = None) -> str:
142
+ """The text in the current language. Without English given, the catalog is asked."""
143
+ if current() != "en":
144
+ return zh
145
+ if en is not None:
146
+ return en
147
+ from clipen.locale_en import MESSAGES, PATTERNS
148
+
149
+ if zh in MESSAGES:
150
+ return MESSAGES[zh]
151
+ for pattern, english_text in PATTERNS:
152
+ found = pattern.fullmatch(zh)
153
+ if found:
154
+ return english_text.format(*found.groups())
155
+ return zh