odforge 0.3.0__py3-none-any.whl
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.
- odforge/__init__.py +1 -0
- odforge/benchmark.py +287 -0
- odforge/check.py +416 -0
- odforge/cli.py +1027 -0
- odforge/components.py +270 -0
- odforge/critic.py +1260 -0
- odforge/docfonts.py +104 -0
- odforge/editor_api.py +33 -0
- odforge/editor_launch.py +134 -0
- odforge/editor_routes.py +131 -0
- odforge/extract.py +478 -0
- odforge/feedback.py +86 -0
- odforge/fontembed.py +166 -0
- odforge/ir.py +1181 -0
- odforge/layoutcheck.py +602 -0
- odforge/llm.py +1865 -0
- odforge/localguard.py +42 -0
- odforge/mcp_server.py +552 -0
- odforge/media.py +352 -0
- odforge/odpedit.py +1219 -0
- odforge/package.py +114 -0
- odforge/pagefacts.py +388 -0
- odforge/preview.py +104 -0
- odforge/references.py +153 -0
- odforge/render/__init__.py +40 -0
- odforge/render/odp.py +5687 -0
- odforge/render/ods.py +155 -0
- odforge/render/odt.py +223 -0
- odforge/scene.py +657 -0
- odforge/setup_agents.py +274 -0
- odforge/skills/odforge-design/SKILL.md +298 -0
- odforge/skills/odforge-design/themes/academic.md +52 -0
- odforge/skills/odforge-design/themes/clay.md +53 -0
- odforge/skills/odforge-design/themes/color-system.md +59 -0
- odforge/skills/odforge-design/themes/crimson.md +53 -0
- odforge/skills/odforge-design/themes/dark.md +53 -0
- odforge/skills/odforge-design/themes/forest.md +54 -0
- odforge/skills/odforge-design/themes/gold.md +53 -0
- odforge/skills/odforge-design/themes/minimal.md +53 -0
- odforge/skills/odforge-design/themes/navy.md +56 -0
- odforge/skills/odforge-design/themes/plum.md +53 -0
- odforge/skills/odforge-design/themes/sky.md +53 -0
- odforge/skills/odforge-design/themes/slate.md +53 -0
- odforge/skills/odforge-design/themes/teal.md +53 -0
- odforge/skills/odforge-design/themes/violet.md +56 -0
- odforge/templates.py +250 -0
- odforge/textmetrics.py +616 -0
- odforge/textutil.py +24 -0
- odforge/themes.py +886 -0
- odforge/validate.py +403 -0
- odforge/watch.py +266 -0
- odforge/webapi.py +2617 -0
- odforge/webui/assets/editor-CjpYXM1a.css +1 -0
- odforge/webui/assets/editor-DPToJGio.js +3 -0
- odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
- odforge/webui/assets/main-BLOs7Hnk.js +7 -0
- odforge/webui/assets/main-D21yFVE6.css +1 -0
- odforge/webui/editor.html +14 -0
- odforge/webui/index.html +25 -0
- odforge/xmlsafe.py +46 -0
- odforge/zipguard.py +91 -0
- odforge-0.3.0.dist-info/METADATA +95 -0
- odforge-0.3.0.dist-info/RECORD +66 -0
- odforge-0.3.0.dist-info/WHEEL +4 -0
- odforge-0.3.0.dist-info/entry_points.txt +3 -0
- odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/cli.py
ADDED
|
@@ -0,0 +1,1027 @@
|
|
|
1
|
+
"""ODForge command-line interface.
|
|
2
|
+
|
|
3
|
+
``odforge new`` turns a natural-language prompt into a native ODF file:
|
|
4
|
+
generate IR -> render -> validate -> present the outcome. This module holds
|
|
5
|
+
no business logic: it only parses arguments, wires the existing building
|
|
6
|
+
blocks together and presents the result. Task 8.2 adds a ``check`` subcommand.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ipaddress
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
from enum import Enum
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import List, Mapping, Optional
|
|
17
|
+
|
|
18
|
+
import typer
|
|
19
|
+
from rich.console import Console
|
|
20
|
+
from rich.markup import escape
|
|
21
|
+
from rich.table import Table
|
|
22
|
+
|
|
23
|
+
from odforge.benchmark import run_benchmark
|
|
24
|
+
from odforge.check import check_odf_verdict, diff_docx_odt_verdict
|
|
25
|
+
from odforge.critic import QAReport, run_qa_loop
|
|
26
|
+
from odforge.extract import extract_design
|
|
27
|
+
from odforge.ir import Branding, MediaAssetRef, Outline
|
|
28
|
+
from odforge.layoutcheck import check_layout
|
|
29
|
+
from odforge.llm import (
|
|
30
|
+
DroppedContent,
|
|
31
|
+
generate_ir,
|
|
32
|
+
generate_outline,
|
|
33
|
+
generate_slides,
|
|
34
|
+
)
|
|
35
|
+
from odforge.media import AssetBlob, AssetInput, MediaError, load_local_image
|
|
36
|
+
from odforge.render import render
|
|
37
|
+
from odforge.textmetrics import check_budget, deck_warnings
|
|
38
|
+
from odforge.textutil import concise
|
|
39
|
+
from odforge.themes import resolve_design, resolve_style
|
|
40
|
+
from odforge.validate import find_soffice, validate_odf
|
|
41
|
+
|
|
42
|
+
# Output extension -> IR doc_type. Also the source of the "supported types"
|
|
43
|
+
# message shown when an unknown extension is given.
|
|
44
|
+
_EXT_DOC_TYPE = {
|
|
45
|
+
".odt": "text",
|
|
46
|
+
".odp": "presentation",
|
|
47
|
+
".ods": "spreadsheet",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Theme(str, Enum):
|
|
52
|
+
academic = "academic"
|
|
53
|
+
minimal = "minimal"
|
|
54
|
+
dark = "dark"
|
|
55
|
+
teal = "teal"
|
|
56
|
+
forest = "forest"
|
|
57
|
+
navy = "navy"
|
|
58
|
+
violet = "violet"
|
|
59
|
+
crimson = "crimson"
|
|
60
|
+
slate = "slate"
|
|
61
|
+
gold = "gold"
|
|
62
|
+
sky = "sky"
|
|
63
|
+
plum = "plum"
|
|
64
|
+
clay = "clay"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class StyleName(str, Enum):
|
|
68
|
+
classic = "classic"
|
|
69
|
+
report = "report"
|
|
70
|
+
academic = "academic"
|
|
71
|
+
keynote = "keynote"
|
|
72
|
+
editorial = "editorial"
|
|
73
|
+
passport = "passport"
|
|
74
|
+
zen = "zen"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Language(str, Enum):
|
|
78
|
+
zh_tw = "zh-TW"
|
|
79
|
+
en = "en"
|
|
80
|
+
bilingual = "bilingual"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class LogoPlacement(str, Enum):
|
|
84
|
+
cover = "cover"
|
|
85
|
+
cover_closing = "cover-closing"
|
|
86
|
+
all = "all"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Backend(str, Enum):
|
|
90
|
+
# Must stay in step with llm.BACKENDS — a backend the registry offers but
|
|
91
|
+
# this enum omits is one typer rejects before it ever reaches the registry
|
|
92
|
+
# (test_cli_backend_choices_match_the_registry holds the two together).
|
|
93
|
+
codex = "codex"
|
|
94
|
+
ollama = "ollama"
|
|
95
|
+
custom = "custom"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Mode(str, Enum):
|
|
99
|
+
detailed = "detailed"
|
|
100
|
+
presenter = "presenter"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
app = typer.Typer(
|
|
104
|
+
add_completion=False,
|
|
105
|
+
no_args_is_help=True,
|
|
106
|
+
help="將自然語言鍛造成原生 ODF 文件(.odt / .odp / .ods)。",
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
_out = Console()
|
|
110
|
+
_err = Console(stderr=True)
|
|
111
|
+
|
|
112
|
+
def _concise(exc: Exception) -> str:
|
|
113
|
+
"""One-line, length-bounded, rich-markup-safe rendering of an exception."""
|
|
114
|
+
return escape(concise(str(exc)))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _print_outline(outline: Outline) -> None:
|
|
118
|
+
"""Render a stage-1 outline for the interactive checkpoint.
|
|
119
|
+
|
|
120
|
+
Prints a page-role table (頁碼 / 版型 / 標題 / gist / 視覺意圖) and a design summary:
|
|
121
|
+
the palette shown as five hex colour swatches, the font pairing, density
|
|
122
|
+
scale and narrative mode. LLM-provided strings (titles, gists, fonts) are
|
|
123
|
+
``escape``\\ d before interpolation into rich markup; palette values are
|
|
124
|
+
already validated ``#RRGGBB`` hex, safe as both a style and displayed text.
|
|
125
|
+
"""
|
|
126
|
+
table = Table(title="大綱")
|
|
127
|
+
table.add_column("頁碼", justify="right")
|
|
128
|
+
table.add_column("版型")
|
|
129
|
+
table.add_column("標題", overflow="fold")
|
|
130
|
+
table.add_column("gist", overflow="fold")
|
|
131
|
+
table.add_column("視覺意圖", overflow="fold")
|
|
132
|
+
for i, page in enumerate(outline.pages, start=1):
|
|
133
|
+
table.add_row(
|
|
134
|
+
str(i),
|
|
135
|
+
escape(page.role),
|
|
136
|
+
escape(page.title),
|
|
137
|
+
escape(page.gist),
|
|
138
|
+
escape(page.visual_intent),
|
|
139
|
+
)
|
|
140
|
+
_out.print(table)
|
|
141
|
+
|
|
142
|
+
design = outline.design
|
|
143
|
+
if design is not None:
|
|
144
|
+
pal = design.palette
|
|
145
|
+
swatches = " ".join(
|
|
146
|
+
f"[on {c}] [/]"
|
|
147
|
+
for c in (pal.bg, pal.surface, pal.text, pal.muted, pal.accent)
|
|
148
|
+
)
|
|
149
|
+
_out.print(
|
|
150
|
+
f"色盤 {swatches} bg={pal.bg} surface={pal.surface} "
|
|
151
|
+
f"text={pal.text} muted={pal.muted} accent={pal.accent}"
|
|
152
|
+
)
|
|
153
|
+
_out.print(
|
|
154
|
+
f"字體 {escape(design.fonts.display)} / {escape(design.fonts.body)}"
|
|
155
|
+
f" 密度 {escape(design.scale)}"
|
|
156
|
+
)
|
|
157
|
+
else:
|
|
158
|
+
_out.print("美術方向:未指定(將套用預設主題)")
|
|
159
|
+
_out.print(f"講述型態(mode):{escape(outline.mode)}")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _print_dropped_content(dropped: List[DroppedContent]) -> None:
|
|
163
|
+
"""Name every line the layout budget removed, on stderr, in full.
|
|
164
|
+
|
|
165
|
+
The engine's last-resort degrade used to leave one parenthetical in the
|
|
166
|
+
speaker notes. That is technically a disclosure and practically a silent
|
|
167
|
+
deletion: nobody reads the notes of a page they did not know had changed.
|
|
168
|
+
The user asked for this content — if it could not be kept, they are told
|
|
169
|
+
exactly what went, so they can decide whether to re-run with more pages.
|
|
170
|
+
"""
|
|
171
|
+
if not dropped:
|
|
172
|
+
return
|
|
173
|
+
table = Table(title="因版面限制未能保留的內容")
|
|
174
|
+
table.add_column("頁", justify="right")
|
|
175
|
+
table.add_column("標題", overflow="fold")
|
|
176
|
+
table.add_column("被移除的內容", overflow="fold")
|
|
177
|
+
for record in dropped:
|
|
178
|
+
table.add_row(
|
|
179
|
+
str(record.slide_no),
|
|
180
|
+
escape(record.title),
|
|
181
|
+
escape("、".join(record.items)),
|
|
182
|
+
)
|
|
183
|
+
_err.print(table)
|
|
184
|
+
_err.print(
|
|
185
|
+
"[yellow]提醒[/yellow] 以上內容已寫進該頁的備忘稿。"
|
|
186
|
+
"若不希望被刪,請提高 --pages 或縮短需求中的重點數量後重新生成。"
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _print_layout(path: Path) -> None:
|
|
191
|
+
"""Print where LibreOffice laid text out beyond its frame or page, if anywhere."""
|
|
192
|
+
layout = check_layout(path, find_soffice())
|
|
193
|
+
if layout.status == "ok":
|
|
194
|
+
_out.print(f"[green]跑版檢查 OK[/green] {escape(layout.message)}")
|
|
195
|
+
elif layout.status == "overflow":
|
|
196
|
+
_out.print(f"[yellow]跑版[/yellow] {escape(layout.message)}:")
|
|
197
|
+
for finding in layout.findings:
|
|
198
|
+
_out.print(f" - {escape(finding.describe())}")
|
|
199
|
+
else:
|
|
200
|
+
_out.print(f"[dim]跑版檢查略過:{escape(layout.message)}[/dim]")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _print_qa_report(report: QAReport) -> None:
|
|
204
|
+
"""Render a run_qa_loop outcome as a before/after summary table."""
|
|
205
|
+
table = Table(title="設計評審(第四道閘)")
|
|
206
|
+
table.add_column("輪次", justify="right")
|
|
207
|
+
table.add_column("error", justify="right")
|
|
208
|
+
table.add_column("warn", justify="right")
|
|
209
|
+
for i, findings in enumerate(report.findings_by_round, start=1):
|
|
210
|
+
errors = sum(1 for f in findings if f.severity == "error")
|
|
211
|
+
warns = sum(1 for f in findings if f.severity == "warn")
|
|
212
|
+
table.add_row(str(i), str(errors), str(warns))
|
|
213
|
+
_out.print(table)
|
|
214
|
+
if report.note:
|
|
215
|
+
_out.print(f"[dim]{escape(report.note)}[/dim]")
|
|
216
|
+
# The three verdicts print as three different things, because they mean three
|
|
217
|
+
# different things. "設計 OK" is reserved for a review that actually
|
|
218
|
+
# completed and found nothing; a review that never happened prints 未完成,
|
|
219
|
+
# never a green tick — 無法檢查不等於通過.
|
|
220
|
+
if report.verdict == "unknown":
|
|
221
|
+
_out.print("[yellow]設計評審未完成[/yellow](視覺品檢無法執行,等同未檢查)")
|
|
222
|
+
elif report.verdict == "pass":
|
|
223
|
+
_out.print(f"[green]設計 OK[/green](共 {report.rounds} 輪)")
|
|
224
|
+
elif report.failure and report.repaired:
|
|
225
|
+
_out.print(
|
|
226
|
+
f"[yellow]設計評審未完成[/yellow](完成 {report.rounds} 輪後中斷;"
|
|
227
|
+
"已套用的修補未經複驗)"
|
|
228
|
+
)
|
|
229
|
+
elif report.failure:
|
|
230
|
+
_out.print(f"[yellow]設計評審未完成[/yellow](完成 {report.rounds} 輪後中斷)")
|
|
231
|
+
else:
|
|
232
|
+
_out.print(
|
|
233
|
+
f"[yellow]設計仍有 error[/yellow](達上限 {report.rounds} 輪仍未收斂)"
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _run_qa(
|
|
238
|
+
ir,
|
|
239
|
+
out_path: Path,
|
|
240
|
+
outline: Optional[Outline],
|
|
241
|
+
llm_backend: Optional[str],
|
|
242
|
+
assets: Mapping[str, AssetInput] | None = None,
|
|
243
|
+
) -> bool:
|
|
244
|
+
"""Run the design-QA loop (第四道閘) and print a before/after summary.
|
|
245
|
+
|
|
246
|
+
Returns whether QA **rewrote and re-rendered** the deck. The caller needs to
|
|
247
|
+
know: a repaired deck is a different file from the one the three format gates
|
|
248
|
+
just approved, and reporting the old verdict for new bytes is how a broken
|
|
249
|
+
package could ship under a green table.
|
|
250
|
+
|
|
251
|
+
Requires LibreOffice (soffice) and a vision backend
|
|
252
|
+
(``ODFORGE_VISION_BACKEND != off``). If either is missing, print a clear
|
|
253
|
+
message and fall back to the deterministic budget gate (already run) — the
|
|
254
|
+
command never fails on ``--qa``. Any QA-side error is likewise swallowed
|
|
255
|
+
into a message rather than crashing the run.
|
|
256
|
+
"""
|
|
257
|
+
vision_backend = os.environ.get("ODFORGE_VISION_BACKEND", "off")
|
|
258
|
+
reasons = []
|
|
259
|
+
if find_soffice() is None:
|
|
260
|
+
reasons.append("找不到 LibreOffice(soffice)")
|
|
261
|
+
if vision_backend == "off":
|
|
262
|
+
reasons.append("未設定視覺後端(ODFORGE_VISION_BACKEND=off)")
|
|
263
|
+
if reasons:
|
|
264
|
+
_err.print(
|
|
265
|
+
"[yellow]--qa 已略過[/yellow] 設計評審需要 soffice 與視覺後端:"
|
|
266
|
+
+ "、".join(reasons)
|
|
267
|
+
+ "。已改跑內建的版面預算閘(deterministic)。"
|
|
268
|
+
)
|
|
269
|
+
return False
|
|
270
|
+
|
|
271
|
+
# QA's repair path re-runs the layout budget, so it can drop bullets too.
|
|
272
|
+
# Silent there is no better than silent anywhere else.
|
|
273
|
+
dropped: List[DroppedContent] = []
|
|
274
|
+
try:
|
|
275
|
+
qa_kwargs = {
|
|
276
|
+
"outline": outline,
|
|
277
|
+
"backend": vision_backend,
|
|
278
|
+
"llm_backend": llm_backend,
|
|
279
|
+
"dropped": dropped,
|
|
280
|
+
}
|
|
281
|
+
if assets:
|
|
282
|
+
qa_kwargs["render_assets"] = assets
|
|
283
|
+
report = run_qa_loop(ir, out_path, **qa_kwargs)
|
|
284
|
+
except Exception as exc:
|
|
285
|
+
_err.print(f"[yellow]--qa 已略過[/yellow] 設計評審發生問題:{_concise(exc)}")
|
|
286
|
+
_print_dropped_content(dropped)
|
|
287
|
+
# The loop works on a candidate file and only swaps it in on the way out,
|
|
288
|
+
# so a failure inside it leaves the deck on disk untouched — the version
|
|
289
|
+
# the three format gates already approved. Re-validate anyway: it costs
|
|
290
|
+
# one soffice run, and "the file cannot have changed" is a claim worth
|
|
291
|
+
# having checked rather than reasoned about.
|
|
292
|
+
return True
|
|
293
|
+
|
|
294
|
+
_print_qa_report(report)
|
|
295
|
+
_print_dropped_content(dropped)
|
|
296
|
+
return report.repaired
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@app.callback()
|
|
300
|
+
def _root() -> None:
|
|
301
|
+
"""ODForge:自然語言 → 原生 ODF。"""
|
|
302
|
+
# A no-op callback keeps ``new`` (and Task 8.2's ``check``) as named
|
|
303
|
+
# subcommands rather than collapsing into a single implicit command.
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
@app.command()
|
|
307
|
+
def new(
|
|
308
|
+
prompt: str = typer.Argument(..., help="自然語言的文件需求描述。"),
|
|
309
|
+
out: Path = typer.Option(
|
|
310
|
+
...,
|
|
311
|
+
"-o",
|
|
312
|
+
"--out",
|
|
313
|
+
help="輸出檔案路徑;副檔名決定文件類型(.odt / .odp / .ods)。",
|
|
314
|
+
),
|
|
315
|
+
theme: Optional[Theme] = typer.Option(
|
|
316
|
+
None, "--theme", help="簡報主題,僅對 .odp 有效;省略則尊重 LLM 的選擇。"
|
|
317
|
+
),
|
|
318
|
+
mode: Optional[Mode] = typer.Option(
|
|
319
|
+
None,
|
|
320
|
+
"--mode",
|
|
321
|
+
help="講述型態,僅對 .odp 兩段式流程有效:presenter(講者型)/ "
|
|
322
|
+
"detailed(自讀型);省略則沿用大綱的判斷。",
|
|
323
|
+
),
|
|
324
|
+
style: Optional[StyleName] = typer.Option(
|
|
325
|
+
None,
|
|
326
|
+
"--style",
|
|
327
|
+
help="版式(僅對 .odp 有效):classic 學院派 / report 顧問報告 / "
|
|
328
|
+
"academic 學術簡潔 / keynote 舞台 / editorial 編輯風 / passport 護照(審查、"
|
|
329
|
+
"提案、成果報告)/ zen 極簡;"
|
|
330
|
+
"省略則用主題配對的預設版式。",
|
|
331
|
+
),
|
|
332
|
+
language: Language = typer.Option(
|
|
333
|
+
Language.zh_tw,
|
|
334
|
+
"--language",
|
|
335
|
+
help="輸出語言:zh-TW(繁體中文,預設)/ en(英文)/ bilingual(中英對照)。",
|
|
336
|
+
),
|
|
337
|
+
byline: str = typer.Option(
|
|
338
|
+
"",
|
|
339
|
+
"--byline",
|
|
340
|
+
help="封面署名(單位/講者/日期),僅對 .odp 有效。",
|
|
341
|
+
),
|
|
342
|
+
logo: Optional[Path] = typer.Option(
|
|
343
|
+
None,
|
|
344
|
+
"--logo",
|
|
345
|
+
exists=True,
|
|
346
|
+
dir_okay=False,
|
|
347
|
+
readable=True,
|
|
348
|
+
help="封面校徽/機構標誌(PNG 或 JPEG),僅對 .odp 有效。",
|
|
349
|
+
),
|
|
350
|
+
logo_placement: LogoPlacement = typer.Option(
|
|
351
|
+
LogoPlacement.cover_closing,
|
|
352
|
+
"--logo-placement",
|
|
353
|
+
help="校徽出現在哪些頁:cover(只封面)/ cover-closing(封面與結尾,預設)/ all(每頁)。",
|
|
354
|
+
),
|
|
355
|
+
backend: Optional[Backend] = typer.Option(
|
|
356
|
+
None, "--backend", help="LLM 後端;省略則使用預設。"
|
|
357
|
+
),
|
|
358
|
+
image: Optional[List[Path]] = typer.Option(
|
|
359
|
+
None,
|
|
360
|
+
"--image",
|
|
361
|
+
exists=True,
|
|
362
|
+
dir_okay=False,
|
|
363
|
+
readable=True,
|
|
364
|
+
help="加入可供簡報使用的 PNG/JPEG 素材;可重複指定。",
|
|
365
|
+
),
|
|
366
|
+
from_template: Optional[Path] = typer.Option(
|
|
367
|
+
None,
|
|
368
|
+
"--from-template",
|
|
369
|
+
help="吃現有 ODF 公版範本(.otp/.odp/.ott/.odt):抽出其樣式並鎖定設計,"
|
|
370
|
+
"LLM 只負責內容。僅對 .odp 有效。",
|
|
371
|
+
),
|
|
372
|
+
interactive: bool = typer.Option(
|
|
373
|
+
False,
|
|
374
|
+
"--interactive",
|
|
375
|
+
help="簡報兩段式流程:先印出大綱供確認,確認後才生成投影片。",
|
|
376
|
+
),
|
|
377
|
+
one_shot: bool = typer.Option(
|
|
378
|
+
False,
|
|
379
|
+
"--one-shot",
|
|
380
|
+
help="簡報改用 v1 單次呼叫(一段式)產生,供弱模型 / Ollama 的逃生路徑使用。",
|
|
381
|
+
),
|
|
382
|
+
soffice: bool = typer.Option(
|
|
383
|
+
True,
|
|
384
|
+
"--soffice/--no-soffice",
|
|
385
|
+
help="驗證時若找得到 LibreOffice 就跑 soffice 轉檔驗證。",
|
|
386
|
+
),
|
|
387
|
+
qa: bool = typer.Option(
|
|
388
|
+
False,
|
|
389
|
+
"--qa",
|
|
390
|
+
help="簡報專用:算圖後跑「第四道閘」設計評審迴圈(render→critique→repair);"
|
|
391
|
+
"需 soffice + 視覺後端,缺任一則略過。",
|
|
392
|
+
),
|
|
393
|
+
) -> None:
|
|
394
|
+
"""由 PROMPT 產生一份 ODF 文件並輸出到 -o 指定的檔案。
|
|
395
|
+
|
|
396
|
+
簡報(.odp)預設走兩段式流程:先產生大綱(美術方向 + 頁面骨架),再逐頁填內容。
|
|
397
|
+
``--interactive`` 會在兩段之間停下來印出大綱供確認;``--one-shot`` 則退回單次
|
|
398
|
+
呼叫的一段式路徑。文字(.odt)與試算表(.ods)一律走單次呼叫。
|
|
399
|
+
"""
|
|
400
|
+
ext = out.suffix.lower()
|
|
401
|
+
doc_type = _EXT_DOC_TYPE.get(ext)
|
|
402
|
+
if doc_type is None:
|
|
403
|
+
supported = ", ".join(sorted(_EXT_DOC_TYPE))
|
|
404
|
+
_err.print(
|
|
405
|
+
f"[red]FAIL[/red] 不支援的副檔名 {escape(repr(ext or '(無)'))};"
|
|
406
|
+
f"支援的類型:{escape(supported)}"
|
|
407
|
+
)
|
|
408
|
+
raise typer.Exit(code=2)
|
|
409
|
+
|
|
410
|
+
backend_name = backend.value if backend else None
|
|
411
|
+
asset_blobs: dict[str, AssetBlob] = {}
|
|
412
|
+
asset_refs: list[MediaAssetRef] = []
|
|
413
|
+
if image:
|
|
414
|
+
if doc_type != "presentation":
|
|
415
|
+
_err.print("[dim]--image 僅適用於 .odp,已忽略。[/dim]")
|
|
416
|
+
else:
|
|
417
|
+
try:
|
|
418
|
+
for index, image_path in enumerate(image, start=1):
|
|
419
|
+
asset_id = f"image-{index:02d}"
|
|
420
|
+
asset_blobs[asset_id] = load_local_image(image_path)
|
|
421
|
+
asset_refs.append(
|
|
422
|
+
MediaAssetRef(
|
|
423
|
+
id=asset_id,
|
|
424
|
+
description=image_path.stem.replace("_", " "),
|
|
425
|
+
)
|
|
426
|
+
)
|
|
427
|
+
except MediaError as exc:
|
|
428
|
+
_err.print(f"[red]FAIL[/red] 圖片素材無法使用:{_concise(exc)}")
|
|
429
|
+
raise typer.Exit(code=1) from None
|
|
430
|
+
|
|
431
|
+
# --from-template (吃現有範本): extract a DesignSpec from a public template and
|
|
432
|
+
# LOCK it — the LLM only produces content, the look comes from the template.
|
|
433
|
+
# Only meaningful for presentations; extracted here (before the pipeline) so
|
|
434
|
+
# it can be locked onto the stage-1 outline AND enforced on the final deck.
|
|
435
|
+
extracted_design = None
|
|
436
|
+
if from_template is not None:
|
|
437
|
+
if doc_type != "presentation":
|
|
438
|
+
_err.print("[dim]--from-template 僅適用於簡報(.odp),已略過[/dim]")
|
|
439
|
+
else:
|
|
440
|
+
try:
|
|
441
|
+
extracted_design = extract_design(from_template)
|
|
442
|
+
except Exception as exc:
|
|
443
|
+
_err.print(f"[red]FAIL[/red] 範本樣式抽取失敗:{_concise(exc)}")
|
|
444
|
+
raise typer.Exit(code=1) from None
|
|
445
|
+
_out.print(f"[cyan]套用範本樣式[/cyan] {escape(str(from_template))}")
|
|
446
|
+
|
|
447
|
+
# The stage-1 outline, when the two-stage path runs — captured so --qa can
|
|
448
|
+
# hand it to the repair step for per-page regeneration (None otherwise).
|
|
449
|
+
outline: Optional[Outline] = None
|
|
450
|
+
# Two-stage (outline -> slides) is the presentation default; .odt/.ods and
|
|
451
|
+
# the --one-shot escape hatch stay on the v1 single-call generate_ir path.
|
|
452
|
+
if doc_type == "presentation" and not one_shot:
|
|
453
|
+
try:
|
|
454
|
+
outline = generate_outline(
|
|
455
|
+
prompt, backend=backend_name, language=language.value
|
|
456
|
+
)
|
|
457
|
+
except Exception as exc:
|
|
458
|
+
_err.print(f"[red]FAIL[/red] 大綱產生失敗:{_concise(exc)}")
|
|
459
|
+
raise typer.Exit(code=1) from None
|
|
460
|
+
|
|
461
|
+
# --mode overrides the outline's narrative register before stage 2.
|
|
462
|
+
if mode is not None:
|
|
463
|
+
outline = outline.model_copy(update={"mode": mode.value})
|
|
464
|
+
# --language likewise: stage 2 reads it off the outline.
|
|
465
|
+
outline = outline.model_copy(update={"language": language.value})
|
|
466
|
+
outline = outline.model_copy(
|
|
467
|
+
update={
|
|
468
|
+
"media_assets": asset_refs,
|
|
469
|
+
"image_generation_available": (
|
|
470
|
+
os.getenv("ODFORGE_IMAGE_BACKEND", "off").lower() == "http"
|
|
471
|
+
and bool(os.getenv("ODFORGE_IMAGE_ENDPOINT", "").strip())
|
|
472
|
+
),
|
|
473
|
+
}
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
# --from-template locks the design: overwrite the outline's design with
|
|
477
|
+
# the extracted one so stage 2 fills content against the locked art
|
|
478
|
+
# direction (generate_slides re-attaches outline.design onto the deck).
|
|
479
|
+
if extracted_design is not None:
|
|
480
|
+
outline = outline.model_copy(update={"design": extracted_design})
|
|
481
|
+
|
|
482
|
+
# Interactive checkpoint: show the outline, then gate stage 2 on confirm.
|
|
483
|
+
if interactive:
|
|
484
|
+
_print_outline(outline)
|
|
485
|
+
if not typer.confirm("依此大綱生成?"):
|
|
486
|
+
_out.print("已取消")
|
|
487
|
+
raise typer.Exit(code=0)
|
|
488
|
+
|
|
489
|
+
dropped: List[DroppedContent] = []
|
|
490
|
+
try:
|
|
491
|
+
ir = generate_slides(outline, backend=backend_name, dropped=dropped)
|
|
492
|
+
except Exception as exc:
|
|
493
|
+
_err.print(f"[red]FAIL[/red] 內容產生失敗:{_concise(exc)}")
|
|
494
|
+
raise typer.Exit(code=1) from None
|
|
495
|
+
_print_dropped_content(dropped)
|
|
496
|
+
else:
|
|
497
|
+
try:
|
|
498
|
+
ir = generate_ir(
|
|
499
|
+
prompt, doc_type, backend=backend_name, language=language.value
|
|
500
|
+
)
|
|
501
|
+
except Exception as exc:
|
|
502
|
+
_err.print(f"[red]FAIL[/red] 內容產生失敗:{_concise(exc)}")
|
|
503
|
+
raise typer.Exit(code=1) from None
|
|
504
|
+
|
|
505
|
+
# --theme only matters for presentations. When given, it locks a built-in
|
|
506
|
+
# preset: the theme is overridden AND any LLM-attached DesignSpec is dropped.
|
|
507
|
+
# Dropping the design is essential — resolve_design lets a present design win
|
|
508
|
+
# over p.theme, so leaving it intact would make --theme a silent no-op on the
|
|
509
|
+
# two-stage path. When omitted (None), the LLM's own choice is respected.
|
|
510
|
+
if doc_type == "presentation" and theme is not None:
|
|
511
|
+
dropped_design = ir.design is not None
|
|
512
|
+
ir = ir.model_copy(update={"theme": theme.value, "design": None})
|
|
513
|
+
if dropped_design:
|
|
514
|
+
_err.print("[dim]--theme 指定,已改用預設主題(捨棄 AI 自選設計)[/dim]")
|
|
515
|
+
|
|
516
|
+
# --from-template wins outright: enforce the extracted design on the final
|
|
517
|
+
# deck (after --theme, so the template look always beats a preset/LLM choice
|
|
518
|
+
# and is honoured even if stage 2 dropped the locked design).
|
|
519
|
+
if extracted_design is not None:
|
|
520
|
+
ir = ir.model_copy(update={"design": extracted_design})
|
|
521
|
+
|
|
522
|
+
# --style locks the layout personality (cover composition, heading marks,
|
|
523
|
+
# divider treatment, footer furniture). Independent of --theme: any palette
|
|
524
|
+
# can be worn by any composition.
|
|
525
|
+
if doc_type == "presentation" and style is not None:
|
|
526
|
+
ir = ir.model_copy(update={"style": style.value})
|
|
527
|
+
|
|
528
|
+
# Cover branding (署名 / 校徽). App-owned, so it is written onto the deck
|
|
529
|
+
# AFTER generation — never asked of the model, never taken from it.
|
|
530
|
+
if doc_type == "presentation" and (byline.strip() or logo is not None):
|
|
531
|
+
logo_ref = ""
|
|
532
|
+
if logo is not None:
|
|
533
|
+
try:
|
|
534
|
+
asset_blobs["logo"] = load_local_image(logo)
|
|
535
|
+
except MediaError as exc:
|
|
536
|
+
_err.print(f"[red]FAIL[/red] 校徽無法讀取:{_concise(exc)}")
|
|
537
|
+
raise typer.Exit(code=2) from None
|
|
538
|
+
logo_ref = "asset://logo"
|
|
539
|
+
ir = ir.model_copy(
|
|
540
|
+
update={
|
|
541
|
+
"branding": Branding(
|
|
542
|
+
byline=byline.strip(),
|
|
543
|
+
logo=logo_ref,
|
|
544
|
+
placement=logo_placement.value,
|
|
545
|
+
)
|
|
546
|
+
}
|
|
547
|
+
)
|
|
548
|
+
elif byline.strip() or logo is not None:
|
|
549
|
+
_err.print("[dim]--byline / --logo 僅適用於 .odp,已忽略。[/dim]")
|
|
550
|
+
|
|
551
|
+
# Soft layout-budget gate: warn (never fail) when a slide's text overruns its
|
|
552
|
+
# frames. The hard enforcement + LLM retry loop is Task 15.2's job; here we
|
|
553
|
+
# only surface the estimate so a human can see it before opening the file.
|
|
554
|
+
if doc_type == "presentation":
|
|
555
|
+
resolved = resolve_design(ir)
|
|
556
|
+
resolved_style = resolve_style(ir)
|
|
557
|
+
for slide in ir.slides:
|
|
558
|
+
for warning in check_budget(slide, resolved, resolved_style):
|
|
559
|
+
_err.print(f"[yellow]WARN[/yellow] {escape(warning)}")
|
|
560
|
+
for warning in deck_warnings(ir.slides):
|
|
561
|
+
_err.print(f"[yellow]WARN[/yellow] {escape(warning)}")
|
|
562
|
+
|
|
563
|
+
out_path = out.resolve()
|
|
564
|
+
try:
|
|
565
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
566
|
+
render(ir, out_path, assets=asset_blobs)
|
|
567
|
+
with_soffice = bool(soffice) and find_soffice() is not None
|
|
568
|
+
report = validate_odf(out_path, with_soffice=with_soffice)
|
|
569
|
+
except Exception as exc:
|
|
570
|
+
_err.print(f"[red]FAIL[/red] 輸出或驗證失敗:{_concise(exc)}")
|
|
571
|
+
raise typer.Exit(code=1) from None
|
|
572
|
+
|
|
573
|
+
table = Table(title="驗證結果")
|
|
574
|
+
table.add_column("Gate")
|
|
575
|
+
table.add_column("結果")
|
|
576
|
+
table.add_column("訊息", overflow="fold")
|
|
577
|
+
for name, (passed, message) in report.gates.items():
|
|
578
|
+
mark = "[green]OK[/green]" if passed else "[red]FAIL[/red]"
|
|
579
|
+
table.add_row(escape(name), mark, escape(message))
|
|
580
|
+
_out.print(table)
|
|
581
|
+
|
|
582
|
+
# Fourth gate (design QA): opt-in, presentations only. Runs after the three
|
|
583
|
+
# deterministic format gates; degrades to a message (never fails) when
|
|
584
|
+
# soffice or a vision backend is missing.
|
|
585
|
+
if qa:
|
|
586
|
+
if doc_type == "presentation":
|
|
587
|
+
repaired = _run_qa(
|
|
588
|
+
ir,
|
|
589
|
+
out_path,
|
|
590
|
+
outline=outline,
|
|
591
|
+
llm_backend=backend_name,
|
|
592
|
+
assets=asset_blobs,
|
|
593
|
+
)
|
|
594
|
+
if repaired:
|
|
595
|
+
# QA rewrote slides and re-rendered the deck. The gate table
|
|
596
|
+
# printed above described the file that existed *before* that,
|
|
597
|
+
# and the exit code was about to be based on it. Re-validate the
|
|
598
|
+
# bytes actually on disk — the final verdict must come from the
|
|
599
|
+
# same artifact the user is going to open.
|
|
600
|
+
_out.print("[dim]設計評審已修補並重新算圖,重新執行格式驗證…[/dim]")
|
|
601
|
+
try:
|
|
602
|
+
report = validate_odf(out_path, with_soffice=with_soffice)
|
|
603
|
+
except Exception as exc:
|
|
604
|
+
_err.print(f"[red]FAIL[/red] 修補後重新驗證失敗:{_concise(exc)}")
|
|
605
|
+
raise typer.Exit(code=1) from None
|
|
606
|
+
table = Table(title="驗證結果(QA 修補後)")
|
|
607
|
+
table.add_column("Gate")
|
|
608
|
+
table.add_column("結果")
|
|
609
|
+
table.add_column("訊息", overflow="fold")
|
|
610
|
+
for name, (passed, message) in report.gates.items():
|
|
611
|
+
mark = "[green]OK[/green]" if passed else "[red]FAIL[/red]"
|
|
612
|
+
table.add_row(escape(name), mark, escape(message))
|
|
613
|
+
_out.print(table)
|
|
614
|
+
else:
|
|
615
|
+
_err.print("[dim]--qa 僅適用於簡報(.odp),已略過[/dim]")
|
|
616
|
+
|
|
617
|
+
# Rendered 跑版 check on the final bytes (after any QA repair). Advisory like
|
|
618
|
+
# the design gate: it never changes the exit code.
|
|
619
|
+
if with_soffice and doc_type != "spreadsheet":
|
|
620
|
+
_print_layout(out_path)
|
|
621
|
+
|
|
622
|
+
if report.ok:
|
|
623
|
+
_out.print(f"[green]OK[/green] {escape(str(out_path))}")
|
|
624
|
+
raise typer.Exit(code=0)
|
|
625
|
+
|
|
626
|
+
_out.print("[red]FAIL[/red] 驗證未通過。")
|
|
627
|
+
raise typer.Exit(code=1)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
@app.command()
|
|
631
|
+
def benchmark(
|
|
632
|
+
prompt: str = typer.Argument(..., help="所有候選模型共用的簡報題目。"),
|
|
633
|
+
out_dir: Path = typer.Option(
|
|
634
|
+
Path("benchmark-results"),
|
|
635
|
+
"--out-dir",
|
|
636
|
+
help="儲存各候選 outline、IR、ODP、預覽與比較報告的目錄。",
|
|
637
|
+
),
|
|
638
|
+
candidate: Optional[List[Backend]] = typer.Option(
|
|
639
|
+
None,
|
|
640
|
+
"--backend",
|
|
641
|
+
help="要比較的 backend;可重複指定,預設 codex + ollama。",
|
|
642
|
+
),
|
|
643
|
+
pages: Optional[int] = typer.Option(
|
|
644
|
+
None, "--pages", min=3, max=30, help="所有候選共用的目標頁數。"
|
|
645
|
+
),
|
|
646
|
+
image: Optional[List[Path]] = typer.Option(
|
|
647
|
+
None,
|
|
648
|
+
"--image",
|
|
649
|
+
exists=True,
|
|
650
|
+
dir_okay=False,
|
|
651
|
+
readable=True,
|
|
652
|
+
help="所有候選共用的 PNG/JPEG 素材;可重複指定。",
|
|
653
|
+
),
|
|
654
|
+
) -> None:
|
|
655
|
+
"""同題執行多個模型,保留完整產物並輸出可稽核的結構品質報告。"""
|
|
656
|
+
|
|
657
|
+
assets: dict[str, AssetBlob] = {}
|
|
658
|
+
refs: list[MediaAssetRef] = []
|
|
659
|
+
try:
|
|
660
|
+
for index, image_path in enumerate(image or [], start=1):
|
|
661
|
+
asset_id = f"image-{index:02d}"
|
|
662
|
+
assets[asset_id] = load_local_image(image_path)
|
|
663
|
+
refs.append(
|
|
664
|
+
MediaAssetRef(
|
|
665
|
+
id=asset_id,
|
|
666
|
+
description=image_path.stem.replace("_", " "),
|
|
667
|
+
)
|
|
668
|
+
)
|
|
669
|
+
except MediaError as exc:
|
|
670
|
+
_err.print(f"[red]FAIL[/red] 圖片素材無法使用:{_concise(exc)}")
|
|
671
|
+
raise typer.Exit(code=1) from None
|
|
672
|
+
|
|
673
|
+
names = (
|
|
674
|
+
[item.value for item in candidate]
|
|
675
|
+
if candidate
|
|
676
|
+
else [Backend.codex.value, Backend.ollama.value]
|
|
677
|
+
)
|
|
678
|
+
report = run_benchmark(
|
|
679
|
+
prompt,
|
|
680
|
+
names,
|
|
681
|
+
out_dir.resolve(),
|
|
682
|
+
pages=pages,
|
|
683
|
+
assets=assets,
|
|
684
|
+
asset_refs=refs,
|
|
685
|
+
)
|
|
686
|
+
|
|
687
|
+
table = Table(title="模型同題 benchmark")
|
|
688
|
+
table.add_column("Candidate")
|
|
689
|
+
table.add_column("Status")
|
|
690
|
+
table.add_column("Score", justify="right")
|
|
691
|
+
table.add_column("Slides", justify="right")
|
|
692
|
+
table.add_column("Visual", justify="right")
|
|
693
|
+
table.add_column("Seconds", justify="right")
|
|
694
|
+
for entry in report.entries:
|
|
695
|
+
table.add_row(
|
|
696
|
+
escape(entry.candidate),
|
|
697
|
+
"[green]OK[/green]" if entry.success else "[red]FAIL[/red]",
|
|
698
|
+
f"{entry.score:.1f}",
|
|
699
|
+
str(entry.metrics.slide_count),
|
|
700
|
+
f"{entry.metrics.visual_slide_ratio:.0%}",
|
|
701
|
+
f"{entry.elapsed_seconds:.1f}",
|
|
702
|
+
)
|
|
703
|
+
_out.print(table)
|
|
704
|
+
if report.winner:
|
|
705
|
+
_out.print(f"[green]結構分數最高[/green] {escape(report.winner)}")
|
|
706
|
+
_out.print(f"報告:{escape(str(out_dir.resolve() / 'report.md'))}")
|
|
707
|
+
raise typer.Exit(code=0 if any(entry.success for entry in report.entries) else 1)
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def _is_loopback_host(host: str) -> bool:
|
|
711
|
+
"""Return whether a uvicorn bind host is explicitly loopback-only."""
|
|
712
|
+
candidate = host.strip().strip("[]")
|
|
713
|
+
if candidate.lower() == "localhost":
|
|
714
|
+
return True
|
|
715
|
+
try:
|
|
716
|
+
return ipaddress.ip_address(candidate).is_loopback
|
|
717
|
+
except ValueError:
|
|
718
|
+
return False
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _free_port(host: str, preferred: int) -> int:
|
|
722
|
+
"""``preferred`` when it is free, otherwise any free port the OS hands out."""
|
|
723
|
+
import socket
|
|
724
|
+
|
|
725
|
+
for candidate in (preferred, 0):
|
|
726
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
727
|
+
try:
|
|
728
|
+
sock.bind((host, candidate))
|
|
729
|
+
except OSError:
|
|
730
|
+
continue
|
|
731
|
+
return sock.getsockname()[1]
|
|
732
|
+
raise typer.BadParameter("找不到可用的連接埠", param_hint="--port")
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
@app.command()
|
|
736
|
+
def setup(
|
|
737
|
+
remove: bool = typer.Option(False, "--remove", help="撤銷 setup 做過的設定。"),
|
|
738
|
+
claude: bool = typer.Option(True, "--claude/--no-claude", help="設定 Claude Code。"),
|
|
739
|
+
codex: bool = typer.Option(True, "--codex/--no-codex", help="設定 Codex。"),
|
|
740
|
+
) -> None:
|
|
741
|
+
"""把 ODForge 接上這台電腦的 AI 助理:註冊 MCP、安裝 skill、讓 odforge 指令找得到。"""
|
|
742
|
+
from odforge.setup_agents import setup as run_setup
|
|
743
|
+
|
|
744
|
+
steps = run_setup(remove=remove, claude=claude, codex=codex)
|
|
745
|
+
for step in steps:
|
|
746
|
+
mark = "[green]OK[/green]" if step.ok else "[yellow]略過[/yellow]"
|
|
747
|
+
_out.print(f"{mark} {escape(step.label)}:{escape(step.detail)}")
|
|
748
|
+
if not remove and any(s.ok for s in steps):
|
|
749
|
+
_out.print(
|
|
750
|
+
"[dim]開一個新的 Claude Code / Codex 對話就能用:例如「用 ODForge 做一份…簡報」,"
|
|
751
|
+
"或在編輯器留言後說「照留言修改」。[/dim]"
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
@app.command()
|
|
756
|
+
def init(
|
|
757
|
+
directory: Path = typer.Argument(Path("."), help="要放簡報的資料夾(預設是目前資料夾)。"),
|
|
758
|
+
) -> None:
|
|
759
|
+
"""讓這個資料夾裡的 AI 助理自己就會用 ODForge:放 AGENTS.md、skill 與 .mcp.json。"""
|
|
760
|
+
from odforge.setup_agents import init_project
|
|
761
|
+
|
|
762
|
+
steps = init_project(directory)
|
|
763
|
+
for step in steps:
|
|
764
|
+
mark = "[green]OK[/green]" if step.ok else "[yellow]略過[/yellow]"
|
|
765
|
+
_out.print(f"{mark} {escape(step.label)}:{escape(step.detail)}")
|
|
766
|
+
if any(s.ok for s in steps):
|
|
767
|
+
_out.print(
|
|
768
|
+
f"[dim]在 {escape(str(directory))} 開 Claude Code / Codex,"
|
|
769
|
+
"直接說「做一份…簡報」就好。[/dim]"
|
|
770
|
+
)
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
@app.command()
|
|
774
|
+
def edit(
|
|
775
|
+
file: Path = typer.Argument(..., help="要編輯的簡報(.odp)。"),
|
|
776
|
+
host: str = typer.Option("127.0.0.1", "--host", help="綁定位址(只接受本機)。"),
|
|
777
|
+
port: int = typer.Option(8790, "--port", help="連接埠;被佔用時自動換一個。"),
|
|
778
|
+
open_browser: bool = typer.Option(
|
|
779
|
+
True, "--open/--no-open", help="啟動後用預設瀏覽器打開編輯器。"
|
|
780
|
+
),
|
|
781
|
+
) -> None:
|
|
782
|
+
"""在瀏覽器裡編輯一份 .odp:拖動、改字、新增與排序頁面,每一步自動存檔。"""
|
|
783
|
+
if not _is_loopback_host(host):
|
|
784
|
+
raise typer.BadParameter("編輯器只能綁定本機位址", param_hint="--host")
|
|
785
|
+
if file.suffix.lower() != ".odp" or not file.is_file():
|
|
786
|
+
_err.print(f"[red]FAIL[/red] 找不到簡報檔 {escape(str(file))}(需要 .odp)")
|
|
787
|
+
raise typer.Exit(code=1)
|
|
788
|
+
try:
|
|
789
|
+
import uvicorn
|
|
790
|
+
|
|
791
|
+
from odforge.editor_api import create_editor_app
|
|
792
|
+
from odforge.odpedit import EditError
|
|
793
|
+
from odforge.webapi import frontend_dist
|
|
794
|
+
except ImportError as exc:
|
|
795
|
+
_err.print(
|
|
796
|
+
"[red]FAIL[/red] 缺少 web 相依,請先安裝:"
|
|
797
|
+
"[cyan]pip install \"odforge[web]\"[/cyan]"
|
|
798
|
+
f"({_concise(exc)})"
|
|
799
|
+
)
|
|
800
|
+
raise typer.Exit(code=1) from None
|
|
801
|
+
if frontend_dist() is None:
|
|
802
|
+
_err.print(
|
|
803
|
+
"[red]FAIL[/red] 找不到建置好的前端。請在 odforge/ 下執行 "
|
|
804
|
+
"[cyan]npm --prefix web ci && npm --prefix web run build[/cyan]。"
|
|
805
|
+
)
|
|
806
|
+
raise typer.Exit(code=1)
|
|
807
|
+
try:
|
|
808
|
+
app_ = create_editor_app(file)
|
|
809
|
+
except (EditError, OSError, ValueError) as exc:
|
|
810
|
+
_err.print(f"[red]FAIL[/red] 無法開啟:{escape(_concise(exc))}")
|
|
811
|
+
raise typer.Exit(code=1) from None
|
|
812
|
+
|
|
813
|
+
from odforge.localguard import add_local_guard, local_hosts
|
|
814
|
+
|
|
815
|
+
bound = _free_port(host, port)
|
|
816
|
+
add_local_guard(app_, local_hosts(bound))
|
|
817
|
+
url = f"http://{host}:{bound}/editor.html"
|
|
818
|
+
_out.print(f"[green]ODForge 編輯器[/green] {escape(url)}")
|
|
819
|
+
_out.print(f"[dim]編輯 {escape(str(file.resolve()))};每一步自動存檔。Ctrl+C 結束。[/dim]")
|
|
820
|
+
if open_browser:
|
|
821
|
+
import threading
|
|
822
|
+
import webbrowser
|
|
823
|
+
|
|
824
|
+
threading.Timer(1.0, webbrowser.open, args=(url,)).start()
|
|
825
|
+
uvicorn.run(app_, host=host, port=bound, log_level="warning")
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
@app.command()
|
|
829
|
+
def preview(
|
|
830
|
+
file: Path = typer.Argument(..., help="要預覽的簡報 Document IR(JSON 檔)。"),
|
|
831
|
+
out: Optional[Path] = typer.Option(
|
|
832
|
+
None,
|
|
833
|
+
"-o",
|
|
834
|
+
"--out",
|
|
835
|
+
help="每次重新排版後把 .odp 寫到這裡;預設與 JSON 同名同目錄。",
|
|
836
|
+
),
|
|
837
|
+
host: str = typer.Option("127.0.0.1", "--host", help="綁定位址(只接受本機)。"),
|
|
838
|
+
port: int = typer.Option(8765, "--port", help="連接埠;被佔用時自動換一個。"),
|
|
839
|
+
open_browser: bool = typer.Option(
|
|
840
|
+
True, "--open/--no-open", help="啟動後用預設瀏覽器打開預覽頁。"
|
|
841
|
+
),
|
|
842
|
+
) -> None:
|
|
843
|
+
"""即時預覽一份簡報 IR:檔案一改就重新排版,網頁自動更新並顯示跑版。
|
|
844
|
+
|
|
845
|
+
給 agent 用的工作方式:agent 編輯 JSON,這裡負責排版、驗證、轉成 .odp,
|
|
846
|
+
使用者在瀏覽器看結果。需安裝 web 相依並先建置前端。
|
|
847
|
+
"""
|
|
848
|
+
if not _is_loopback_host(host):
|
|
849
|
+
raise typer.BadParameter("預覽只能綁定本機位址", param_hint="--host")
|
|
850
|
+
try:
|
|
851
|
+
import uvicorn
|
|
852
|
+
|
|
853
|
+
from odforge.watch import create_preview_app
|
|
854
|
+
from odforge.webapi import frontend_dist
|
|
855
|
+
except ImportError as exc:
|
|
856
|
+
_err.print(
|
|
857
|
+
"[red]FAIL[/red] 缺少 web 相依,請先安裝:"
|
|
858
|
+
"[cyan]pip install \"odforge[web]\"[/cyan]"
|
|
859
|
+
f"({_concise(exc)})"
|
|
860
|
+
)
|
|
861
|
+
raise typer.Exit(code=1) from None
|
|
862
|
+
if frontend_dist() is None:
|
|
863
|
+
_err.print(
|
|
864
|
+
"[red]FAIL[/red] 找不到建置好的前端。請在 odforge/ 下執行 "
|
|
865
|
+
"[cyan]npm --prefix web ci && npm --prefix web run build[/cyan]。"
|
|
866
|
+
)
|
|
867
|
+
raise typer.Exit(code=1)
|
|
868
|
+
if not file.is_file():
|
|
869
|
+
_err.print(f"[red]FAIL[/red] 找不到 {escape(str(file))}")
|
|
870
|
+
raise typer.Exit(code=1)
|
|
871
|
+
|
|
872
|
+
target = out if out is not None else file.with_suffix(".odp")
|
|
873
|
+
def announce(text: str) -> None:
|
|
874
|
+
stamp = time.strftime("%H:%M:%S")
|
|
875
|
+
# Plain print, flushed: an agent running this in the background reads
|
|
876
|
+
# the output file to learn what changed, and Rich markup would be noise.
|
|
877
|
+
print(f"[{stamp}] {text}", flush=True)
|
|
878
|
+
|
|
879
|
+
app_, job = create_preview_app(file, target, announce=announce)
|
|
880
|
+
from odforge.localguard import add_local_guard, local_hosts
|
|
881
|
+
|
|
882
|
+
bound = _free_port(host, port)
|
|
883
|
+
add_local_guard(app_, local_hosts(bound))
|
|
884
|
+
url = f"http://{host}:{bound}/?job={job.id}&watch=1"
|
|
885
|
+
_out.print(f"[green]ODForge 預覽[/green] {escape(url)}")
|
|
886
|
+
_out.print(
|
|
887
|
+
f"[dim]監看 {escape(str(file.resolve()))};成品寫到 "
|
|
888
|
+
f"{escape(str(target.resolve()))}。Ctrl+C 結束。[/dim]"
|
|
889
|
+
)
|
|
890
|
+
if open_browser:
|
|
891
|
+
import threading
|
|
892
|
+
import webbrowser
|
|
893
|
+
|
|
894
|
+
threading.Timer(1.0, webbrowser.open, args=(url,)).start()
|
|
895
|
+
uvicorn.run(app_, host=host, port=bound, log_level="warning")
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
@app.command()
|
|
899
|
+
def serve(
|
|
900
|
+
host: str = typer.Option(
|
|
901
|
+
"127.0.0.1", "--host", help="伺服器綁定的位址(本機工具預設 127.0.0.1)。"
|
|
902
|
+
),
|
|
903
|
+
port: int = typer.Option(8000, "--port", help="伺服器連接埠。"),
|
|
904
|
+
allow_remote: bool = typer.Option(
|
|
905
|
+
False,
|
|
906
|
+
"--allow-remote",
|
|
907
|
+
help="明確允許非 loopback 綁定;API 無認證,僅限受信任網路。",
|
|
908
|
+
),
|
|
909
|
+
) -> None:
|
|
910
|
+
"""啟動 ODForge Web API 伺服器(FastAPI + SSE),供前端控制台驅動兩段式生成。
|
|
911
|
+
|
|
912
|
+
需安裝 web 相依:``pip install "odforge[web]"``。fastapi / uvicorn /
|
|
913
|
+
sse-starlette 只在此指令內延遲載入,核心套件不因它們而變重。
|
|
914
|
+
"""
|
|
915
|
+
if not _is_loopback_host(host) and not allow_remote:
|
|
916
|
+
raise typer.BadParameter(
|
|
917
|
+
"非本機綁定會暴露無認證且可花用 LLM 金鑰的 API;"
|
|
918
|
+
"若已確認網路與防火牆可信,請加上 --allow-remote。",
|
|
919
|
+
param_hint="--host",
|
|
920
|
+
)
|
|
921
|
+
if not _is_loopback_host(host):
|
|
922
|
+
_err.print(
|
|
923
|
+
"[bold yellow]警告[/bold yellow] 遠端模式無認證;請只在受信任網路使用,"
|
|
924
|
+
"並設定明確的 ODFORGE_CORS_ORIGINS。"
|
|
925
|
+
)
|
|
926
|
+
# Subscription-authenticated backends (codex) refuse to run behind a
|
|
927
|
+
# public bind: with no authentication in front of the API, they would
|
|
928
|
+
# spend the operator's personal plan for whoever reaches the port.
|
|
929
|
+
os.environ["ODFORGE_PUBLIC_BIND"] = "1"
|
|
930
|
+
|
|
931
|
+
# Load a local .env (odforge/.env) so API keys and endpoints can live in a file
|
|
932
|
+
# instead of the shell env. Best-effort: python-dotenv ships with the web extra,
|
|
933
|
+
# and this runs only for `serve`, never at import time (so tests stay unaffected).
|
|
934
|
+
# The project-relative path makes it independent of the current working dir.
|
|
935
|
+
try:
|
|
936
|
+
from dotenv import load_dotenv
|
|
937
|
+
|
|
938
|
+
load_dotenv(Path(__file__).resolve().parents[2] / ".env")
|
|
939
|
+
load_dotenv() # also honour a .env in the current working dir, if present
|
|
940
|
+
except ImportError:
|
|
941
|
+
pass
|
|
942
|
+
|
|
943
|
+
try:
|
|
944
|
+
import uvicorn
|
|
945
|
+
|
|
946
|
+
from odforge.webapi import create_app, frontend_dist
|
|
947
|
+
except ImportError as exc:
|
|
948
|
+
_err.print(
|
|
949
|
+
"[red]FAIL[/red] 缺少 web 相依,請先安裝:"
|
|
950
|
+
"[cyan]pip install \"odforge[web]\"[/cyan]"
|
|
951
|
+
f"({_concise(exc)})"
|
|
952
|
+
)
|
|
953
|
+
raise typer.Exit(code=1) from None
|
|
954
|
+
|
|
955
|
+
if frontend_dist() is not None:
|
|
956
|
+
_out.print(
|
|
957
|
+
f"[green]ODForge[/green] 完整控制台啟動於 http://{escape(host)}:{port}/ "
|
|
958
|
+
"(前端已掛載,Ctrl+C 結束)"
|
|
959
|
+
)
|
|
960
|
+
else:
|
|
961
|
+
# 不要假設「現在的工作目錄就是 repo 根目錄」。從 wheel 安裝的使用者根本
|
|
962
|
+
# 沒有 odforge/web 這個目錄,叫他去那裡跑 npm 只會讓人更困惑;那種情況是
|
|
963
|
+
# 安裝檔本身沒帶前端(見 hatch_build.py),要重裝而不是重 build。
|
|
964
|
+
from odforge.webapi import __file__ as _webapi_file
|
|
965
|
+
|
|
966
|
+
source_web = Path(_webapi_file).resolve().parents[2] / "web"
|
|
967
|
+
if (source_web / "package.json").is_file():
|
|
968
|
+
hint = (
|
|
969
|
+
f"前端尚未 build:先執行 `npm --prefix {escape(str(source_web))} ci` "
|
|
970
|
+
f"與 `npm --prefix {escape(str(source_web))} run build`,"
|
|
971
|
+
"或另開一個 `npm run dev` 開發伺服器"
|
|
972
|
+
)
|
|
973
|
+
else:
|
|
974
|
+
hint = (
|
|
975
|
+
"這份安裝沒有內含前端資產(API-only wheel)。"
|
|
976
|
+
"請改裝含前端的版本:[cyan]pip install --force-reinstall \"odforge[web]\"[/cyan]"
|
|
977
|
+
)
|
|
978
|
+
_out.print(
|
|
979
|
+
f"[green]ODForge Web API[/green] 啟動於 http://{escape(host)}:{port} "
|
|
980
|
+
f"(API-only:{hint};Ctrl+C 結束)"
|
|
981
|
+
)
|
|
982
|
+
uvicorn.run(create_app(), host=host, port=port)
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
@app.command()
|
|
986
|
+
def check(
|
|
987
|
+
file: Path = typer.Argument(
|
|
988
|
+
..., help="要檢測的檔案;.odt/.odp/.ods 做 ODF 檢測,.docx 做結構比對。"
|
|
989
|
+
),
|
|
990
|
+
out: Optional[Path] = typer.Option(
|
|
991
|
+
None,
|
|
992
|
+
"-o",
|
|
993
|
+
"--out",
|
|
994
|
+
help="同時把報告寫入此檔案(UTF-8)。",
|
|
995
|
+
),
|
|
996
|
+
) -> None:
|
|
997
|
+
"""檢測一份 ODF 檔(.odt/.odp/.ods),或比對 .docx 與其轉出的 .odt 結構。"""
|
|
998
|
+
ext = file.suffix.lower()
|
|
999
|
+
if ext == ".docx":
|
|
1000
|
+
report, failed = diff_docx_odt_verdict(file)
|
|
1001
|
+
elif ext in _EXT_DOC_TYPE:
|
|
1002
|
+
report, failed = check_odf_verdict(file)
|
|
1003
|
+
else:
|
|
1004
|
+
supported = ", ".join(sorted((*_EXT_DOC_TYPE, ".docx")))
|
|
1005
|
+
report = (
|
|
1006
|
+
f"error: unsupported extension {ext or '(無)'!r}; "
|
|
1007
|
+
f"supported: {supported}"
|
|
1008
|
+
)
|
|
1009
|
+
failed = True
|
|
1010
|
+
|
|
1011
|
+
# Print the raw markdown so stdout is exactly the report body; keep any
|
|
1012
|
+
# side notes on stderr so ``-o`` output and stdout stay identical.
|
|
1013
|
+
typer.echo(report)
|
|
1014
|
+
|
|
1015
|
+
if out is not None:
|
|
1016
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
1017
|
+
out.write_text(report, encoding="utf-8")
|
|
1018
|
+
_err.print(f"[green]OK[/green] 報告已寫入 {escape(str(out))}")
|
|
1019
|
+
|
|
1020
|
+
# The exit code comes from the structured verdict, never from grepping the
|
|
1021
|
+
# report: its free text echoes file/style names, and a valid file named
|
|
1022
|
+
# q4-FAIL-review.odt must not exit 1.
|
|
1023
|
+
raise typer.Exit(code=1 if failed else 0)
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
if __name__ == "__main__": # pragma: no cover
|
|
1027
|
+
app()
|