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.
Files changed (66) hide show
  1. odforge/__init__.py +1 -0
  2. odforge/benchmark.py +287 -0
  3. odforge/check.py +416 -0
  4. odforge/cli.py +1027 -0
  5. odforge/components.py +270 -0
  6. odforge/critic.py +1260 -0
  7. odforge/docfonts.py +104 -0
  8. odforge/editor_api.py +33 -0
  9. odforge/editor_launch.py +134 -0
  10. odforge/editor_routes.py +131 -0
  11. odforge/extract.py +478 -0
  12. odforge/feedback.py +86 -0
  13. odforge/fontembed.py +166 -0
  14. odforge/ir.py +1181 -0
  15. odforge/layoutcheck.py +602 -0
  16. odforge/llm.py +1865 -0
  17. odforge/localguard.py +42 -0
  18. odforge/mcp_server.py +552 -0
  19. odforge/media.py +352 -0
  20. odforge/odpedit.py +1219 -0
  21. odforge/package.py +114 -0
  22. odforge/pagefacts.py +388 -0
  23. odforge/preview.py +104 -0
  24. odforge/references.py +153 -0
  25. odforge/render/__init__.py +40 -0
  26. odforge/render/odp.py +5687 -0
  27. odforge/render/ods.py +155 -0
  28. odforge/render/odt.py +223 -0
  29. odforge/scene.py +657 -0
  30. odforge/setup_agents.py +274 -0
  31. odforge/skills/odforge-design/SKILL.md +298 -0
  32. odforge/skills/odforge-design/themes/academic.md +52 -0
  33. odforge/skills/odforge-design/themes/clay.md +53 -0
  34. odforge/skills/odforge-design/themes/color-system.md +59 -0
  35. odforge/skills/odforge-design/themes/crimson.md +53 -0
  36. odforge/skills/odforge-design/themes/dark.md +53 -0
  37. odforge/skills/odforge-design/themes/forest.md +54 -0
  38. odforge/skills/odforge-design/themes/gold.md +53 -0
  39. odforge/skills/odforge-design/themes/minimal.md +53 -0
  40. odforge/skills/odforge-design/themes/navy.md +56 -0
  41. odforge/skills/odforge-design/themes/plum.md +53 -0
  42. odforge/skills/odforge-design/themes/sky.md +53 -0
  43. odforge/skills/odforge-design/themes/slate.md +53 -0
  44. odforge/skills/odforge-design/themes/teal.md +53 -0
  45. odforge/skills/odforge-design/themes/violet.md +56 -0
  46. odforge/templates.py +250 -0
  47. odforge/textmetrics.py +616 -0
  48. odforge/textutil.py +24 -0
  49. odforge/themes.py +886 -0
  50. odforge/validate.py +403 -0
  51. odforge/watch.py +266 -0
  52. odforge/webapi.py +2617 -0
  53. odforge/webui/assets/editor-CjpYXM1a.css +1 -0
  54. odforge/webui/assets/editor-DPToJGio.js +3 -0
  55. odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
  56. odforge/webui/assets/main-BLOs7Hnk.js +7 -0
  57. odforge/webui/assets/main-D21yFVE6.css +1 -0
  58. odforge/webui/editor.html +14 -0
  59. odforge/webui/index.html +25 -0
  60. odforge/xmlsafe.py +46 -0
  61. odforge/zipguard.py +91 -0
  62. odforge-0.3.0.dist-info/METADATA +95 -0
  63. odforge-0.3.0.dist-info/RECORD +66 -0
  64. odforge-0.3.0.dist-info/WHEEL +4 -0
  65. odforge-0.3.0.dist-info/entry_points.txt +3 -0
  66. odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/docfonts.py ADDED
