draftboard 0.0.1__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 (51) hide show
  1. draftboard/__init__.py +41 -0
  2. draftboard/__main__.py +225 -0
  3. draftboard/agent.py +104 -0
  4. draftboard/api.py +901 -0
  5. draftboard/measure.py +225 -0
  6. draftboard/models.py +407 -0
  7. draftboard/pptx_export.py +479 -0
  8. draftboard/render.py +80 -0
  9. draftboard/static/404.html +1 -0
  10. draftboard/static/__next.__PAGE__.txt +27 -0
  11. draftboard/static/__next._full.txt +22 -0
  12. draftboard/static/__next._tree.txt +3 -0
  13. draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_buildManifest.js +11 -0
  14. draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_clientMiddlewareManifest.js +1 -0
  15. draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_ssgManifest.js +1 -0
  16. draftboard/static/_next/static/chunks/0cz1d0mv5g_q7.js +1 -0
  17. draftboard/static/_next/static/chunks/0oheds1fsp9jx.js +1 -0
  18. draftboard/static/_next/static/chunks/1vsonpqt4u2rw.js +1 -0
  19. draftboard/static/_next/static/chunks/24xul4hawiu8l.js +1 -0
  20. draftboard/static/_next/static/chunks/2r7iycbt4s29o.js +22 -0
  21. draftboard/static/_next/static/chunks/2utugak-w5oge.css +1 -0
  22. draftboard/static/_next/static/chunks/39_j1bdzreq0m.js +1 -0
  23. draftboard/static/_next/static/chunks/3qfy96eoyh-ek.js +1 -0
  24. draftboard/static/_next/static/chunks/3u8gxd9uztfzl.js +4 -0
  25. draftboard/static/_next/static/chunks/3v_59l1qr_8dp.js +31 -0
  26. draftboard/static/_next/static/chunks/turbopack-2u1d16houkiyo.js +1 -0
  27. draftboard/static/_not-found/__next._full.txt +20 -0
  28. draftboard/static/_not-found/__next._not-found/__PAGE__.txt +26 -0
  29. draftboard/static/_not-found/__next._tree.txt +4 -0
  30. draftboard/static/_not-found.html +1 -0
  31. draftboard/static/_not-found.txt +20 -0
  32. draftboard/static/index.html +1 -0
  33. draftboard/static/index.txt +22 -0
  34. draftboard/static/p/__placeholder__/__next._full.txt +27 -0
  35. draftboard/static/p/__placeholder__/__next._tree.txt +5 -0
  36. draftboard/static/p/__placeholder__/__next.p/$d$id/__PAGE__.txt +34 -0
  37. draftboard/static/p/__placeholder__/preview/__next._full.txt +27 -0
  38. draftboard/static/p/__placeholder__/preview/__next._tree.txt +6 -0
  39. draftboard/static/p/__placeholder__/preview/__next.p/$d$id/preview/__PAGE__.txt +35 -0
  40. draftboard/static/p/__placeholder__/preview.html +1 -0
  41. draftboard/static/p/__placeholder__/preview.txt +27 -0
  42. draftboard/static/p/__placeholder__.html +1 -0
  43. draftboard/static/p/__placeholder__.txt +27 -0
  44. draftboard/storage.py +183 -0
  45. draftboard/tasks.py +464 -0
  46. draftboard/themes.py +213 -0
  47. draftboard/tools.py +723 -0
  48. draftboard-0.0.1.dist-info/METADATA +16 -0
  49. draftboard-0.0.1.dist-info/RECORD +51 -0
  50. draftboard-0.0.1.dist-info/WHEEL +4 -0
  51. draftboard-0.0.1.dist-info/entry_points.txt +2 -0
