@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.
- package/README.md +3 -2
- package/apps/web/dist/assets/{index-CaxEZKLc.css → index-CJ80KHsQ.css} +1 -1
- package/apps/web/dist/assets/index-C_4u_hVf.js +16 -0
- package/apps/web/dist/index.html +2 -2
- package/bin/clipen.js +231 -61
- package/package.json +8 -2
- package/pyproject.toml +1 -1
- package/src/clipen/__init__.py +1 -1
- package/src/clipen/analysis/qwen_worker.py +13 -4
- package/src/clipen/analysis/setup.py +2 -1
- package/src/clipen/analysis/setup_cli.py +58 -12
- package/src/clipen/bootstrap.py +389 -164
- package/src/clipen/cli.py +40 -15
- package/src/clipen/controller/app.py +37 -17
- package/src/clipen/controller/server.py +65 -27
- package/src/clipen/editing/agent_repository.py +8 -0
- package/src/clipen/editing/change_report.py +17 -0
- package/src/clipen/editing/coordinator.py +6 -0
- package/src/clipen/editing/evidence_jobs.py +3 -1
- package/src/clipen/editing/history_changes.py +56 -27
- package/src/clipen/editing/production_progress.py +46 -3
- package/src/clipen/editing/versions.py +53 -10
- package/src/clipen/i18n.py +155 -0
- package/src/clipen/locale_en.py +528 -0
- package/src/clipen/mcp_editing/__main__.py +8 -0
- package/src/clipen/projects/models.py +16 -1
- package/src/clipen/projects/picker.py +3 -1
- package/src/clipen/projects/storage.py +17 -1
- package/src/clipen/providers/claude_editing.py +3 -1
- package/src/clipen/providers/codex_editing.py +3 -1
- package/src/clipen/providers/editing_agent.py +36 -1
- package/src/clipen/providers/liveness.py +39 -0
- package/src/clipen/skills/builtin/display.en.json +89 -0
- package/src/clipen/skills/builtin/references/graphics.md +0 -1
- package/src/clipen/skills/catalog.py +22 -0
- package/src/clipen/terminal.py +344 -0
- package/src/clipen/workspace.py +97 -28
- package/apps/web/dist/assets/index-C3Zw0WaM.js +0 -14
|
@@ -365,7 +365,23 @@ class ProjectRepository:
|
|
|
365
365
|
UNION ALL SELECT MAX(created_at) FROM inventory_runs
|
|
366
366
|
UNION ALL SELECT MAX(completed_at) FROM preview_renders
|
|
367
367
|
)""").fetchone()[0]
|
|
368
|
-
|
|
368
|
+
checked = (
|
|
369
|
+
db.execute("SELECT 1 FROM inventory_runs WHERE state='succeeded' LIMIT 1").fetchone() is not None
|
|
370
|
+
)
|
|
371
|
+
run = db.execute(
|
|
372
|
+
"SELECT state,error_code FROM edit_agent_runs ORDER BY created_at DESC,rowid DESC LIMIT 1"
|
|
373
|
+
).fetchone()
|
|
374
|
+
standing = {
|
|
375
|
+
"footage_checked": checked,
|
|
376
|
+
"production": None if run is None else {"state": run["state"], "error_code": run["error_code"]},
|
|
377
|
+
}
|
|
378
|
+
projects.append(
|
|
379
|
+
replace(
|
|
380
|
+
project,
|
|
381
|
+
last_activity_at=max(project.updated_at, activity or project.updated_at),
|
|
382
|
+
standing=standing,
|
|
383
|
+
)
|
|
384
|
+
)
|
|
369
385
|
projects.sort(key=lambda project: project.last_activity_at or project.updated_at, reverse=True)
|
|
370
386
|
return tuple(projects)
|
|
371
387
|
|
|
@@ -48,7 +48,9 @@ class ClaudeEditingAgent(BoundedEditingAgent):
|
|
|
48
48
|
server = {
|
|
49
49
|
"type": "stdio",
|
|
50
50
|
"command": str(self.python),
|
|
51
|
-
"args": mcp_server_arguments(
|
|
51
|
+
"args": mcp_server_arguments(
|
|
52
|
+
self.projects_root, project_id, run_id, self.local_runtime, getattr(self, "_language", "zh-TW")
|
|
53
|
+
),
|
|
52
54
|
}
|
|
53
55
|
return (
|
|
54
56
|
str(self.binary),
|
|
@@ -47,7 +47,9 @@ class CodexEditingAgent(BoundedEditingAgent):
|
|
|
47
47
|
workspace: Path,
|
|
48
48
|
output_path: Path,
|
|
49
49
|
) -> tuple[str, ...]:
|
|
50
|
-
args = mcp_server_arguments(
|
|
50
|
+
args = mcp_server_arguments(
|
|
51
|
+
self.projects_root, project_id, run_id, self.local_runtime, getattr(self, "_language", "zh-TW")
|
|
52
|
+
)
|
|
51
53
|
return (
|
|
52
54
|
str(self.binary),
|
|
53
55
|
"--ask-for-approval",
|
|
@@ -22,6 +22,7 @@ from typing import Mapping
|
|
|
22
22
|
|
|
23
23
|
from clipen.editing.agent import AgentRun, EditAgentRepository
|
|
24
24
|
from clipen.editing.production_catalog import AGENT_NAMES
|
|
25
|
+
from clipen.providers import liveness
|
|
25
26
|
from clipen.providers.recovery import ProviderUsage
|
|
26
27
|
|
|
27
28
|
from .errors import (
|
|
@@ -140,6 +141,32 @@ for rendering, inspection and finish_edit; report concrete incomplete work if bl
|
|
|
140
141
|
The person reads Traditional Chinese: write the change report and your closing message
|
|
141
142
|
in Traditional Chinese, whatever language these instructions use.
|
|
142
143
|
"""
|
|
144
|
+
_ENGLISH = (
|
|
145
|
+
(
|
|
146
|
+
"The person reads Traditional Chinese: write the change report and your closing message\n"
|
|
147
|
+
"in Traditional Chinese, whatever language these instructions use.",
|
|
148
|
+
"The person reads English: write the change report and your closing message in English.\n"
|
|
149
|
+
"Write titles, chapter cards, labels and other on-screen text in English too, whatever\n"
|
|
150
|
+
"language the skill's defaults or examples use; captions keep the language that was spoken.",
|
|
151
|
+
),
|
|
152
|
+
(
|
|
153
|
+
"The person reads Traditional Chinese: write the change report, every reply to a note and\n"
|
|
154
|
+
"your closing message in Traditional Chinese, whatever language these instructions use.",
|
|
155
|
+
"The person reads English: write the change report, every reply to a note and your\n"
|
|
156
|
+
"closing message in English. Write new on-screen text in English, whatever language the\n"
|
|
157
|
+
"skill's defaults or examples use; captions keep the language that was spoken.",
|
|
158
|
+
),
|
|
159
|
+
("Correct subtitles faithfully in Traditional Chinese.", "Correct subtitles faithfully in the language spoken."),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _in_english(prompt):
|
|
164
|
+
"""The prompt for a person who reads English: only the lines about language change."""
|
|
165
|
+
for chinese, english in _ENGLISH:
|
|
166
|
+
prompt = prompt.replace(chinese, english)
|
|
167
|
+
return prompt
|
|
168
|
+
|
|
169
|
+
|
|
143
170
|
_MCP_TOOLS = (
|
|
144
171
|
"get_edit_status",
|
|
145
172
|
"search_media",
|
|
@@ -282,8 +309,9 @@ def mcp_server_arguments(
|
|
|
282
309
|
project_id: str,
|
|
283
310
|
run_id: str,
|
|
284
311
|
local_runtime: tuple[Path, Path] | None,
|
|
312
|
+
language: str = "zh-TW",
|
|
285
313
|
) -> list[str]:
|
|
286
|
-
"""Arguments that start the Clipen MCP server bound to one edit run."""
|
|
314
|
+
"""Arguments that start the Clipen MCP server bound to one edit run, speaking the run's language."""
|
|
287
315
|
args = [
|
|
288
316
|
"-m",
|
|
289
317
|
"clipen.mcp_editing",
|
|
@@ -296,6 +324,8 @@ def mcp_server_arguments(
|
|
|
296
324
|
]
|
|
297
325
|
if local_runtime:
|
|
298
326
|
args += ["--data-root", str(local_runtime[0]), "--asr-requirements", str(local_runtime[1])]
|
|
327
|
+
if language != "zh-TW":
|
|
328
|
+
args += ["--language", language]
|
|
299
329
|
return args
|
|
300
330
|
|
|
301
331
|
|
|
@@ -398,6 +428,9 @@ class BoundedEditingAgent:
|
|
|
398
428
|
raise ValueError("editing timeout must be between 30 and 14400 seconds")
|
|
399
429
|
run = self.repository.get(project_id, run_id)
|
|
400
430
|
self._prompt = _PRODUCTION_PROMPT if session else _PROMPT
|
|
431
|
+
self._language = (session or {}).get("intent", {}).get("language", "zh-TW")
|
|
432
|
+
if self._language == "en":
|
|
433
|
+
self._prompt = _in_english(self._prompt)
|
|
401
434
|
if run.provider != self.provider_id:
|
|
402
435
|
raise ValueError("editing run belongs to another provider")
|
|
403
436
|
attempt_id = "agent-" + uuid.uuid4().hex
|
|
@@ -412,8 +445,10 @@ class BoundedEditingAgent:
|
|
|
412
445
|
self._slept = []
|
|
413
446
|
try:
|
|
414
447
|
try:
|
|
448
|
+
liveness.watch(run_id, events)
|
|
415
449
|
returncode = self._run(command, workspace, events, diagnostics, timeout_seconds, cancel)
|
|
416
450
|
finally:
|
|
451
|
+
liveness.forget(run_id, events)
|
|
417
452
|
record = getattr(self.repository, "record_machine_sleep", None)
|
|
418
453
|
if self._slept and record is not None:
|
|
419
454
|
record(project_id, run_id, self._slept)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""When each running AI attempt last wrote output, so the UI can tell working from stuck.
|
|
2
|
+
|
|
3
|
+
The provider streams its events into a file while it works; that file's modification time is
|
|
4
|
+
the last moment the AI process said anything, including the long thinking between tool calls
|
|
5
|
+
that leaves no tool activity behind. Kept in memory: it only means something while Clipen runs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
_lock = threading.Lock()
|
|
15
|
+
_attempts: dict[str, Path] = {}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def watch(run_id: str, events: Path) -> None:
|
|
19
|
+
with _lock:
|
|
20
|
+
_attempts[run_id] = events
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def forget(run_id: str, events: Path) -> None:
|
|
24
|
+
with _lock:
|
|
25
|
+
if _attempts.get(run_id) == events:
|
|
26
|
+
del _attempts[run_id]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def last_output(run_id: str) -> str | None:
|
|
30
|
+
"""The ISO time the run's AI process last wrote output, or None when no process runs for it."""
|
|
31
|
+
with _lock:
|
|
32
|
+
events = _attempts.get(run_id)
|
|
33
|
+
if events is None:
|
|
34
|
+
return None
|
|
35
|
+
try:
|
|
36
|
+
written = events.stat().st_mtime
|
|
37
|
+
except OSError:
|
|
38
|
+
return None
|
|
39
|
+
return datetime.fromtimestamp(written, timezone.utc).isoformat(timespec="microseconds")
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_about": "English names and descriptions for the built-in skill and templates, shown when the interface reads English. Display only: not part of the frozen skill content.",
|
|
3
|
+
"skills": {
|
|
4
|
+
"travel-program": {
|
|
5
|
+
"name": "People-and-experience travel show",
|
|
6
|
+
"description": "A travel show made from real people, conversation and experience, with consistent captions, info labels, motion and sound."
|
|
7
|
+
}
|
|
8
|
+
},
|
|
9
|
+
"references": {
|
|
10
|
+
"旅遊行程的地名標示、激動句子放大、資訊寫進字幕;轉成 Clipen 原創版面。": "Place names along the route, excited lines made big, facts written into captions; turned into Clipen's own layouts.",
|
|
11
|
+
"左上角地點小標、店名與評價的小字標示、收斂的畫面質感;轉成 Clipen 原創版面。": "A small place label top left, small shop-name and rating tags, a restrained look; turned into Clipen's own layouts.",
|
|
12
|
+
"描邊字幕與黃色重點、貼在人物旁的反應字;轉成 Clipen 原創版面。": "Outlined captions with yellow highlights and reaction words beside people; turned into Clipen's own layouts.",
|
|
13
|
+
"YouTube 頻道": "YouTube channel"
|
|
14
|
+
},
|
|
15
|
+
"templates": {
|
|
16
|
+
"travel-vlog": {
|
|
17
|
+
"name": "Travel vlog", "category": "Travel",
|
|
18
|
+
"description": "Take viewers along in first person: setting off, on the way, arriving, and how it felt.",
|
|
19
|
+
"editorial_direction": "Follow your itinerary and keep the real conversations and reactions on the way; label places, transport and costs only when they help.",
|
|
20
|
+
"design_direction": "Outlined handwritten titles, tape-style “place | English” labels, yellow sticker words only for funny or surprising moments.",
|
|
21
|
+
"music_direction": "Light acoustic guitar or lo-fi beats that step back when people talk.",
|
|
22
|
+
"tags": ["First person", "Itinerary order", "Place labels"]
|
|
23
|
+
},
|
|
24
|
+
"product-unboxing": {
|
|
25
|
+
"name": "Unboxing", "category": "Products",
|
|
26
|
+
"description": "From the box and what is inside to first impressions, so viewers know what they would get.",
|
|
27
|
+
"editorial_direction": "In unboxing order: box, accessories, the product, first use. Specs and prices only from the footage or from you.",
|
|
28
|
+
"design_direction": "A slanted colour-block title to open, specs as black tags beside the product, a starburst reaction only for real surprise.",
|
|
29
|
+
"music_direction": "Clean electronic beats, turned down while unboxing and explaining.",
|
|
30
|
+
"tags": ["Unboxing order", "Spec labels", "First impressions"]
|
|
31
|
+
},
|
|
32
|
+
"travel-highlight": {
|
|
33
|
+
"name": "Travel highlights", "category": "Travel",
|
|
34
|
+
"description": "The whole trip in under three minutes, carried by picture and music.",
|
|
35
|
+
"editorial_direction": "Pick the trip's best and most telling moments and cut to the music; keep only the one or two lines that land.",
|
|
36
|
+
"design_direction": "A widely spaced serif title and thin-line place labels, no stickers, everything fading in slowly so the scenery has the frame.",
|
|
37
|
+
"music_direction": "Music with rises and falls sets the pace; cuts fall on the beat.",
|
|
38
|
+
"tags": ["Music first", "Best shots", "Restrained titles"]
|
|
39
|
+
},
|
|
40
|
+
"food-review": {
|
|
41
|
+
"name": "Food spot", "category": "Travel",
|
|
42
|
+
"description": "Take viewers to one place to eat: why you came, what you ordered, the first bite.",
|
|
43
|
+
"editorial_direction": "Say why you came and what you ordered; keep the first bite and the real reaction whole. Prices and names need a source.",
|
|
44
|
+
"design_direction": "A rounded capsule shop name, price tags beside the food, speech bubbles only when it is really good or surprising.",
|
|
45
|
+
"music_direction": "Light beats, lower while eating and talking.",
|
|
46
|
+
"tags": ["First bite", "Shop and price", "Real reactions"]
|
|
47
|
+
},
|
|
48
|
+
"daily-vlog": {
|
|
49
|
+
"name": "Daily vlog", "category": "Life",
|
|
50
|
+
"description": "The little things in a day, like chatting with a friend.",
|
|
51
|
+
"editorial_direction": "In the order of the day, keep the fun conversations and small moments; pass quickly over empty shots and travel.",
|
|
52
|
+
"design_direction": "A handwritten title with a wavy underline that appears as if written; cute reaction words, but not too many.",
|
|
53
|
+
"music_direction": "Warm lo-fi or acoustic guitar that steps back when people talk.",
|
|
54
|
+
"tags": ["Everyday feel", "Time order", "Easy conversation"]
|
|
55
|
+
},
|
|
56
|
+
"product-demo": {
|
|
57
|
+
"name": "Product demo", "category": "Products",
|
|
58
|
+
"description": "Show step by step how to use a product so viewers can follow and learn.",
|
|
59
|
+
"editorial_direction": "One step at a time in the order you use it; each step says what to do, then shows a clear close-up.",
|
|
60
|
+
"design_direction": "Dark interface-panel titles, keycap “STEP” labels, straight arrows pointing at buttons and screens.",
|
|
61
|
+
"music_direction": "Quiet electronic beats, clearly lower while explaining.",
|
|
62
|
+
"tags": ["Step by step", "Close-ups", "Order of use"]
|
|
63
|
+
},
|
|
64
|
+
"product-review": {
|
|
65
|
+
"name": "Product review", "category": "Products",
|
|
66
|
+
"description": "What it is like after real use: pros, cons, and who it suits.",
|
|
67
|
+
"editorial_direction": "Say what was tested and how, then the pros and the cons, then who it suits. Judgements come only from what the speaker actually experienced in the footage.",
|
|
68
|
+
"design_direction": "Highlighter titles, a tick for each pro and a cross for each con, the verdict as a stamp.",
|
|
69
|
+
"music_direction": "Steady beats, lower while explaining and comparing.",
|
|
70
|
+
"tags": ["Pros and cons", "Real testing", "Verdict"]
|
|
71
|
+
},
|
|
72
|
+
"event-recap": {
|
|
73
|
+
"name": "Event recap", "category": "Events",
|
|
74
|
+
"description": "The highlights of a wedding, party or exhibition, keeping the feel of being there.",
|
|
75
|
+
"editorial_direction": "Follow the event: the opening, the main moments, people's reactions and the close. Keep the key lines of speeches or vows whole.",
|
|
76
|
+
"design_direction": "A gold calligraphic title with fine lines, small time and place labels, names with a thin underline, all fading in elegantly.",
|
|
77
|
+
"music_direction": "Warm piano or strings that stop or drop well down during speeches.",
|
|
78
|
+
"tags": ["Event order", "Key moments", "Atmosphere"]
|
|
79
|
+
},
|
|
80
|
+
"shorts-highlight": {
|
|
81
|
+
"name": "Shorts highlight", "category": "Shorts",
|
|
82
|
+
"description": "A vertical 30–60 second highlight that grabs attention in the first second.",
|
|
83
|
+
"editorial_direction": "Open on the funniest or most striking moment, then quickly give the context; something new every two or three seconds.",
|
|
84
|
+
"design_direction": "Big vertical text with a red and black double outline, neon block labels, key words popping with the lines, large captions.",
|
|
85
|
+
"music_direction": "Brisk music; cuts fall on the beat.",
|
|
86
|
+
"tags": ["Vertical 9:16", "Hook in 1 second", "Fast pace"]
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -304,9 +304,31 @@ def _public(skill):
|
|
|
304
304
|
}
|
|
305
305
|
|
|
306
306
|
|
|
307
|
+
def _english(skill):
|
|
308
|
+
"""The built-in skill and templates as an English reader sees them; their frozen content is unchanged."""
|
|
309
|
+
display = json.loads(_root().joinpath("display.en.json").read_text(encoding="utf-8"))
|
|
310
|
+
# A template's own skill is named after its template.
|
|
311
|
+
template = display["templates"].get(skill["skill_id"].removeprefix("clipen-"), {})
|
|
312
|
+
names = display["skills"].get(skill["skill_id"]) or {
|
|
313
|
+
k: template[k] for k in ("name", "description") if k in template
|
|
314
|
+
}
|
|
315
|
+
if names:
|
|
316
|
+
skill.update(names)
|
|
317
|
+
for template in skill["templates"]:
|
|
318
|
+
template.update(display["templates"].get(template["template_id"], {}))
|
|
319
|
+
for reference in template.get("references", []):
|
|
320
|
+
for key in ("title", "takeaway"):
|
|
321
|
+
reference[key] = display["references"].get(reference.get(key), reference.get(key))
|
|
322
|
+
return skill
|
|
323
|
+
|
|
324
|
+
|
|
307
325
|
def list_skills():
|
|
326
|
+
from clipen.i18n import english
|
|
327
|
+
|
|
308
328
|
core, skills = builtin_skills()
|
|
309
329
|
listed = [_public(compose([entry], core=core)) for entry in skills.values()]
|
|
330
|
+
if english():
|
|
331
|
+
listed = [_english(skill) if skill["source"] == "builtin" else skill for skill in listed]
|
|
310
332
|
library = skill_library()
|
|
311
333
|
for item in library.list():
|
|
312
334
|
if item["state"] == "ready":
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Clipen's terminal look, shared by the installer and the running app.
|
|
2
|
+
|
|
3
|
+
Standard library only: the installer draws with it before any dependency exists. It uses the same
|
|
4
|
+
frame, symbols and colours as the npx launcher (@clack/prompts), so setup and launch read as one
|
|
5
|
+
product. Output that is not a terminal (a log, a pipe, a test) gets the same frame without colour or
|
|
6
|
+
animation.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
import unicodedata
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from typing import Iterator, Sequence, TextIO
|
|
20
|
+
|
|
21
|
+
from clipen.i18n import tr
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
import termios
|
|
25
|
+
import tty
|
|
26
|
+
except ImportError: # Windows has no POSIX terminal control; prompts fall back to a typed answer.
|
|
27
|
+
termios = tty = None
|
|
28
|
+
|
|
29
|
+
_ANSI = re.compile(r"\033\[[0-9;?]*[A-Za-z]|\033\]8;;.*?\033\\")
|
|
30
|
+
_FRAMES = "◒◐◓◑"
|
|
31
|
+
_LOGO = (
|
|
32
|
+
" ██████╗██╗ ██╗██████╗ ███████╗███╗ ██╗",
|
|
33
|
+
"██╔════╝██║ ██║██╔══██╗██╔════╝████╗ ██║",
|
|
34
|
+
"██║ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║",
|
|
35
|
+
"██║ ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║",
|
|
36
|
+
"╚██████╗███████╗██║██║ ███████╗██║ ╚████║",
|
|
37
|
+
" ╚═════╝╚══════╝╚═╝╚═╝ ╚══════╝╚═╝ ╚═══╝",
|
|
38
|
+
)
|
|
39
|
+
# The brand gold from the README badges, warming to amber down the logo.
|
|
40
|
+
_LOGO_COLOURS = ((246, 211, 122), (240, 198, 100), (233, 180, 76), (226, 160, 62), (218, 140, 52), (208, 120, 44))
|
|
41
|
+
_BRAND = (233, 180, 76)
|
|
42
|
+
# The npx launcher sets this when it has drawn the logo and opened the frame the installer continues.
|
|
43
|
+
FRAME_OPEN = "CLIPEN_FRAME_OPEN"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def display_width(text: str) -> int:
|
|
47
|
+
"""Columns the text takes in a terminal: CJK characters take two, colour codes none."""
|
|
48
|
+
width = 0
|
|
49
|
+
for character in _ANSI.sub("", text):
|
|
50
|
+
if unicodedata.combining(character):
|
|
51
|
+
continue
|
|
52
|
+
width += 2 if unicodedata.east_asian_width(character) in "WF" else 1
|
|
53
|
+
return width
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _clip(text: str, columns: int) -> str:
|
|
57
|
+
"""Cut the text to the given columns, keeping colour codes whole."""
|
|
58
|
+
if display_width(text) <= columns:
|
|
59
|
+
return text
|
|
60
|
+
pieces: list[str] = []
|
|
61
|
+
used = 0
|
|
62
|
+
position = 0
|
|
63
|
+
while position < len(text):
|
|
64
|
+
code = _ANSI.match(text, position)
|
|
65
|
+
if code:
|
|
66
|
+
pieces.append(code.group())
|
|
67
|
+
position = code.end()
|
|
68
|
+
continue
|
|
69
|
+
character = text[position]
|
|
70
|
+
width = 2 if unicodedata.east_asian_width(character) in "WF" else 1
|
|
71
|
+
if used + width > columns - 1:
|
|
72
|
+
pieces.append("…\033[0m" if "\033[" in text else "…")
|
|
73
|
+
break
|
|
74
|
+
pieces.append(character)
|
|
75
|
+
used += width
|
|
76
|
+
position += 1
|
|
77
|
+
return "".join(pieces)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _wrap(text: str, columns: int) -> list[str]:
|
|
81
|
+
"""Break a plain line so each piece fits the columns."""
|
|
82
|
+
lines: list[str] = []
|
|
83
|
+
current = ""
|
|
84
|
+
for character in text:
|
|
85
|
+
if current and display_width(current + character) > columns:
|
|
86
|
+
lines.append(current)
|
|
87
|
+
current = character.lstrip() if character == " " else character
|
|
88
|
+
else:
|
|
89
|
+
current += character
|
|
90
|
+
return [*lines, current]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _is_terminal(stream: TextIO) -> bool:
|
|
94
|
+
try:
|
|
95
|
+
return stream.isatty()
|
|
96
|
+
except (AttributeError, ValueError):
|
|
97
|
+
return False
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Terminal:
|
|
101
|
+
def __init__(self, stream: TextIO | None = None) -> None:
|
|
102
|
+
self.stream = stream if stream is not None else sys.stdout
|
|
103
|
+
self.live = _is_terminal(self.stream)
|
|
104
|
+
self.colour = bool(os.environ.get("FORCE_COLOR")) or (self.live and "NO_COLOR" not in os.environ)
|
|
105
|
+
|
|
106
|
+
# Colours ---------------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
def paint(self, code: str, text: str) -> str:
|
|
109
|
+
return f"\033[{code}m{text}\033[0m" if self.colour else text
|
|
110
|
+
|
|
111
|
+
def rgb(self, colour: tuple[int, int, int], text: str) -> str:
|
|
112
|
+
return self.paint("38;2;{};{};{}".format(*colour), text)
|
|
113
|
+
|
|
114
|
+
def brand(self, text: str) -> str:
|
|
115
|
+
return self.rgb(_BRAND, text)
|
|
116
|
+
|
|
117
|
+
def bold(self, text: str) -> str:
|
|
118
|
+
return self.paint("1", text)
|
|
119
|
+
|
|
120
|
+
def dim(self, text: str) -> str:
|
|
121
|
+
return self.paint("2", text)
|
|
122
|
+
|
|
123
|
+
def link(self, url: str) -> str:
|
|
124
|
+
"""A URL the terminal can open with a click."""
|
|
125
|
+
shown = self.paint("4;36", url)
|
|
126
|
+
return f"\033]8;;{url}\033\\{shown}\033]8;;\033\\" if self.live else shown
|
|
127
|
+
|
|
128
|
+
def columns(self) -> int:
|
|
129
|
+
return shutil.get_terminal_size((80, 24)).columns if self.live else 100
|
|
130
|
+
|
|
131
|
+
# Output ----------------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
def write(self, line: str = "") -> None:
|
|
134
|
+
self.stream.write(f"{line}\n")
|
|
135
|
+
self.stream.flush()
|
|
136
|
+
|
|
137
|
+
def _bar(self) -> str:
|
|
138
|
+
return self.paint("90", "│")
|
|
139
|
+
|
|
140
|
+
def _item(self, symbol: str, message: str) -> None:
|
|
141
|
+
first, *rest = message.split("\n")
|
|
142
|
+
self.write(self._bar())
|
|
143
|
+
self.write(f"{symbol} {first}")
|
|
144
|
+
for line in rest:
|
|
145
|
+
self.write(f"{self._bar()} {line}")
|
|
146
|
+
|
|
147
|
+
def logo(self, subtitle: str = "") -> None:
|
|
148
|
+
"""The CLIPEN wordmark, or a compact badge where it would not fit."""
|
|
149
|
+
if self.colour and self.columns() >= 50:
|
|
150
|
+
self.write()
|
|
151
|
+
for line, colour in zip(_LOGO, _LOGO_COLOURS):
|
|
152
|
+
self.write(f" {self.rgb(colour, line)}")
|
|
153
|
+
if subtitle:
|
|
154
|
+
self.write(f" {self.dim(subtitle)}")
|
|
155
|
+
self.write()
|
|
156
|
+
else:
|
|
157
|
+
self.write(f"Clipen {subtitle}".rstrip())
|
|
158
|
+
|
|
159
|
+
def intro(self, title: str) -> None:
|
|
160
|
+
self.write(f"{self.paint('90', '┌')} {self.paint('30;48;2;233;180;76', f' {title} ')}")
|
|
161
|
+
|
|
162
|
+
def outro(self, message: str) -> None:
|
|
163
|
+
self.write(self._bar())
|
|
164
|
+
self.write(f"{self.paint('90', '└')} {message}")
|
|
165
|
+
self.write()
|
|
166
|
+
|
|
167
|
+
def step(self, message: str) -> None:
|
|
168
|
+
self._item(self.paint("32", "◇"), message)
|
|
169
|
+
|
|
170
|
+
def info(self, message: str) -> None:
|
|
171
|
+
self._item(self.paint("34", "●"), message)
|
|
172
|
+
|
|
173
|
+
def warn(self, message: str) -> None:
|
|
174
|
+
self._item(self.paint("33", "▲"), message)
|
|
175
|
+
|
|
176
|
+
def error(self, message: str) -> None:
|
|
177
|
+
self._item(self.paint("31", "■"), message)
|
|
178
|
+
|
|
179
|
+
def note(self, title: str, lines: Sequence[str], footer: Sequence[str] = ()) -> None:
|
|
180
|
+
"""A framed block: what is about to happen, before the person is asked.
|
|
181
|
+
|
|
182
|
+
Footer lines are plain fine print, wrapped to the terminal and dimmed.
|
|
183
|
+
"""
|
|
184
|
+
limit = max(20, self.columns() - 6)
|
|
185
|
+
body = [piece for line in lines for piece in (_wrap(line, limit) if not _ANSI.search(line) else [line])]
|
|
186
|
+
if footer:
|
|
187
|
+
body += ([""] if body else []) + [self.dim(piece) for line in footer for piece in _wrap(line, limit)]
|
|
188
|
+
inner = max([display_width(line) for line in body] + [display_width(title) + 2])
|
|
189
|
+
grey = lambda text: self.paint("90", text) # noqa: E731
|
|
190
|
+
self.write(self._bar())
|
|
191
|
+
self.write(
|
|
192
|
+
f"{self.paint('32', '◇')} {self.bold(title)} {grey('─' * (inner + 1 - display_width(title)) + '╮')}"
|
|
193
|
+
)
|
|
194
|
+
self.write(grey("│") + " " * (inner + 4) + grey("│"))
|
|
195
|
+
for line in body:
|
|
196
|
+
self.write(f"{grey('│')} {line}{' ' * (inner - display_width(line))} {grey('│')}")
|
|
197
|
+
self.write(grey("│") + " " * (inner + 4) + grey("│"))
|
|
198
|
+
self.write(grey("├" + "─" * (inner + 4) + "╯"))
|
|
199
|
+
|
|
200
|
+
# Prompts ---------------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
def confirm(self, message: str, stdin: TextIO, *, default: bool = True) -> bool:
|
|
203
|
+
"""Yes or no; arrow keys in a terminal, a typed y/n anywhere else."""
|
|
204
|
+
if self.live and termios is not None and _is_terminal(stdin):
|
|
205
|
+
try:
|
|
206
|
+
descriptor = stdin.fileno()
|
|
207
|
+
except (AttributeError, OSError, ValueError):
|
|
208
|
+
descriptor = None
|
|
209
|
+
if descriptor is not None:
|
|
210
|
+
return self._confirm_keys(message, descriptor, default)
|
|
211
|
+
hint = "[Y/n]" if default else "[y/N]"
|
|
212
|
+
self.write(self._bar())
|
|
213
|
+
self.stream.write(f"{self.paint('36', '◆')} {message} {self.dim(hint)} ")
|
|
214
|
+
self.stream.flush()
|
|
215
|
+
answer = stdin.readline().strip().lower()
|
|
216
|
+
if not self.live: # A terminal echoes the Enter; anywhere else the next item needs its own line.
|
|
217
|
+
self.write()
|
|
218
|
+
return answer in {"y", "yes"} or (default and answer == "")
|
|
219
|
+
|
|
220
|
+
def _confirm_keys(self, message: str, descriptor: int, value: bool) -> bool:
|
|
221
|
+
def choices() -> str:
|
|
222
|
+
yes = (
|
|
223
|
+
tr(f"{self.paint('32', '●')} 是", f"{self.paint('32', '●')} Yes")
|
|
224
|
+
if value
|
|
225
|
+
else tr(f"{self.dim('○ 是')}", f"{self.dim('○ Yes')}")
|
|
226
|
+
)
|
|
227
|
+
no = (
|
|
228
|
+
tr(f"{self.paint('32', '●')} 否", f"{self.paint('32', '●')} No")
|
|
229
|
+
if not value
|
|
230
|
+
else tr(f"{self.dim('○ 否')}", f"{self.dim('○ No')}")
|
|
231
|
+
)
|
|
232
|
+
return f"{yes} {self.dim('/')} {no}"
|
|
233
|
+
|
|
234
|
+
def draw(first: bool) -> None:
|
|
235
|
+
if not first:
|
|
236
|
+
self.stream.write("\r\033[2A\033[J")
|
|
237
|
+
self.stream.write(
|
|
238
|
+
f"{self.paint('36', '◆')} {message}\n{self.paint('36', '│')} {choices()}\n{self.paint('36', '└')}"
|
|
239
|
+
)
|
|
240
|
+
self.stream.flush()
|
|
241
|
+
|
|
242
|
+
saved = termios.tcgetattr(descriptor)
|
|
243
|
+
self.write(self._bar())
|
|
244
|
+
self.stream.write("\033[?25l")
|
|
245
|
+
submitted = False
|
|
246
|
+
try:
|
|
247
|
+
tty.setcbreak(descriptor)
|
|
248
|
+
draw(True)
|
|
249
|
+
while True:
|
|
250
|
+
key = os.read(descriptor, 8)
|
|
251
|
+
if key in (b"\r", b"\n"):
|
|
252
|
+
break
|
|
253
|
+
if key in (b"y", b"Y", b"n", b"N"):
|
|
254
|
+
value = key in (b"y", b"Y")
|
|
255
|
+
break
|
|
256
|
+
if key in (b"\x1b",):
|
|
257
|
+
value = False
|
|
258
|
+
break
|
|
259
|
+
if key in (b"\x1b[C", b"\x1b[D", b"\x1b[A", b"\x1b[B", b"\t", b" ", b"h", b"l", b"j", b"k"):
|
|
260
|
+
value = not value
|
|
261
|
+
draw(False)
|
|
262
|
+
submitted = True
|
|
263
|
+
finally:
|
|
264
|
+
termios.tcsetattr(descriptor, termios.TCSADRAIN, saved)
|
|
265
|
+
self.stream.write("\r\033[2A\033[J")
|
|
266
|
+
symbol = self.paint("32", "◇") if submitted else self.paint("31", "■")
|
|
267
|
+
answer = (
|
|
268
|
+
tr(("是" if value else "否"), ("Yes" if value else "No")) if submitted else tr("已取消", "Cancelled")
|
|
269
|
+
)
|
|
270
|
+
self.stream.write(f"{symbol} {message}\n{self._bar()} {self.dim(answer)}\n\033[?25h")
|
|
271
|
+
self.stream.flush()
|
|
272
|
+
return value
|
|
273
|
+
|
|
274
|
+
# Progress --------------------------------------------------------------------------------
|
|
275
|
+
|
|
276
|
+
@contextmanager
|
|
277
|
+
def spinner(self, message: str) -> Iterator[Spinner]:
|
|
278
|
+
"""An animated line while work runs, closed with ◇ on success or ■ when it fails."""
|
|
279
|
+
spinner = Spinner(self, message)
|
|
280
|
+
self.write(self._bar())
|
|
281
|
+
spinner.start()
|
|
282
|
+
try:
|
|
283
|
+
yield spinner
|
|
284
|
+
except BaseException:
|
|
285
|
+
spinner.stop()
|
|
286
|
+
self.write(f"{self.paint('31', '■')} {spinner.current}")
|
|
287
|
+
raise
|
|
288
|
+
spinner.stop()
|
|
289
|
+
self.write(f"{self.paint('32', '◇')} {spinner.final or spinner.current}")
|
|
290
|
+
|
|
291
|
+
def progress_bar(self, percent: int, width: int = 24) -> str:
|
|
292
|
+
filled = max(0, min(width, percent * width // 100))
|
|
293
|
+
return self.brand("━" * filled) + self.paint("90", "─" * (width - filled))
|
|
294
|
+
|
|
295
|
+
def overwrite(self, line: str) -> None:
|
|
296
|
+
"""Redraw the current line in place (a live terminal only)."""
|
|
297
|
+
self.stream.write("\r\033[K" + _clip(line, self.columns() - 1))
|
|
298
|
+
self.stream.flush()
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class Spinner:
|
|
302
|
+
def __init__(self, terminal: Terminal, message: str) -> None:
|
|
303
|
+
self._terminal = terminal
|
|
304
|
+
self.current = message
|
|
305
|
+
self.final: str | None = None
|
|
306
|
+
self._started = time.monotonic()
|
|
307
|
+
self._stopped = threading.Event()
|
|
308
|
+
self._thread: threading.Thread | None = None
|
|
309
|
+
|
|
310
|
+
def update(self, message: str) -> None:
|
|
311
|
+
self.current = message
|
|
312
|
+
|
|
313
|
+
def done(self, message: str) -> None:
|
|
314
|
+
"""What the line says once the work has finished."""
|
|
315
|
+
self.final = message
|
|
316
|
+
|
|
317
|
+
def start(self) -> None:
|
|
318
|
+
if not self._terminal.live:
|
|
319
|
+
return
|
|
320
|
+
self._terminal.stream.write("\033[?25l")
|
|
321
|
+
self._thread = threading.Thread(target=self._spin, name="clipen-spinner", daemon=True)
|
|
322
|
+
self._thread.start()
|
|
323
|
+
|
|
324
|
+
def stop(self) -> None:
|
|
325
|
+
self._stopped.set()
|
|
326
|
+
if self._thread is not None:
|
|
327
|
+
self._thread.join()
|
|
328
|
+
self._terminal.stream.write("\r\033[K\033[?25h")
|
|
329
|
+
self._terminal.stream.flush()
|
|
330
|
+
|
|
331
|
+
def _spin(self) -> None:
|
|
332
|
+
frame = 0
|
|
333
|
+
while True:
|
|
334
|
+
elapsed = int(time.monotonic() - self._started)
|
|
335
|
+
clock = (
|
|
336
|
+
tr(f"{elapsed // 60} 分 {elapsed % 60:02d} 秒", f"{elapsed // 60}m {elapsed % 60:02d}s")
|
|
337
|
+
if elapsed >= 60
|
|
338
|
+
else tr(f"{elapsed} 秒", f"{elapsed}s")
|
|
339
|
+
)
|
|
340
|
+
symbol = self._terminal.paint("35", _FRAMES[frame % len(_FRAMES)])
|
|
341
|
+
self._terminal.overwrite(f"{symbol} {self.current} {self._terminal.dim(clock)}")
|
|
342
|
+
frame += 1
|
|
343
|
+
if self._stopped.wait(0.08):
|
|
344
|
+
return
|