@@ -0,0 +1,104 @@
1
+ """Keep an edited document's embedded fonts in step with its text.
2
+
3
+ ODForge embeds *subsets* of its fonts — only the characters a deck uses — so a
4
+ deck stays small and still looks right on a machine without the fonts. Editing
5
+ breaks that bargain: type a character the deck never had and the embedded face
6
+ has no glyph for it, so LibreOffice (and the browser) draw that character in
7
+ some fallback font. This module notices missing glyphs and re-subsets from the
8
+ original font files when this machine has them.
9
+
10
+ Everything here is best effort. Without fontTools or the source files nothing is
11
+ re-embedded and the document is saved exactly as edited.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import io
18
+ from functools import lru_cache
19
+ from typing import Dict, Iterable, List, Optional, Set
20
+
21
+ from lxml import etree
22
+
23
+ from .fontembed import _ALWAYS, embed_fonts, find_font
24
+ from .scene import q
25
+
26
+ # The families the editor offers even when a document has not used them yet:
27
+ # they can be embedded (when installed here), so the result travels.
28
+ OFFERED = ("Noto Sans TC", "Noto Serif TC")
29
+
30
+
31
+ def _family_of(face: etree._Element) -> str:
32
+ return face.get(q("svg", "font-family"), face.get(q("style", "name"), "")).strip("'\"")
33
+
34
+
35
+ def font_faces(roots: Iterable[etree._Element]) -> List[etree._Element]:
36
+ return [face for root in roots for face in root.iter(q("style", "font-face"))]
37
+
38
+
39
+ def referenced_families(roots: List[etree._Element]) -> Set[str]:
40
+ """Families some style actually names (not just declares)."""
41
+ names: Set[str] = set()
42
+ for root in roots:
43
+ for props in root.iter(q("style", "text-properties")):
44
+ for attr in ("font-name", "font-name-asian", "font-name-complex"):
45
+ value = props.get(q("style", attr))
46
+ if value:
47
+ names.add(value)
48
+ by_name = {face.get(q("style", "name")): _family_of(face) for face in font_faces(roots)}
49
+ return {by_name.get(name, name) for name in names}
50
+
51
+
52
+ def choices(roots: List[etree._Element]) -> List[Dict[str, object]]:
53
+ """Fonts the editor lets a person pick, with whether they can be embedded here."""
54
+ families = [_family_of(face) for face in font_faces(roots)]
55
+ for family in OFFERED:
56
+ if find_font(family, False) is not None:
57
+ families.append(family)
58
+ seen: Dict[str, Dict[str, object]] = {}
59
+ for family in families:
60
+ if family and family not in seen:
61
+ seen[family] = {
62
+ "family": family,
63
+ "embeddable": find_font(family, False) is not None,
64
+ }
65
+ return list(seen.values())
66
+
67
+
68
+ def document_text(roots: List[etree._Element]) -> str:
69
+ """Text drawn in the document's fonts — comments are not (the viewer draws them)."""
70
+ annotation = q("officeooo", "annotation")
71
+ parts: List[str] = []
72
+ for root in roots:
73
+ for el in root.iter(q("text", "p"), q("text", "h")):
74
+ if any(a.tag == annotation for a in el.iterancestors()):
75
+ continue
76
+ parts.append("".join(el.itertext()))
77
+ return "".join(parts)
78
+
79
+
80
+ @lru_cache(maxsize=64)
81
+ def _coverage(digest: str, data: bytes) -> Optional[frozenset]:
82
+ try:
83
+ from fontTools.ttLib import TTFont
84
+ except ImportError:
85
+ return None
86
+ try:
87
+ cmap = TTFont(io.BytesIO(data), lazy=True)["cmap"].getBestCmap() or {}
88
+ except Exception:
89
+ return None
90
+ return frozenset(cmap)
91
+
92
+
93
+ def coverage(data: bytes) -> Optional[frozenset]:
94
+ """Code points an embedded font has glyphs for (``None`` when unreadable)."""
95
+ return _coverage(hashlib.sha1(data).hexdigest(), data)
96
+
97
+
98
+ def needed_chars(text: str) -> Set[int]:
99
+ return {ord(c) for c in set(text) | set(_ALWAYS) if not c.isspace() or c == " "}
100
+
101
+
102
+ def rebuild(family: str, text: str):
103
+ """Fresh subsets (regular + bold) of ``family`` covering ``text``, or ``[]``."""
104
+ return embed_fonts({family}, text)
odforge/editor_api.py ADDED
@@ -0,0 +1,33 @@
1
+ """``odforge edit deck.odp``: one process, one file, the editor page.
2
+
3
+ The routes themselves live in :mod:`odforge.editor_routes`, shared with the web
4
+ console (``odforge serve``), which mounts them per generated deck.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from fastapi import FastAPI
12
+ from fastapi.responses import RedirectResponse
13
+ from fastapi.staticfiles import StaticFiles
14
+
15
+ from .editor_routes import add_editor_routes
16
+ from .odpedit import Document
17
+ from .webapi import frontend_dist
18
+
19
+
20
+ def create_editor_app(path: Path) -> FastAPI:
21
+ document = Document(Path(path))
22
+ app = FastAPI(title="ODForge Editor")
23
+ app.state.document = document
24
+ add_editor_routes(app, "/api/doc", lambda _doc_id: document)
25
+
26
+ @app.get("/")
27
+ def root() -> RedirectResponse:
28
+ return RedirectResponse("/editor.html")
29
+
30
+ dist = frontend_dist()
31
+ if dist is not None:
32
+ app.mount("/", StaticFiles(directory=dist, html=True), name="frontend")
33
+ return app
@@ -0,0 +1,134 @@
1
+ """Open the web editor for a file, from wherever ODForge is running (MCP included).
2
+
3
+ When an assistant makes a deck through MCP, the person should land in the
4
+ browser looking at it — not be told to run a command. :func:`ensure_editor`
5
+ starts ``odforge edit <file>`` as a detached background process (it opens the
6
+ browser itself), or reuses the one already serving that file.
7
+
8
+ Running editors are remembered in ``~/.odforge/editors.json`` as
9
+ ``{absolute path: {port, pid}}``; a stale entry (process gone, port silent) is
10
+ simply replaced.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import socket
18
+ import subprocess
19
+ import sys
20
+ import time
21
+ import urllib.request
22
+ import webbrowser
23
+ from pathlib import Path
24
+ from typing import Dict, Optional
25
+
26
+ STATE_DIR = Path.home() / ".odforge"
27
+ START_TIMEOUT = 15.0
28
+
29
+
30
+ def disabled() -> bool:
31
+ """``ODFORGE_NO_EDITOR=1`` turns auto-opening off (tests, CI, headless hosts)."""
32
+ return os.environ.get("ODFORGE_NO_EDITOR", "").strip() not in ("", "0")
33
+
34
+
35
+ def _registry_path() -> Path:
36
+ return STATE_DIR / "editors.json"
37
+
38
+
39
+ def _load() -> Dict[str, Dict[str, int]]:
40
+ try:
41
+ return json.loads(_registry_path().read_text(encoding="utf-8"))
42
+ except (OSError, ValueError):
43
+ return {}
44
+
45
+
46
+ def _save(data: Dict[str, Dict[str, int]]) -> None:
47
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
48
+ _registry_path().write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
49
+
50
+
51
+ def _serving(port: int, name: str) -> bool:
52
+ try:
53
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/api/doc", timeout=1.5) as response:
54
+ return json.loads(response.read()).get("name") == name
55
+ except Exception:
56
+ return False
57
+
58
+
59
+ def _free_port() -> int:
60
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
61
+ sock.bind(("127.0.0.1", 0))
62
+ return sock.getsockname()[1]
63
+
64
+
65
+ def _command() -> list[str]:
66
+ script = Path(sys.executable).parent / "odforge"
67
+ if script.exists():
68
+ return [str(script)]
69
+ return [sys.executable, "-c", "from odforge.cli import app; app()"]
70
+
71
+
72
+ def url_for(port: int) -> str:
73
+ return f"http://127.0.0.1:{port}/editor.html"
74
+
75
+
76
+ def ensure_editor(path: Path, open_browser: bool = True) -> str:
77
+ """The editor URL for ``path``, starting an editor when none is serving it.
78
+
79
+ Raises ``RuntimeError`` with a readable reason when it cannot start one.
80
+ """
81
+ path = Path(path).resolve()
82
+ registry = _load()
83
+ entry = registry.get(str(path))
84
+ if entry and _serving(int(entry["port"]), path.name):
85
+ url = url_for(int(entry["port"]))
86
+ if open_browser:
87
+ webbrowser.open(url)
88
+ return url
89
+
90
+ from .webapi import frontend_dist
91
+
92
+ if frontend_dist() is None:
93
+ raise RuntimeError("找不到建置好的前端(在 odforge/ 下執行 npm --prefix web run build)")
94
+ port = _free_port()
95
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
96
+ log = open(STATE_DIR / f"editor-{port}.log", "w", encoding="utf-8") # noqa: SIM115
97
+ args = [*_command(), "edit", str(path), "--port", str(port)]
98
+ if not open_browser:
99
+ args.append("--no-open")
100
+ process = subprocess.Popen(
101
+ args,
102
+ # Under an MCP host stdin/stdout are the protocol pipe: the child must
103
+ # never inherit them, or it corrupts (or blocks on) the stream.
104
+ stdin=subprocess.DEVNULL,
105
+ stdout=log,
106
+ stderr=subprocess.STDOUT,
107
+ start_new_session=True,
108
+ cwd=str(path.parent),
109
+ )
110
+ deadline = time.monotonic() + START_TIMEOUT
111
+ while time.monotonic() < deadline:
112
+ if process.poll() is not None:
113
+ raise RuntimeError(f"編輯器啟動失敗,詳見 {STATE_DIR / f'editor-{port}.log'}")
114
+ if _serving(port, path.name):
115
+ registry[str(path)] = {"port": port, "pid": process.pid}
116
+ _save(registry)
117
+ return url_for(port)
118
+ time.sleep(0.25)
119
+ raise RuntimeError("編輯器沒有在時間內啟動")
120
+
121
+
122
+ def editor_note(path: Path) -> Optional[str]:
123
+ """A line for MCP results: where the deck opened, or why it did not."""
124
+ if disabled():
125
+ return None
126
+ try:
127
+ url = ensure_editor(path)
128
+ except Exception as exc:
129
+ return f"(沒有自動打開網頁編輯器:{exc})"
130
+ return (
131
+ f"已在使用者的瀏覽器用 ODForge 網頁編輯器打開這份簡報:{url}\n"
132
+ "使用者可以在網頁上瀏覽、拖動、改字,並用「留言」點出要改的地方、按「交給 AI 修改」。"
133
+ f'下一步:呼叫 wait_for_feedback("{Path(path).resolve()}") 等他在網頁上的回饋。'
134
+ )
@@ -0,0 +1,131 @@
1
+ """Editor HTTP routes, mountable on any app (``odforge edit`` or ``odforge serve``).
2
+
3
+ The browser asks for the scene, sends operations, and gets the new scene back;
4
+ every accepted operation is already on disk when the response arrives. Fonts
5
+ and pictures embedded in the package are served so the browser draws text in
6
+ the document's own typefaces.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Dict, List
13
+
14
+ from fastapi import FastAPI, HTTPException
15
+ from fastapi.responses import FileResponse, Response
16
+ from pydantic import BaseModel, Field
17
+
18
+ from .odpedit import Document, EditError
19
+
20
+ # Package members the browser may fetch: what the scene references, nothing else.
21
+ _SERVABLE_PREFIXES = ("Fonts/", "Pictures/", "media/")
22
+ # …and only as these types. HTML, XML and scripts never get an active type.
23
+ _SERVABLE_TYPES = {
24
+ ".otf": "font/otf",
25
+ ".ttf": "font/ttf",
26
+ ".woff": "font/woff",
27
+ ".woff2": "font/woff2",
28
+ ".png": "image/png",
29
+ ".jpg": "image/jpeg",
30
+ ".jpeg": "image/jpeg",
31
+ ".gif": "image/gif",
32
+ ".svg": "image/svg+xml",
33
+ }
34
+
35
+
36
+ class OpsBody(BaseModel):
37
+ ops: List[Dict[str, Any]] = Field(min_length=1, max_length=500)
38
+
39
+
40
+ class ClipBody(BaseModel):
41
+ ids: List[str] = Field(min_length=1, max_length=500)
42
+
43
+
44
+ def add_editor_routes(app: FastAPI, base: str, resolve: Callable[[str], Document]) -> None:
45
+ """Register the editor API under ``base``.
46
+
47
+ ``base`` may hold a ``{doc_id}`` segment (``/api/docs/{doc_id}``) for a server
48
+ that edits many documents; without one, ``resolve`` is called with ``""``.
49
+ ``resolve`` raises ``HTTPException`` for a document that cannot be edited.
50
+ """
51
+
52
+ def guarded(call: Callable[[], Any]) -> Any:
53
+ try:
54
+ return call()
55
+ except EditError as exc:
56
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
57
+
58
+ @app.get(base)
59
+ def get_doc(doc_id: str = "") -> Dict[str, Any]:
60
+ return resolve(doc_id).state()
61
+
62
+ @app.get(f"{base}/version")
63
+ def get_version(doc_id: str = "") -> Dict[str, Any]:
64
+ # Polled by the page: a changed number means someone else saved the file.
65
+ return {"version": resolve(doc_id).poll()}
66
+
67
+ @app.post(f"{base}/ops")
68
+ def post_ops(body: OpsBody, doc_id: str = "") -> Dict[str, Any]:
69
+ document = resolve(doc_id)
70
+ return guarded(lambda: document.apply(body.ops))
71
+
72
+ @app.post(f"{base}/clip")
73
+ def post_clip(body: ClipBody, doc_id: str = "") -> Dict[str, Any]:
74
+ document = resolve(doc_id)
75
+ return guarded(lambda: {"items": document.clip(body.ids)})
76
+
77
+ @app.post(f"{base}/undo")
78
+ def post_undo(doc_id: str = "") -> Dict[str, Any]:
79
+ return resolve(doc_id).undo()
80
+
81
+ @app.post(f"{base}/redo")
82
+ def post_redo(doc_id: str = "") -> Dict[str, Any]:
83
+ return resolve(doc_id).redo()
84
+
85
+ @app.get(base + "/file/{member:path}")
86
+ def get_member(member: str, doc_id: str = "") -> Response:
87
+ if not member.startswith(_SERVABLE_PREFIXES):
88
+ raise HTTPException(status_code=404, detail="not found")
89
+ data = resolve(doc_id).member(member)
90
+ if data is None:
91
+ raise HTTPException(status_code=404, detail="not found")
92
+ kind = _SERVABLE_TYPES.get(Path(member).suffix.lower(), "application/octet-stream")
93
+ # The package is untrusted input: whatever it holds is served as inert data.
94
+ # SVG only ever reaches the page through <img>, where scripts never run; the
95
+ # sandbox policy covers someone opening the URL directly.
96
+ return Response(
97
+ data,
98
+ media_type=kind,
99
+ headers={
100
+ "Cache-Control": "private, max-age=3600",
101
+ "X-Content-Type-Options": "nosniff",
102
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
103
+ },
104
+ )
105
+
106
+ @app.get(f"{base}/export")
107
+ def export(doc_id: str = "") -> FileResponse:
108
+ """The file as it is now, after checking it is a well-formed ODF package."""
109
+ from .validate import validate_odf
110
+
111
+ document = resolve(doc_id)
112
+ document.poll()
113
+ report = validate_odf(document.path)
114
+ if not report.ok:
115
+ problems = "; ".join(m for ok, m in report.gates.values() if not ok)
116
+ raise HTTPException(status_code=500, detail=f"檔案沒有通過格式檢查,未匯出:{problems}")
117
+ return FileResponse(
118
+ document.path,
119
+ media_type="application/vnd.oasis.opendocument.presentation",
120
+ filename=document.path.name,
121
+ headers={"Cache-Control": "no-store"},
122
+ )
123
+
124
+ @app.get(f"{base}/download")
125
+ def download(doc_id: str = "") -> FileResponse:
126
+ document = resolve(doc_id)
127
+ return FileResponse(
128
+ document.path,
129
+ media_type="application/vnd.oasis.opendocument.presentation",
130
+ filename=document.path.name,
131
+ )