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/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.3.0"
|
odforge/benchmark.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Same-prompt presentation benchmark with reproducible artifacts.
|
|
2
|
+
|
|
3
|
+
The score is a structural quality proxy, not a substitute for human or vision
|
|
4
|
+
review. Every candidate keeps its outline, final IR, native ODP and previews so
|
|
5
|
+
the numeric summary remains auditable.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import List, Mapping, Optional
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, Field
|
|
17
|
+
|
|
18
|
+
from odforge.ir import MediaAssetRef, Outline, Presentation
|
|
19
|
+
from odforge.llm import generate_outline, generate_slides
|
|
20
|
+
from odforge.media import AssetInput
|
|
21
|
+
from odforge.preview import PreviewUnavailable, render_pages
|
|
22
|
+
from odforge.render import render
|
|
23
|
+
from odforge.textmetrics import check_budget
|
|
24
|
+
from odforge.themes import resolve_design
|
|
25
|
+
from odforge.validate import validate_odf
|
|
26
|
+
|
|
27
|
+
_VISUAL_LAYOUTS = {
|
|
28
|
+
"chart",
|
|
29
|
+
"process",
|
|
30
|
+
"timeline",
|
|
31
|
+
"metrics",
|
|
32
|
+
"cards",
|
|
33
|
+
"diagram",
|
|
34
|
+
"image-focus",
|
|
35
|
+
"image-split",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class BenchmarkMetrics(BaseModel):
|
|
40
|
+
slide_count: int = 0
|
|
41
|
+
layout_variety: int = 0
|
|
42
|
+
visual_slide_ratio: float = 0.0
|
|
43
|
+
notes_coverage: float = 0.0
|
|
44
|
+
source_coverage: float = 0.0
|
|
45
|
+
budget_warning_count: int = 0
|
|
46
|
+
image_placeholder_count: int = 0
|
|
47
|
+
package_valid: bool = False
|
|
48
|
+
previews_rendered: int = 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class BenchmarkEntry(BaseModel):
|
|
52
|
+
candidate: str
|
|
53
|
+
success: bool
|
|
54
|
+
score: float = Field(ge=0, le=100)
|
|
55
|
+
elapsed_seconds: float
|
|
56
|
+
metrics: BenchmarkMetrics = Field(default_factory=BenchmarkMetrics)
|
|
57
|
+
artifact_dir: str
|
|
58
|
+
error: Optional[str] = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class BenchmarkReport(BaseModel):
|
|
62
|
+
prompt: str
|
|
63
|
+
pages: Optional[int] = None
|
|
64
|
+
entries: List[BenchmarkEntry]
|
|
65
|
+
winner: Optional[str] = None
|
|
66
|
+
scoring_note: str = (
|
|
67
|
+
"Score is a deterministic structural proxy; inspect previews and use "
|
|
68
|
+
"vision/human review for visual quality."
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _safe_name(value: str) -> str:
|
|
73
|
+
cleaned = re.sub(r"[^A-Za-z0-9_-]+", "-", value).strip("-").lower()
|
|
74
|
+
return cleaned[:48] or "candidate"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _placeholder_count(
|
|
78
|
+
presentation: Presentation,
|
|
79
|
+
assets: Mapping[str, AssetInput] | None,
|
|
80
|
+
image_generation_available: bool,
|
|
81
|
+
) -> int:
|
|
82
|
+
known = set((assets or {}).keys())
|
|
83
|
+
count = 0
|
|
84
|
+
for slide in presentation.slides:
|
|
85
|
+
image = slide.image
|
|
86
|
+
if image is None:
|
|
87
|
+
continue
|
|
88
|
+
if image.src.startswith("asset://"):
|
|
89
|
+
if image.src.removeprefix("asset://") not in known:
|
|
90
|
+
count += 1
|
|
91
|
+
elif not image.src and image.prompt and not image_generation_available:
|
|
92
|
+
count += 1
|
|
93
|
+
return count
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def measure_presentation(
|
|
97
|
+
presentation: Presentation,
|
|
98
|
+
*,
|
|
99
|
+
assets: Mapping[str, AssetInput] | None = None,
|
|
100
|
+
package_valid: bool = False,
|
|
101
|
+
previews_rendered: int = 0,
|
|
102
|
+
image_generation_available: bool = False,
|
|
103
|
+
) -> BenchmarkMetrics:
|
|
104
|
+
"""Compute deterministic metrics from a generated presentation."""
|
|
105
|
+
|
|
106
|
+
slides = presentation.slides
|
|
107
|
+
total = len(slides)
|
|
108
|
+
theme = resolve_design(presentation)
|
|
109
|
+
visual = sum(slide.layout in _VISUAL_LAYOUTS for slide in slides)
|
|
110
|
+
notes = sum(bool(slide.notes.strip()) for slide in slides)
|
|
111
|
+
sources = sum(bool(slide.sources) for slide in slides)
|
|
112
|
+
warnings = sum(len(check_budget(slide, theme)) for slide in slides)
|
|
113
|
+
return BenchmarkMetrics(
|
|
114
|
+
slide_count=total,
|
|
115
|
+
layout_variety=len({slide.layout for slide in slides}),
|
|
116
|
+
visual_slide_ratio=visual / total if total else 0.0,
|
|
117
|
+
notes_coverage=notes / total if total else 0.0,
|
|
118
|
+
source_coverage=sources / total if total else 0.0,
|
|
119
|
+
budget_warning_count=warnings,
|
|
120
|
+
image_placeholder_count=_placeholder_count(
|
|
121
|
+
presentation, assets, image_generation_available
|
|
122
|
+
),
|
|
123
|
+
package_valid=package_valid,
|
|
124
|
+
previews_rendered=previews_rendered,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def score_presentation(
|
|
129
|
+
presentation: Presentation, metrics: BenchmarkMetrics
|
|
130
|
+
) -> float:
|
|
131
|
+
"""Return a 0–100 structural quality score."""
|
|
132
|
+
|
|
133
|
+
if not metrics.package_valid or not presentation.slides:
|
|
134
|
+
return 0.0
|
|
135
|
+
slides = presentation.slides
|
|
136
|
+
score = 10.0 # valid native package
|
|
137
|
+
score += min(20.0, metrics.layout_variety / min(len(slides), 8) * 20.0)
|
|
138
|
+
score += min(25.0, metrics.visual_slide_ratio / 0.6 * 25.0)
|
|
139
|
+
score += metrics.notes_coverage * 15.0
|
|
140
|
+
score += min(10.0, metrics.source_coverage / 0.35 * 10.0)
|
|
141
|
+
score += max(0.0, 15.0 - metrics.budget_warning_count * 3.0)
|
|
142
|
+
if slides[0].layout == "title":
|
|
143
|
+
score += 2.5
|
|
144
|
+
if slides[-1].layout == "closing":
|
|
145
|
+
score += 2.5
|
|
146
|
+
score -= metrics.image_placeholder_count * 8.0
|
|
147
|
+
return round(max(0.0, min(100.0, score)), 1)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _markdown(report: BenchmarkReport) -> str:
|
|
151
|
+
lines = [
|
|
152
|
+
"# ODForge model benchmark",
|
|
153
|
+
"",
|
|
154
|
+
f"Prompt: {report.prompt}",
|
|
155
|
+
"",
|
|
156
|
+
"> The score is a deterministic structural proxy. Review the generated "
|
|
157
|
+
"previews for actual visual quality.",
|
|
158
|
+
"",
|
|
159
|
+
"| Candidate | Status | Score | Time | Slides | Layouts | Visual | "
|
|
160
|
+
"Budget warnings | Previews |",
|
|
161
|
+
"|---|---:|---:|---:|---:|---:|---:|---:|---:|",
|
|
162
|
+
]
|
|
163
|
+
for entry in report.entries:
|
|
164
|
+
metrics = entry.metrics
|
|
165
|
+
candidate_link = (
|
|
166
|
+
f"[{entry.candidate}]({Path(entry.artifact_dir).name}/)"
|
|
167
|
+
if entry.success
|
|
168
|
+
else entry.candidate
|
|
169
|
+
)
|
|
170
|
+
lines.append(
|
|
171
|
+
f"| {candidate_link} | {'OK' if entry.success else 'FAIL'} | "
|
|
172
|
+
f"{entry.score:.1f} | {entry.elapsed_seconds:.1f}s | "
|
|
173
|
+
f"{metrics.slide_count} | {metrics.layout_variety} | "
|
|
174
|
+
f"{metrics.visual_slide_ratio:.0%} | "
|
|
175
|
+
f"{metrics.budget_warning_count} | {metrics.previews_rendered} |"
|
|
176
|
+
)
|
|
177
|
+
if entry.error:
|
|
178
|
+
lines.extend(["", f"- **{entry.candidate} error:** {entry.error}"])
|
|
179
|
+
if report.winner:
|
|
180
|
+
lines.extend(["", f"Structural-score winner: **{report.winner}**"])
|
|
181
|
+
return "\n".join(lines) + "\n"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def run_benchmark(
|
|
185
|
+
prompt: str,
|
|
186
|
+
candidates: List[str],
|
|
187
|
+
out_dir: Path,
|
|
188
|
+
*,
|
|
189
|
+
pages: int | None = None,
|
|
190
|
+
assets: Mapping[str, AssetInput] | None = None,
|
|
191
|
+
asset_refs: List[MediaAssetRef] | None = None,
|
|
192
|
+
) -> BenchmarkReport:
|
|
193
|
+
"""Run the complete pipeline once per candidate and write JSON/Markdown."""
|
|
194
|
+
|
|
195
|
+
root = Path(out_dir)
|
|
196
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
197
|
+
unique_candidates = list(dict.fromkeys(candidates))
|
|
198
|
+
image_generation_available = (
|
|
199
|
+
os.getenv("ODFORGE_IMAGE_BACKEND", "off").lower() == "http"
|
|
200
|
+
and bool(os.getenv("ODFORGE_IMAGE_ENDPOINT", "").strip())
|
|
201
|
+
)
|
|
202
|
+
entries: list[BenchmarkEntry] = []
|
|
203
|
+
|
|
204
|
+
for candidate in unique_candidates:
|
|
205
|
+
started = time.perf_counter()
|
|
206
|
+
candidate_dir = root / _safe_name(candidate)
|
|
207
|
+
candidate_dir.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
metrics = BenchmarkMetrics()
|
|
209
|
+
try:
|
|
210
|
+
outline: Outline = generate_outline(prompt, candidate, pages=pages)
|
|
211
|
+
outline = outline.model_copy(
|
|
212
|
+
update={
|
|
213
|
+
"media_assets": asset_refs or [],
|
|
214
|
+
"image_generation_available": image_generation_available,
|
|
215
|
+
}
|
|
216
|
+
)
|
|
217
|
+
(candidate_dir / "outline.json").write_text(
|
|
218
|
+
outline.model_dump_json(indent=2), encoding="utf-8"
|
|
219
|
+
)
|
|
220
|
+
presentation = generate_slides(outline, candidate)
|
|
221
|
+
(candidate_dir / "presentation.json").write_text(
|
|
222
|
+
presentation.model_dump_json(indent=2), encoding="utf-8"
|
|
223
|
+
)
|
|
224
|
+
odp_path = candidate_dir / "deck.odp"
|
|
225
|
+
render(presentation, odp_path, assets=assets)
|
|
226
|
+
validation = validate_odf(odp_path)
|
|
227
|
+
package_valid = validation.ok
|
|
228
|
+
previews = 0
|
|
229
|
+
try:
|
|
230
|
+
previews = len(
|
|
231
|
+
render_pages(odp_path, candidate_dir / "preview")
|
|
232
|
+
)
|
|
233
|
+
except PreviewUnavailable:
|
|
234
|
+
previews = 0
|
|
235
|
+
except Exception:
|
|
236
|
+
previews = 0
|
|
237
|
+
metrics = measure_presentation(
|
|
238
|
+
presentation,
|
|
239
|
+
assets=assets,
|
|
240
|
+
package_valid=package_valid,
|
|
241
|
+
previews_rendered=previews,
|
|
242
|
+
image_generation_available=image_generation_available,
|
|
243
|
+
)
|
|
244
|
+
score = score_presentation(presentation, metrics)
|
|
245
|
+
success = package_valid
|
|
246
|
+
error = None if success else "ODF validation failed"
|
|
247
|
+
except Exception as exc:
|
|
248
|
+
score = 0.0
|
|
249
|
+
success = False
|
|
250
|
+
error = str(exc)
|
|
251
|
+
|
|
252
|
+
entries.append(
|
|
253
|
+
BenchmarkEntry(
|
|
254
|
+
candidate=candidate,
|
|
255
|
+
success=success,
|
|
256
|
+
score=score,
|
|
257
|
+
elapsed_seconds=round(time.perf_counter() - started, 3),
|
|
258
|
+
metrics=metrics,
|
|
259
|
+
artifact_dir=str(candidate_dir.resolve()),
|
|
260
|
+
error=error,
|
|
261
|
+
)
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
successful = [entry for entry in entries if entry.success]
|
|
265
|
+
winner = (
|
|
266
|
+
max(successful, key=lambda entry: entry.score).candidate
|
|
267
|
+
if successful
|
|
268
|
+
else None
|
|
269
|
+
)
|
|
270
|
+
report = BenchmarkReport(
|
|
271
|
+
prompt=prompt, pages=pages, entries=entries, winner=winner
|
|
272
|
+
)
|
|
273
|
+
(root / "report.json").write_text(
|
|
274
|
+
report.model_dump_json(indent=2), encoding="utf-8"
|
|
275
|
+
)
|
|
276
|
+
(root / "report.md").write_text(_markdown(report), encoding="utf-8")
|
|
277
|
+
return report
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
__all__ = [
|
|
281
|
+
"BenchmarkEntry",
|
|
282
|
+
"BenchmarkMetrics",
|
|
283
|
+
"BenchmarkReport",
|
|
284
|
+
"measure_presentation",
|
|
285
|
+
"run_benchmark",
|
|
286
|
+
"score_presentation",
|
|
287
|
+
]
|
odforge/check.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"""Task 8.2: human-readable ODF check reports.
|
|
2
|
+
|
|
3
|
+
Two entry points, both returning clean markdown (never raising - problems come
|
|
4
|
+
back as report text or ``error:`` strings):
|
|
5
|
+
|
|
6
|
+
- :func:`check_odf` runs the three-gate validator over an ODF file and adds a
|
|
7
|
+
style-reference integrity pass, rendering the outcome as a markdown report.
|
|
8
|
+
- :func:`diff_docx_odt` converts a ``.docx`` to ``.odt`` via LibreOffice and
|
|
9
|
+
reports a heuristic structural comparison of the two.
|
|
10
|
+
|
|
11
|
+
Depends only on the stdlib, lxml and :mod:`odforge.validate`. It never imports
|
|
12
|
+
``render/*`` or the IR: it consumes a :class:`~pathlib.Path` and nothing more.
|
|
13
|
+
The markdown it emits is meant to be read and shared ("ODF 優化建議"), so the
|
|
14
|
+
formatting is kept tidy and deterministic.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import tempfile
|
|
22
|
+
import zipfile
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from lxml import etree
|
|
26
|
+
|
|
27
|
+
from .layoutcheck import LayoutReport, check_layout
|
|
28
|
+
from .validate import find_soffice, run_soffice_convert, validate_odf
|
|
29
|
+
from .xmlsafe import safe_fromstring
|
|
30
|
+
from .zipguard import (
|
|
31
|
+
MAX_XML_MEMBER,
|
|
32
|
+
ArchiveLimitError,
|
|
33
|
+
inspect_archive,
|
|
34
|
+
read_xml_member,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
# Namespaces
|
|
39
|
+
# ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
_TEXT_NS = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"
|
|
42
|
+
_DRAW_NS = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
|
|
43
|
+
_TABLE_NS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
|
|
44
|
+
_STYLE_NS = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"
|
|
45
|
+
|
|
46
|
+
# The style-reference attributes we treat as "uses a named style".
|
|
47
|
+
_STYLE_REF_ATTRS = frozenset(
|
|
48
|
+
{
|
|
49
|
+
f"{{{_TEXT_NS}}}style-name",
|
|
50
|
+
f"{{{_DRAW_NS}}}style-name",
|
|
51
|
+
f"{{{_TABLE_NS}}}style-name",
|
|
52
|
+
}
|
|
53
|
+
)
|
|
54
|
+
# Attribute that declares a named style (in either automatic-styles or styles.xml).
|
|
55
|
+
_STYLE_NAME_ATTR = f"{{{_STYLE_NS}}}name"
|
|
56
|
+
|
|
57
|
+
# Built-in / producer-supplied styles that ODF applications resolve without an
|
|
58
|
+
# explicit definition inside the package. odfdo and LibreOffice routinely
|
|
59
|
+
# reference these, so an unresolved reference to one of them is not a defect.
|
|
60
|
+
STYLE_REFERENCE_WHITELIST = frozenset(
|
|
61
|
+
{
|
|
62
|
+
"Default",
|
|
63
|
+
"Standard",
|
|
64
|
+
"Text_20_body",
|
|
65
|
+
"Heading",
|
|
66
|
+
"Caption",
|
|
67
|
+
"List",
|
|
68
|
+
"Table_20_Contents",
|
|
69
|
+
"Table_20_Heading",
|
|
70
|
+
"Graphics",
|
|
71
|
+
"Frame",
|
|
72
|
+
"OLE",
|
|
73
|
+
"Formula",
|
|
74
|
+
"Illustration",
|
|
75
|
+
"Drawing",
|
|
76
|
+
"Footnote",
|
|
77
|
+
"Endnote",
|
|
78
|
+
"Header",
|
|
79
|
+
"Footer",
|
|
80
|
+
"Index",
|
|
81
|
+
"Contents_20_Heading",
|
|
82
|
+
"Numbering_20_Symbols",
|
|
83
|
+
"Bullet_20_Symbols",
|
|
84
|
+
"List_20_Paragraph",
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
_SOFFICE_TIMEOUT = 120
|
|
89
|
+
|
|
90
|
+
# docx (OOXML wordprocessing) namespaces.
|
|
91
|
+
_W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
# check_odf
|
|
96
|
+
# ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _read_part(path: Path, name: str) -> bytes | None:
|
|
100
|
+
"""Return the bytes of zip member ``name``, or ``None`` if absent."""
|
|
101
|
+
try:
|
|
102
|
+
with zipfile.ZipFile(path) as z:
|
|
103
|
+
infos = inspect_archive(z)
|
|
104
|
+
if name not in {info.filename for info in infos}:
|
|
105
|
+
return None
|
|
106
|
+
return read_xml_member(z, name, max_bytes=MAX_XML_MEMBER)
|
|
107
|
+
except (ArchiveLimitError, zipfile.BadZipFile, OSError):
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _style_reference_issues(path: Path) -> tuple[list[str], str | None]:
|
|
112
|
+
"""Return (undefined-style-references, error-message).
|
|
113
|
+
|
|
114
|
+
Collects every ``text:``/``draw:``/``table:style-name`` reference in
|
|
115
|
+
content.xml and checks each against the styles defined in content.xml's
|
|
116
|
+
automatic-styles plus styles.xml. Whitelisted built-ins are allowed through.
|
|
117
|
+
On a parse/read failure returns ``([], message)``.
|
|
118
|
+
"""
|
|
119
|
+
content = _read_part(path, "content.xml")
|
|
120
|
+
if content is None:
|
|
121
|
+
return [], "content.xml 缺失或無法讀取"
|
|
122
|
+
|
|
123
|
+
defined: set[str] = set()
|
|
124
|
+
refs: set[str] = set()
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
# Untrusted input: hardened parse (no external-entity resolution).
|
|
128
|
+
content_root = safe_fromstring(content)
|
|
129
|
+
except etree.XMLSyntaxError as exc:
|
|
130
|
+
return [], f"content.xml 無法解析:{exc}"
|
|
131
|
+
|
|
132
|
+
for el in content_root.iter():
|
|
133
|
+
name = el.get(_STYLE_NAME_ATTR)
|
|
134
|
+
if name:
|
|
135
|
+
defined.add(name)
|
|
136
|
+
for attr in _STYLE_REF_ATTRS:
|
|
137
|
+
val = el.get(attr)
|
|
138
|
+
if val:
|
|
139
|
+
refs.add(val)
|
|
140
|
+
|
|
141
|
+
styles = _read_part(path, "styles.xml")
|
|
142
|
+
if styles is not None:
|
|
143
|
+
try:
|
|
144
|
+
# Untrusted input: hardened parse (no external-entity resolution).
|
|
145
|
+
styles_root = safe_fromstring(styles)
|
|
146
|
+
except etree.XMLSyntaxError:
|
|
147
|
+
styles_root = None
|
|
148
|
+
if styles_root is not None:
|
|
149
|
+
for el in styles_root.iter():
|
|
150
|
+
name = el.get(_STYLE_NAME_ATTR)
|
|
151
|
+
if name:
|
|
152
|
+
defined.add(name)
|
|
153
|
+
|
|
154
|
+
undefined = sorted(
|
|
155
|
+
ref
|
|
156
|
+
for ref in refs
|
|
157
|
+
if ref not in defined and ref not in STYLE_REFERENCE_WHITELIST
|
|
158
|
+
)
|
|
159
|
+
return undefined, None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _part_listing(path: Path) -> list[str]:
|
|
163
|
+
"""Return ``"- name (N bytes)"`` lines for each package part, or an error."""
|
|
164
|
+
try:
|
|
165
|
+
with zipfile.ZipFile(path) as z:
|
|
166
|
+
return [
|
|
167
|
+
f"- {info.filename} ({info.file_size} bytes)"
|
|
168
|
+
for info in inspect_archive(z)
|
|
169
|
+
]
|
|
170
|
+
except (ArchiveLimitError, zipfile.BadZipFile, OSError) as exc:
|
|
171
|
+
return [f"- (無法列出部件:{exc})"]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def check_odf(path: Path) -> str:
|
|
175
|
+
"""Validate an ODF file and return a markdown check report.
|
|
176
|
+
|
|
177
|
+
Never raises. A missing file yields ``"error: file not found: {path}"``;
|
|
178
|
+
any unexpected exception while building the report becomes an ``error:``
|
|
179
|
+
string (same outer guard as validate.py's gates).
|
|
180
|
+
"""
|
|
181
|
+
return check_odf_verdict(path)[0]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def check_odf_verdict(path: Path) -> tuple[str, bool]:
|
|
185
|
+
"""``(report, failed)`` — the verdict comes from the structured gate results.
|
|
186
|
+
|
|
187
|
+
The report's free text echoes the file name, part names and style names, so
|
|
188
|
+
a caller that greps it for "FAIL" flips its exit code on a perfectly valid
|
|
189
|
+
file that merely *contains* that substring (``q4-FAIL-review.odt``). The
|
|
190
|
+
boolean is derived from the gates themselves and immune to that.
|
|
191
|
+
"""
|
|
192
|
+
path = Path(path)
|
|
193
|
+
if not path.exists():
|
|
194
|
+
return f"error: file not found: {path}", True
|
|
195
|
+
try:
|
|
196
|
+
return _check_odf_report(path)
|
|
197
|
+
except Exception as exc:
|
|
198
|
+
return f"error: check failed: {type(exc).__name__}: {exc}", True
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _check_odf_report(path: Path) -> tuple[str, bool]:
|
|
202
|
+
"""Build the markdown report for an existing file (may raise; guarded)."""
|
|
203
|
+
soffice = find_soffice()
|
|
204
|
+
report = validate_odf(path, with_soffice=soffice is not None)
|
|
205
|
+
|
|
206
|
+
lines: list[str] = [f"# ODF 檢測報告:{path.name}", ""]
|
|
207
|
+
|
|
208
|
+
failed = False
|
|
209
|
+
lines.append("## 驗證結果")
|
|
210
|
+
for name in ("structure", "xml", "soffice"):
|
|
211
|
+
if name not in report.gates:
|
|
212
|
+
continue
|
|
213
|
+
passed, message = report.gates[name]
|
|
214
|
+
failed = failed or not passed
|
|
215
|
+
status = "OK" if passed else "FAIL"
|
|
216
|
+
lines.append(f"- {name}: {status} — {message}")
|
|
217
|
+
lines.append("")
|
|
218
|
+
|
|
219
|
+
lines.append("## 部件清單")
|
|
220
|
+
lines.extend(_part_listing(path))
|
|
221
|
+
lines.append("")
|
|
222
|
+
|
|
223
|
+
lines.append("## 樣式引用")
|
|
224
|
+
undefined, err = _style_reference_issues(path)
|
|
225
|
+
if err is not None:
|
|
226
|
+
lines.append(f"- 略過:{err}")
|
|
227
|
+
elif not undefined:
|
|
228
|
+
lines.append("- OK — 所有樣式引用皆有定義")
|
|
229
|
+
else:
|
|
230
|
+
lines.append("- 發現未定義的樣式引用(引用了但未定義):")
|
|
231
|
+
lines.extend(f" - `{name}`" for name in undefined)
|
|
232
|
+
lines.append("")
|
|
233
|
+
|
|
234
|
+
if path.suffix.lower() != ".ods":
|
|
235
|
+
lines.append("## 跑版")
|
|
236
|
+
lines.extend(layout_lines(check_layout(path, soffice)))
|
|
237
|
+
lines.append("")
|
|
238
|
+
|
|
239
|
+
# Style-reference issues and layout overflow stay informational, like the
|
|
240
|
+
# design gate: only the three format gates decide the verdict.
|
|
241
|
+
return "\n".join(lines).rstrip() + "\n", failed
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def layout_lines(layout: LayoutReport) -> list[str]:
|
|
245
|
+
"""Markdown bullets for a :class:`~odforge.layoutcheck.LayoutReport`."""
|
|
246
|
+
if layout.status == "ok":
|
|
247
|
+
return [f"- OK — {layout.message}"]
|
|
248
|
+
if layout.status != "overflow":
|
|
249
|
+
return [f"- 略過:{layout.message}"]
|
|
250
|
+
return [f"- 發現 {len(layout.findings)} 處跑版:"] + [
|
|
251
|
+
f" - {finding.describe()}" for finding in layout.findings
|
|
252
|
+
]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# ---------------------------------------------------------------------------
|
|
256
|
+
# diff_docx_odt
|
|
257
|
+
# ---------------------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _convert_docx_to_odt(docx: Path, soffice: Path, outdir: Path) -> tuple[Path | None, str]:
|
|
261
|
+
"""Convert ``docx`` to ``.odt`` inside ``outdir`` using an isolated profile.
|
|
262
|
+
|
|
263
|
+
Delegates to :func:`odforge.validate.run_soffice_convert`, the single shared
|
|
264
|
+
soffice entry point (captured output, timeout, private-profile isolation).
|
|
265
|
+
Returns (odt-path, message); the path is ``None`` on failure.
|
|
266
|
+
"""
|
|
267
|
+
try:
|
|
268
|
+
proc = run_soffice_convert(soffice, docx, "odt", outdir, timeout=_SOFFICE_TIMEOUT)
|
|
269
|
+
except subprocess.TimeoutExpired:
|
|
270
|
+
return None, f"soffice timed out after {_SOFFICE_TIMEOUT}s"
|
|
271
|
+
if proc.returncode != 0:
|
|
272
|
+
stderr = (proc.stderr or proc.stdout or "").strip()
|
|
273
|
+
return None, f"soffice exited {proc.returncode}: {stderr[:500]}"
|
|
274
|
+
odt = outdir / (docx.stem + ".odt")
|
|
275
|
+
if not odt.exists():
|
|
276
|
+
stderr = (proc.stderr or proc.stdout or "").strip()
|
|
277
|
+
return None, f"soffice produced no odt: {stderr[:500]}"
|
|
278
|
+
return odt, "ok"
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _count_docx(docx: Path) -> dict[str, int]:
|
|
282
|
+
"""Heuristic element counts from a .docx's word/document.xml."""
|
|
283
|
+
data = _read_part(docx, "word/document.xml")
|
|
284
|
+
if data is None:
|
|
285
|
+
raise ValueError("word/document.xml 缺失")
|
|
286
|
+
# Untrusted input: hardened parse (no external-entity resolution).
|
|
287
|
+
root = safe_fromstring(data)
|
|
288
|
+
|
|
289
|
+
paragraphs = len(root.findall(f".//{{{_W_NS}}}p"))
|
|
290
|
+
tables = len(root.findall(f".//{{{_W_NS}}}tbl"))
|
|
291
|
+
# Images: prefer drawings, fall back to legacy VML pictures.
|
|
292
|
+
images = len(root.findall(f".//{{{_W_NS}}}drawing")) or len(
|
|
293
|
+
root.findall(f".//{{{_W_NS}}}pict")
|
|
294
|
+
)
|
|
295
|
+
headings = 0
|
|
296
|
+
for pstyle in root.iter(f"{{{_W_NS}}}pStyle"):
|
|
297
|
+
val = pstyle.get(f"{{{_W_NS}}}val", "")
|
|
298
|
+
if val.startswith("Heading"):
|
|
299
|
+
headings += 1
|
|
300
|
+
return {
|
|
301
|
+
"paragraph": paragraphs,
|
|
302
|
+
"table": tables,
|
|
303
|
+
"image": images,
|
|
304
|
+
"heading": headings,
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _count_odt(odt: Path) -> dict[str, int]:
|
|
309
|
+
"""Heuristic element counts from an .odt's content.xml."""
|
|
310
|
+
data = _read_part(odt, "content.xml")
|
|
311
|
+
if data is None:
|
|
312
|
+
raise ValueError("content.xml 缺失")
|
|
313
|
+
# Untrusted input: hardened parse (no external-entity resolution).
|
|
314
|
+
root = safe_fromstring(data)
|
|
315
|
+
return {
|
|
316
|
+
"paragraph": len(root.findall(f".//{{{_TEXT_NS}}}p")),
|
|
317
|
+
"table": len(root.findall(f".//{{{_TABLE_NS}}}table")),
|
|
318
|
+
"image": len(root.findall(f".//{{{_DRAW_NS}}}image")),
|
|
319
|
+
"heading": len(root.findall(f".//{{{_TEXT_NS}}}h")),
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
# Display label per element key.
|
|
324
|
+
_ELEMENT_LABELS = (
|
|
325
|
+
("paragraph", "段落 (paragraph)"),
|
|
326
|
+
("table", "表格 (table)"),
|
|
327
|
+
("image", "圖片 (image)"),
|
|
328
|
+
("heading", "標題 (heading)"),
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def diff_docx_odt(docx: Path) -> str:
|
|
333
|
+
"""Convert ``docx`` to ``.odt`` and return a heuristic comparison report.
|
|
334
|
+
|
|
335
|
+
Never raises. Without LibreOffice, returns an explanatory string. A failed
|
|
336
|
+
conversion yields ``"error: conversion failed: {摘要}"``; any unexpected
|
|
337
|
+
exception (e.g. a stale soffice path raising ``FileNotFoundError`` inside
|
|
338
|
+
``subprocess.run``) is likewise returned as an ``error:`` string.
|
|
339
|
+
"""
|
|
340
|
+
return diff_docx_odt_verdict(docx)[0]
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def diff_docx_odt_verdict(docx: Path) -> tuple[str, bool]:
|
|
344
|
+
"""``(report, failed)`` — failed only when the comparison could not run.
|
|
345
|
+
|
|
346
|
+
Count mismatches are heuristic observations, not failures (they never
|
|
347
|
+
tripped the exit code before either); ``error:`` reports are.
|
|
348
|
+
"""
|
|
349
|
+
docx = Path(docx)
|
|
350
|
+
soffice = find_soffice()
|
|
351
|
+
if soffice is None:
|
|
352
|
+
return (
|
|
353
|
+
"error: 此比對需要 LibreOffice(soffice)把 .docx 轉成 .odt,"
|
|
354
|
+
"但在本機找不到 soffice。請安裝 LibreOffice 後再試。"
|
|
355
|
+
), True
|
|
356
|
+
|
|
357
|
+
if not docx.exists():
|
|
358
|
+
return f"error: file not found: {docx}", True
|
|
359
|
+
|
|
360
|
+
try:
|
|
361
|
+
report = _diff_report(docx, soffice)
|
|
362
|
+
except Exception as exc:
|
|
363
|
+
return f"error: conversion failed: {type(exc).__name__}: {exc}", True
|
|
364
|
+
return report, report.startswith("error:")
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _diff_report(docx: Path, soffice: Path) -> str:
|
|
368
|
+
"""Convert, count and format the comparison (may raise; guarded)."""
|
|
369
|
+
outdir = Path(tempfile.mkdtemp(prefix="odforge-check-diff-"))
|
|
370
|
+
try:
|
|
371
|
+
odt, message = _convert_docx_to_odt(docx, soffice, outdir)
|
|
372
|
+
if odt is None:
|
|
373
|
+
return f"error: conversion failed: {message}"
|
|
374
|
+
|
|
375
|
+
try:
|
|
376
|
+
docx_counts = _count_docx(docx)
|
|
377
|
+
odt_counts = _count_odt(odt)
|
|
378
|
+
except (etree.XMLSyntaxError, ValueError) as exc:
|
|
379
|
+
return f"error: conversion failed: 無法解析結構:{exc}"
|
|
380
|
+
# Counts say whether elements survived the conversion; this says whether
|
|
381
|
+
# they still fit on the page once LibreOffice laid them out.
|
|
382
|
+
layout = check_layout(odt, soffice)
|
|
383
|
+
finally:
|
|
384
|
+
shutil.rmtree(outdir, ignore_errors=True)
|
|
385
|
+
|
|
386
|
+
lines: list[str] = [
|
|
387
|
+
f"# DOCX/ODT 結構比對報告:{docx.name}",
|
|
388
|
+
"",
|
|
389
|
+
"> heuristic structural comparison(啟發式結構比對):以段落/表格/圖片/標題"
|
|
390
|
+
"的計數比較轉檔前後的文件結構,數量差異僅供參考。",
|
|
391
|
+
"",
|
|
392
|
+
"| 元素 | DOCX | ODT |",
|
|
393
|
+
"| --- | ---: | ---: |",
|
|
394
|
+
]
|
|
395
|
+
for key, label in _ELEMENT_LABELS:
|
|
396
|
+
lines.append(f"| {label} | {docx_counts[key]} | {odt_counts[key]} |")
|
|
397
|
+
lines.append("")
|
|
398
|
+
|
|
399
|
+
lines.append("## 差異說明")
|
|
400
|
+
mismatches = [
|
|
401
|
+
(label, docx_counts[key], odt_counts[key])
|
|
402
|
+
for key, label in _ELEMENT_LABELS
|
|
403
|
+
if docx_counts[key] != odt_counts[key]
|
|
404
|
+
]
|
|
405
|
+
if not mismatches:
|
|
406
|
+
lines.append("- OK — 各類元素數量一致,轉檔結構相符。")
|
|
407
|
+
else:
|
|
408
|
+
for label, dv, ov in mismatches:
|
|
409
|
+
lines.append(f"- {label}:DOCX={dv} 對 ODT={ov},數量不一致。")
|
|
410
|
+
lines.append("")
|
|
411
|
+
|
|
412
|
+
lines.append("## 跑版(轉出的 .odt)")
|
|
413
|
+
lines.extend(layout_lines(layout))
|
|
414
|
+
lines.append("")
|
|
415
|
+
|
|
416
|
+
return "\n".join(lines).rstrip() + "\n"
|