draftboard/tasks.py ADDED
@@ -0,0 +1,464 @@
1
+ """
2
+ Persisted background tasks for the Draftboard API.
3
+
4
+ Task records live in {project}/tasks/{task_id}.json so progress survives
5
+ page reloads and service restarts. Work runs in a daemon thread; the
6
+ pipeline functions themselves are the same ones the CLI and agent use.
7
+ """
8
+
9
+ import asyncio
10
+ import inspect
11
+ import json
12
+ import os
13
+ import pathlib
14
+ import re
15
+ import threading
16
+ import uuid
17
+ from datetime import datetime, timezone
18
+ from typing import Callable, Optional
19
+
20
+ from draftboard.models import TaskRecord, TaskStatus
21
+ from draftboard.storage import ProjectStorage, load_json
22
+
23
+ _submit_lock = threading.Lock()
24
+
25
+
26
+ def _now() -> str:
27
+ return datetime.now(timezone.utc).isoformat()
28
+
29
+
30
+ def _tasks_dir(root: pathlib.Path, project_id: str) -> pathlib.Path:
31
+ return root / project_id / "tasks"
32
+
33
+
34
+ def _save(root: pathlib.Path, record: TaskRecord) -> None:
35
+ storage = ProjectStorage(record.project_id, storage_root=root)
36
+ record.updated_at = _now()
37
+ storage.save_task(record.task_id, record.model_dump())
38
+
39
+
40
+ def load_task(root: pathlib.Path, project_id: str, task_id: str) -> TaskRecord:
41
+ path = _tasks_dir(root, project_id) / f"{task_id}.json"
42
+ if not path.exists():
43
+ raise KeyError(f"Task '{task_id}' not found in project '{project_id}'")
44
+ return TaskRecord.model_validate(load_json(path))
45
+
46
+
47
+ def list_tasks(root: pathlib.Path, project_id: str) -> list[TaskRecord]:
48
+ tasks_dir = _tasks_dir(root, project_id)
49
+ if not tasks_dir.exists():
50
+ return []
51
+ records = [
52
+ TaskRecord.model_validate(load_json(p))
53
+ for p in tasks_dir.glob("*.json")
54
+ ]
55
+ return sorted(records, key=lambda r: r.created_at)
56
+
57
+
58
+ def sweep_interrupted(root: pathlib.Path) -> int:
59
+ """Mark queued/running tasks as failed after a service restart.
60
+
61
+ A task thread cannot survive a restart; leaving its record as 'running'
62
+ would show '生成中' forever. Saved intermediates remain usable.
63
+ """
64
+ count = 0
65
+ if not root.exists():
66
+ return count
67
+ for proj_dir in root.iterdir():
68
+ if not proj_dir.is_dir():
69
+ continue
70
+ for record in list_tasks(root, proj_dir.name):
71
+ if record.status in (TaskStatus.QUEUED, TaskStatus.RUNNING):
72
+ record.status = TaskStatus.FAILED
73
+ record.error = (
74
+ "服务重启,任务已中断。已保存的大纲和幻灯片仍然有效,可重新提交。"
75
+ )
76
+ _save(root, record)
77
+ count += 1
78
+ return count
79
+
80
+
81
+ class TaskConflictError(Exception):
82
+ """A task of the same kind is already queued or running."""
83
+
84
+
85
+ class TaskContext:
86
+ """Lets running work report real steps and save partial results."""
87
+
88
+ def __init__(self, root: pathlib.Path, record: TaskRecord) -> None:
89
+ self._root = root
90
+ self.record = record
91
+
92
+ def set_step(self, step: str) -> None:
93
+ self.record.step = step
94
+ _save(self._root, self.record)
95
+
96
+ def set_result(self, result: dict) -> None:
97
+ self.record.result = result
98
+ _save(self._root, self.record)
99
+
100
+
101
+ def _execute(
102
+ root: pathlib.Path,
103
+ project_id: str,
104
+ task_id: str,
105
+ work: Callable[[TaskContext], dict],
106
+ ) -> None:
107
+ record = load_task(root, project_id, task_id)
108
+ record.status = TaskStatus.RUNNING
109
+ _save(root, record)
110
+ ctx = TaskContext(root, record)
111
+ try:
112
+ result = work(ctx)
113
+ record.result = result
114
+ record.status = TaskStatus.SUCCEEDED
115
+ record.step = "完成"
116
+ _save(root, record)
117
+ except Exception as e:
118
+ record.status = TaskStatus.FAILED
119
+ record.error = str(e)
120
+ _save(root, record)
121
+
122
+
123
+ def submit(
124
+ root: pathlib.Path,
125
+ project_id: str,
126
+ kind: str,
127
+ work: Callable[[TaskContext], dict],
128
+ ) -> TaskRecord:
129
+ """Create a persisted task and run it in a background thread.
130
+
131
+ Raises TaskConflictError if a task of the same kind is already active,
132
+ so duplicate clicks never start two generations.
133
+ """
134
+ with _submit_lock:
135
+ for record in list_tasks(root, project_id):
136
+ if record.kind == kind and record.status in (
137
+ TaskStatus.QUEUED,
138
+ TaskStatus.RUNNING,
139
+ ):
140
+ raise TaskConflictError(
141
+ f"已有一个{kind}任务在进行中({record.task_id}),请等待它完成。"
142
+ )
143
+ record = TaskRecord(
144
+ task_id=f"task-{uuid.uuid4().hex[:8]}",
145
+ project_id=project_id,
146
+ kind=kind,
147
+ created_at=_now(),
148
+ updated_at=_now(),
149
+ )
150
+ _save(root, record)
151
+ threading.Thread(
152
+ target=_execute,
153
+ args=(root, project_id, record.task_id, work),
154
+ daemon=True,
155
+ ).start()
156
+ return record
157
+
158
+
159
+ # ── Work definitions (reuse the existing pipeline tools) ─────────────────────
160
+
161
+
162
+ def outline_via_agent(project_id: str, user_prompt: Optional[str] = None) -> None:
163
+ """Ask the real agent to read materials and propose an outline.
164
+
165
+ Tests monkeypatch this function; everything downstream is shared code.
166
+ """
167
+ from draftboard.agent import run_agent
168
+
169
+ prompt = (
170
+ f"Read materials for project '{project_id}' using read_materials, "
171
+ f"then call propose_outline to save an outline. Use one item per "
172
+ f"slide, cite real source_ids from the materials, and keep each "
173
+ f"summary concise. Report the outline_version returned."
174
+ )
175
+ if user_prompt and user_prompt.strip():
176
+ prompt += (
177
+ f"\n\nUser direction / constraints (follow while still strictly "
178
+ f"citing real source_ids and marking unsupported claims as "
179
+ f"'unsupported' without fabricating numbers):\n{user_prompt.strip()}"
180
+ )
181
+ asyncio.run(run_agent(prompt))
182
+
183
+
184
+ def _latest_outline_version(root: pathlib.Path, project_id: str) -> Optional[str]:
185
+ outlines_dir = root / project_id / "outlines"
186
+ if not outlines_dir.exists():
187
+ return None
188
+ files = list(outlines_dir.glob("*.json"))
189
+ if not files:
190
+ return None
191
+ return max(files, key=lambda p: p.stat().st_mtime).stem
192
+
193
+
194
+ def outline_work(
195
+ root: pathlib.Path,
196
+ project_id: str,
197
+ user_prompt: Optional[str] = None,
198
+ ) -> Callable[[TaskContext], dict]:
199
+ def work(ctx: TaskContext) -> dict:
200
+ assets_dir = root / project_id / "assets"
201
+ materials = [f for f in assets_dir.glob("*") if f.is_file()] if assets_dir.exists() else []
202
+ if not materials:
203
+ raise RuntimeError("项目中暂无可用素材,请先上传文件或输入主题笔记后再生成大纲。")
204
+ ctx.set_step("读取材料并生成大纲")
205
+ params = inspect.signature(outline_via_agent).parameters
206
+ if user_prompt and len(params) >= 2:
207
+ outline_via_agent(project_id, user_prompt)
208
+ else:
209
+ outline_via_agent(project_id)
210
+ version = _latest_outline_version(root, project_id)
211
+ if version is None:
212
+ raise RuntimeError("Agent 没有保存任何大纲,请检查素材内容格式或稍后重试。")
213
+ return {"outline_version": version}
214
+
215
+ return work
216
+
217
+
218
+ def _split_clauses(text: str) -> list[str]:
219
+ raw_lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
220
+ if len(raw_lines) >= 2:
221
+ return [re.sub(r"^[•\-\*\d\.、\s]+", "", ln).strip() for ln in raw_lines if ln.strip()]
222
+ parts = [
223
+ p.strip()
224
+ for p in re.split(r"[。;;!!??\n]+", text)
225
+ if p and p.strip()
226
+ ]
227
+ return [re.sub(r"^[•\-\*\d\.、\s]+", "", p).strip() for p in parts if p.strip()]
228
+
229
+
230
+ def _deterministic_refine_slide(
231
+ title: str,
232
+ summary: str,
233
+ column_right: Optional[str],
234
+ layout: Optional[str],
235
+ source_excerpts: list[str],
236
+ mode: str,
237
+ instruction: Optional[str],
238
+ ) -> dict:
239
+ """Deterministic local refinement rules (also used as offline fallback)."""
240
+ base_title = title.strip() or "核心要点"
241
+ if len(base_title) > 22 and mode == "concise":
242
+ base_title = base_title[:21].rstrip(",、:: ") + "…"
243
+
244
+ base_text = summary.strip()
245
+ if (not base_text or base_text == "输入本页的核心陈述内容…") and source_excerpts:
246
+ base_text = source_excerpts[0].strip()
247
+
248
+ effective_mode = mode
249
+ if mode == "custom" and instruction:
250
+ inst = instruction.lower()
251
+ if any(k in inst for k in ("双栏", "对比", "左右", "two_column")):
252
+ effective_mode = "two_column"
253
+ elif any(k in inst for k in ("分点", "要点", "列表", "bullet")):
254
+ effective_mode = "bullets"
255
+ else:
256
+ effective_mode = "concise"
257
+
258
+ clauses = _split_clauses(base_text)
259
+ if not clauses and source_excerpts:
260
+ clauses = _split_clauses(source_excerpts[0])
261
+ if not clauses:
262
+ clauses = [base_text or "待补充要点"]
263
+
264
+ if effective_mode == "two_column":
265
+ if len(clauses) == 1 and len(clauses[0]) > 16:
266
+ mid_char = len(clauses[0]) // 2
267
+ clauses = [clauses[0][:mid_char].strip(), clauses[0][mid_char:].strip()]
268
+ elif len(clauses) == 1:
269
+ clauses = [clauses[0], (column_right or "").strip() or "对比与落地成效"]
270
+ mid = max(1, (len(clauses) + 1) // 2)
271
+ left_lines = [c[:42] for c in clauses[:mid][:4]]
272
+ right_lines = [c[:42] for c in clauses[mid:][:4]]
273
+ if not right_lines:
274
+ right_lines = [(column_right or "").strip() or clauses[-1][:42]]
275
+ return {
276
+ "title": base_title,
277
+ "summary": "\n".join(left_lines),
278
+ "column_right": "\n".join(right_lines),
279
+ "layout": "two_column",
280
+ "rationale": "已将核心陈述拆分为左右双栏对比结构,单栏控制在 4 行以内。",
281
+ }
282
+
283
+ if effective_mode == "bullets":
284
+ bullet_lines = []
285
+ for c in clauses[:5]:
286
+ trimmed = c[:38].rstrip(",、") + ("…" if len(c) > 38 else "")
287
+ if trimmed:
288
+ bullet_lines.append(trimmed)
289
+ return {
290
+ "title": base_title,
291
+ "summary": "\n".join(bullet_lines),
292
+ "column_right": column_right,
293
+ "layout": "bullets",
294
+ "rationale": f"已提炼为 {len(bullet_lines)} 条独立分点要点,每条控制在单行安全宽度内。",
295
+ }
296
+
297
+ # Default: "concise" (anti-overflow compaction)
298
+ concise_lines = []
299
+ for c in clauses[:4]:
300
+ trimmed = c[:34].rstrip(",、") + ("…" if len(c) > 34 else "")
301
+ if trimmed:
302
+ concise_lines.append(trimmed)
303
+ next_right = column_right
304
+ if layout == "two_column" and column_right:
305
+ r_clauses = _split_clauses(column_right)
306
+ next_right = "\n".join(
307
+ c[:32].rstrip(",、") + ("…" if len(c) > 32 else "")
308
+ for c in r_clauses[:4]
309
+ )
310
+ return {
311
+ "title": base_title,
312
+ "summary": "\n".join(concise_lines),
313
+ "column_right": next_right,
314
+ "layout": layout or "content",
315
+ "rationale": "已精简冗余修饰并收紧单行字数,确保在 18pt 正文框内不溢出。",
316
+ }
317
+
318
+
319
+ def refine_slide_item(
320
+ project_id: str,
321
+ title: str,
322
+ summary: str,
323
+ column_right: Optional[str] = None,
324
+ layout: Optional[str] = None,
325
+ source_excerpts: Optional[list[str]] = None,
326
+ mode: str = "concise",
327
+ instruction: Optional[str] = None,
328
+ ) -> dict:
329
+ """Produce a non-destructive refinement candidate (Diff preview) for one slide.
330
+
331
+ Uses the configured LLM when an API key is available, and falls back to
332
+ deterministic local rules when offline or in unit tests.
333
+ """
334
+ excerpts = [e for e in (source_excerpts or []) if e and e.strip()]
335
+ has_api_key = bool(
336
+ os.environ.get("GEMINI_API_KEY") or os.environ.get("OPENAI_API_KEY")
337
+ )
338
+ if has_api_key and not os.environ.get("PYTEST_CURRENT_TEST"):
339
+ try:
340
+ from draftboard.agent import run_agent
341
+
342
+ mode_desc = {
343
+ "concise": "精简字数以防止 PPT 文本框溢出(总行数不超过 4 行,每行不超过 34 字),保留关键事实与数字",
344
+ "bullets": "改写为 3~5 条按换行分隔的分点要点(layout 设为 'bullets')",
345
+ "two_column": "改写为左栏(summary)与右栏(column_right)对称的双栏对比(layout 设为 'two_column')",
346
+ "custom": instruction or "优化本页表达,使其更紧凑清晰",
347
+ }.get(mode, instruction or "精简优化本页内容")
348
+
349
+ prompt = (
350
+ f"You are refining a single slide in project '{project_id}'. "
351
+ f"Do NOT call any tools. Return ONLY a raw JSON object with keys: "
352
+ f"title, summary, column_right, layout, rationale.\n"
353
+ f"Strict rule: never fabricate numbers or facts not present in the current slide or source excerpts.\n"
354
+ f"Current slide:\n"
355
+ f"- title: {title}\n"
356
+ f"- layout: {layout or 'content'}\n"
357
+ f"- summary:\n{summary}\n"
358
+ f"- column_right:\n{column_right or ''}\n"
359
+ f"Bound source excerpts:\n{chr(10).join(excerpts) if excerpts else '(none)'}\n"
360
+ f"Refinement task: {mode_desc}\n"
361
+ f"Additional instruction: {instruction or '(none)'}"
362
+ )
363
+ raw_out = asyncio.run(run_agent(prompt))
364
+ match = re.search(r"\{[\s\S]*\}", raw_out)
365
+ if match:
366
+ parsed = json.loads(match.group(0))
367
+ if parsed.get("title") and parsed.get("summary"):
368
+ return {
369
+ "title": str(parsed["title"]).strip(),
370
+ "summary": str(parsed["summary"]).strip(),
371
+ "column_right": (
372
+ str(parsed["column_right"]).strip()
373
+ if parsed.get("column_right")
374
+ else column_right
375
+ ),
376
+ "layout": parsed.get("layout") or layout or "content",
377
+ "rationale": str(
378
+ parsed.get("rationale") or "已根据原始素材与指令生成修改建议。"
379
+ ),
380
+ }
381
+ except Exception:
382
+ pass
383
+
384
+ return _deterministic_refine_slide(
385
+ title=title,
386
+ summary=summary,
387
+ column_right=column_right,
388
+ layout=layout,
389
+ source_excerpts=excerpts,
390
+ mode=mode,
391
+ instruction=instruction,
392
+ )
393
+
394
+
395
+ def generate_work(
396
+ root: pathlib.Path,
397
+ project_id: str,
398
+ outline_version: str,
399
+ template_id: str = "default",
400
+ auto_fit: bool = False,
401
+ ) -> Callable[[TaskContext], dict]:
402
+ import draftboard.tools as tools_module
403
+
404
+ def work(ctx: TaskContext) -> dict:
405
+ key_suffix = f"{outline_version}-{template_id}-af{int(auto_fit)}"
406
+ ctx.set_step("从已确认大纲生成幻灯片")
407
+ artifact = _raw(tools_module.generate_slides)(
408
+ project_id=project_id,
409
+ approved_outline_version=outline_version,
410
+ template_id=template_id,
411
+ idempotency_key=f"api-gen-{key_suffix}",
412
+ auto_fit=auto_fit,
413
+ )
414
+ ctx.set_step("校验幻灯片结构")
415
+ report = _raw(tools_module.validate_artifact)(
416
+ artifact_id=artifact.artifact_id,
417
+ revision=artifact.artifact_revision,
418
+ )
419
+ ctx.set_step("排版检查并导出 PPTX")
420
+ export = tools_module.export_deck_impl(
421
+ project_id=project_id,
422
+ artifact_id=artifact.artifact_id,
423
+ revision=artifact.artifact_revision,
424
+ idempotency_key=f"api-export-{key_suffix}",
425
+ )
426
+ result = {
427
+ "outline_version": outline_version,
428
+ "artifact_id": artifact.artifact_id,
429
+ "artifact_revision": artifact.artifact_revision,
430
+ "validation": report.model_dump(),
431
+ "export": export.model_dump(),
432
+ }
433
+ ctx.set_result(result)
434
+ if report.has_errors:
435
+ raise RuntimeError("幻灯片结构校验未通过,未导出文件。")
436
+ if not export.success:
437
+ raise RuntimeError("排版检查未通过,未生成文件。请根据问题列表调整大纲后重新生成。")
438
+ if export.pptx_path:
439
+ ctx.set_step("渲染逐页预览")
440
+ import pathlib as _pathlib
441
+
442
+ from draftboard.render import render_preview
443
+
444
+ preview_dir = (
445
+ root / project_id / "previews"
446
+ / f"{artifact.artifact_id}-r{artifact.artifact_revision}"
447
+ )
448
+ try:
449
+ pages = render_preview(_pathlib.Path(export.pptx_path), preview_dir)
450
+ result["preview_pages"] = len(pages)
451
+ except Exception as e:
452
+ # Preview failure never invalidates the written PPTX.
453
+ result["preview_error"] = str(e)
454
+ ctx.set_result(result)
455
+ return result
456
+
457
+ return work
458
+
459
+
460
+ def _raw(tool):
461
+ fn = getattr(tool, "__wrapped__", None) or getattr(tool, "fn", None)
462
+ if fn is None:
463
+ raise RuntimeError(f"Cannot unwrap tool {tool}")
464
+ return fn
draftboard/themes.py ADDED
@@ -0,0 +1,213 @@
1
+ """
2
+ Presentation theme definitions for Draftboard's deterministic PPTX exporter.
3
+
4
+ Curated Apple Keynote / Swiss Editorial themes:
5
+ - keynote_light : Pure light canvas, graphite typography, restrained blue accent
6
+ - keynote_dark : Keynote obsidian dark canvas, crisp white/silver hierarchy
7
+ - nordic_pine : Deep pine cover, ivory content slides, sage accent
8
+ - gallery_sand : Warm linen paper canvas, charcoal cover, terracotta accent
9
+ - default : Minimalist unstyled white baseline (preserves Phase-1 fixtures)
10
+ """
11
+
12
+ from dataclasses import dataclass
13
+ from pptx.dml.color import RGBColor
14
+
15
+
16
+ def _rgb(hex_color: str) -> RGBColor:
17
+ h = hex_color.lstrip("#")
18
+ return RGBColor(int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ThemeSpec:
23
+ id: str
24
+ name: str
25
+ description: str
26
+ bg_hex: str
27
+ cover_bg_hex: str
28
+ title_hex: str
29
+ cover_title_hex: str
30
+ body_hex: str
31
+ cover_body_hex: str
32
+ accent_hex: str
33
+ muted_hex: str
34
+ divider_hex: str
35
+ surface_hex: str
36
+ bold_title: bool = True
37
+ decorative: bool = True
38
+ show_page_number: bool = True
39
+ left_aligned_cover: bool = True
40
+
41
+ @property
42
+ def bg_rgb(self) -> RGBColor:
43
+ return _rgb(self.bg_hex)
44
+
45
+ @property
46
+ def cover_bg_rgb(self) -> RGBColor:
47
+ return _rgb(self.cover_bg_hex)
48
+
49
+ @property
50
+ def title_rgb(self) -> RGBColor:
51
+ return _rgb(self.title_hex)
52
+
53
+ @property
54
+ def cover_title_rgb(self) -> RGBColor:
55
+ return _rgb(self.cover_title_hex)
56
+
57
+ @property
58
+ def body_rgb(self) -> RGBColor:
59
+ return _rgb(self.body_hex)
60
+
61
+ @property
62
+ def cover_body_rgb(self) -> RGBColor:
63
+ return _rgb(self.cover_body_hex)
64
+
65
+ @property
66
+ def accent_rgb(self) -> RGBColor:
67
+ return _rgb(self.accent_hex)
68
+
69
+ @property
70
+ def muted_rgb(self) -> RGBColor:
71
+ return _rgb(self.muted_hex)
72
+
73
+ @property
74
+ def divider_rgb(self) -> RGBColor:
75
+ return _rgb(self.divider_hex)
76
+
77
+ @property
78
+ def surface_rgb(self) -> RGBColor:
79
+ return _rgb(self.surface_hex)
80
+
81
+ def to_public_dict(self) -> dict:
82
+ return {
83
+ "id": self.id,
84
+ "name": self.name,
85
+ "description": self.description,
86
+ "swatches": {
87
+ "bg": self.bg_hex,
88
+ "cover_bg": self.cover_bg_hex,
89
+ "title": self.title_hex,
90
+ "cover_title": self.cover_title_hex,
91
+ "body": self.body_hex,
92
+ "cover_body": self.cover_body_hex,
93
+ "accent": self.accent_hex,
94
+ "muted": self.muted_hex,
95
+ "divider": self.divider_hex,
96
+ "surface": self.surface_hex,
97
+ },
98
+ }
99
+
100
+
101
+ THEMES: dict[str, ThemeSpec] = {
102
+ "keynote_light": ThemeSpec(
103
+ id="keynote_light",
104
+ name="苹果白",
105
+ description="纯净画布 · 极简黑字",
106
+ bg_hex="#FBFBFD",
107
+ cover_bg_hex="#F5F5F7",
108
+ title_hex="#1D1D1F",
109
+ cover_title_hex="#1D1D1F",
110
+ body_hex="#424245",
111
+ cover_body_hex="#6E6E73",
112
+ accent_hex="#0071E3",
113
+ muted_hex="#86868B",
114
+ divider_hex="#E5E5EA",
115
+ surface_hex="#FFFFFF",
116
+ ),
117
+ "keynote_dark": ThemeSpec(
118
+ id="keynote_dark",
119
+ name="深空钛黑",
120
+ description="发布会暗黑 · 银灰层次",
121
+ bg_hex="#111113",
122
+ cover_bg_hex="#000000",
123
+ title_hex="#F5F5F7",
124
+ cover_title_hex="#FFFFFF",
125
+ body_hex="#A1A1A6",
126
+ cover_body_hex="#86868B",
127
+ accent_hex="#2997FF",
128
+ muted_hex="#6E6E73",
129
+ divider_hex="#262629",
130
+ surface_hex="#1C1C1F",
131
+ ),
132
+ "nordic_pine": ThemeSpec(
133
+ id="nordic_pine",
134
+ name="松柏森绿",
135
+ description="深松封面 · 象牙正文",
136
+ bg_hex="#FAFBF9",
137
+ cover_bg_hex="#0F2922",
138
+ title_hex="#10241E",
139
+ cover_title_hex="#F4F7F5",
140
+ body_hex="#3D4F49",
141
+ cover_body_hex="#9FB8AF",
142
+ accent_hex="#2E7D63",
143
+ muted_hex="#7E948C",
144
+ divider_hex="#E3EAE6",
145
+ surface_hex="#F2F6F4",
146
+ ),
147
+ "gallery_sand": ThemeSpec(
148
+ id="gallery_sand",
149
+ name="美术馆暖石",
150
+ description="亚麻纸感 · 陶土点缀",
151
+ bg_hex="#F4F1EA",
152
+ cover_bg_hex="#23221F",
153
+ title_hex="#1F1E1B",
154
+ cover_title_hex="#F4F1EA",
155
+ body_hex="#4F4B45",
156
+ cover_body_hex="#B8B2A6",
157
+ accent_hex="#B4533C",
158
+ muted_hex="#948E84",
159
+ divider_hex="#E3DDD2",
160
+ surface_hex="#ECE7DD",
161
+ ),
162
+ "default": ThemeSpec(
163
+ id="default",
164
+ name="极简白纸",
165
+ description="纯净白底 · 零装饰",
166
+ bg_hex="#FFFFFF",
167
+ cover_bg_hex="#FFFFFF",
168
+ title_hex="#262626",
169
+ cover_title_hex="#262626",
170
+ body_hex="#262626",
171
+ cover_body_hex="#262626",
172
+ accent_hex="#262626",
173
+ muted_hex="#737373",
174
+ divider_hex="#E5E5E5",
175
+ surface_hex="#FFFFFF",
176
+ bold_title=False,
177
+ decorative=False,
178
+ show_page_number=False,
179
+ left_aligned_cover=False,
180
+ ),
181
+ }
182
+
183
+ # Backwards-compatible aliases for earlier theme IDs saved in existing projects
184
+ THEME_ALIASES: dict[str, str] = {
185
+ "business_slate": "keynote_light",
186
+ "dark_tech": "keynote_dark",
187
+ "warm_editorial": "gallery_sand",
188
+ }
189
+
190
+ DEFAULT_PRESENTATION_THEME = "keynote_light"
191
+
192
+
193
+ def is_valid_theme(template_id: str | None) -> bool:
194
+ if not template_id:
195
+ return False
196
+ return template_id in THEMES or template_id in THEME_ALIASES
197
+
198
+
199
+ def resolve_theme_id(template_id: str | None) -> str:
200
+ if not template_id:
201
+ return "default"
202
+ canonical = THEME_ALIASES.get(template_id, template_id)
203
+ return canonical if canonical in THEMES else "default"
204
+
205
+
206
+ def get_theme(template_id: str | None) -> ThemeSpec:
207
+ return THEMES[resolve_theme_id(template_id)]
208
+
209
+
210
+ def list_themes() -> list[dict]:
211
+ """Return the 4 curated presentation themes for the studio picker."""
212
+ curated = ("keynote_light", "keynote_dark", "nordic_pine", "gallery_sand")
213
+ return [THEMES[tid].to_public_dict() for tid in curated]