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.
- draftboard/__init__.py +41 -0
- draftboard/__main__.py +225 -0
- draftboard/agent.py +104 -0
- draftboard/api.py +901 -0
- draftboard/measure.py +225 -0
- draftboard/models.py +407 -0
- draftboard/pptx_export.py +479 -0
- draftboard/render.py +80 -0
- draftboard/static/404.html +1 -0
- draftboard/static/__next.__PAGE__.txt +27 -0
- draftboard/static/__next._full.txt +22 -0
- draftboard/static/__next._tree.txt +3 -0
- draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_buildManifest.js +11 -0
- draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_clientMiddlewareManifest.js +1 -0
- draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_ssgManifest.js +1 -0
- draftboard/static/_next/static/chunks/0cz1d0mv5g_q7.js +1 -0
- draftboard/static/_next/static/chunks/0oheds1fsp9jx.js +1 -0
- draftboard/static/_next/static/chunks/1vsonpqt4u2rw.js +1 -0
- draftboard/static/_next/static/chunks/24xul4hawiu8l.js +1 -0
- draftboard/static/_next/static/chunks/2r7iycbt4s29o.js +22 -0
- draftboard/static/_next/static/chunks/2utugak-w5oge.css +1 -0
- draftboard/static/_next/static/chunks/39_j1bdzreq0m.js +1 -0
- draftboard/static/_next/static/chunks/3qfy96eoyh-ek.js +1 -0
- draftboard/static/_next/static/chunks/3u8gxd9uztfzl.js +4 -0
- draftboard/static/_next/static/chunks/3v_59l1qr_8dp.js +31 -0
- draftboard/static/_next/static/chunks/turbopack-2u1d16houkiyo.js +1 -0
- draftboard/static/_not-found/__next._full.txt +20 -0
- draftboard/static/_not-found/__next._not-found/__PAGE__.txt +26 -0
- draftboard/static/_not-found/__next._tree.txt +4 -0
- draftboard/static/_not-found.html +1 -0
- draftboard/static/_not-found.txt +20 -0
- draftboard/static/index.html +1 -0
- draftboard/static/index.txt +22 -0
- draftboard/static/p/__placeholder__/__next._full.txt +27 -0
- draftboard/static/p/__placeholder__/__next._tree.txt +5 -0
- draftboard/static/p/__placeholder__/__next.p/$d$id/__PAGE__.txt +34 -0
- draftboard/static/p/__placeholder__/preview/__next._full.txt +27 -0
- draftboard/static/p/__placeholder__/preview/__next._tree.txt +6 -0
- draftboard/static/p/__placeholder__/preview/__next.p/$d$id/preview/__PAGE__.txt +35 -0
- draftboard/static/p/__placeholder__/preview.html +1 -0
- draftboard/static/p/__placeholder__/preview.txt +27 -0
- draftboard/static/p/__placeholder__.html +1 -0
- draftboard/static/p/__placeholder__.txt +27 -0
- draftboard/storage.py +183 -0
- draftboard/tasks.py +464 -0
- draftboard/themes.py +213 -0
- draftboard/tools.py +723 -0
- draftboard-0.0.1.dist-info/METADATA +16 -0
- draftboard-0.0.1.dist-info/RECORD +51 -0
- draftboard-0.0.1.dist-info/WHEEL +4 -0
- draftboard-0.0.1.dist-info/entry_points.txt +2 -0
draftboard/api.py
ADDED
|
@@ -0,0 +1,901 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FastAPI interface over the existing Draftboard pipeline.
|
|
3
|
+
|
|
4
|
+
Every endpoint calls the same tool/storage/export functions the CLI and
|
|
5
|
+
agent use — there is no second generation path here. Long work (model
|
|
6
|
+
outline generation, slide generation + export) runs as persisted tasks.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import pathlib
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from contextlib import asynccontextmanager
|
|
16
|
+
from typing import Optional
|
|
17
|
+
|
|
18
|
+
from dotenv import load_dotenv
|
|
19
|
+
from fastapi import Body, FastAPI, HTTPException, UploadFile
|
|
20
|
+
from fastapi.responses import FileResponse, JSONResponse, Response
|
|
21
|
+
from pydantic import BaseModel
|
|
22
|
+
|
|
23
|
+
import draftboard.tasks as tasks
|
|
24
|
+
import draftboard.tools as tools_module
|
|
25
|
+
from draftboard.models import (
|
|
26
|
+
EvidenceStatus,
|
|
27
|
+
Outline,
|
|
28
|
+
OutlineItem,
|
|
29
|
+
SlideLayout,
|
|
30
|
+
validate_outline,
|
|
31
|
+
)
|
|
32
|
+
from draftboard.pptx_export import _resolve_image_path
|
|
33
|
+
from draftboard.storage import STORAGE_ROOT, ProjectStorage, load_json
|
|
34
|
+
from draftboard.themes import is_valid_theme, list_themes, resolve_theme_id
|
|
35
|
+
|
|
36
|
+
load_dotenv()
|
|
37
|
+
|
|
38
|
+
_PROJECT_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}")
|
|
39
|
+
_ALLOWED_EXTENSIONS = {".md", ".txt", ".docx", ".pdf", ".png", ".jpg", ".jpeg"}
|
|
40
|
+
_STATIC_DIR = pathlib.Path(__file__).parent / "static"
|
|
41
|
+
_PARENTS = pathlib.Path(__file__).resolve().parents
|
|
42
|
+
_FRONTEND_OUT_DIR = (
|
|
43
|
+
_PARENTS[3] / "frontend" / "out" if len(_PARENTS) > 3 else None
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _web_dir() -> pathlib.Path:
|
|
48
|
+
if _FRONTEND_OUT_DIR and (_FRONTEND_OUT_DIR / "index.html").exists():
|
|
49
|
+
return _FRONTEND_OUT_DIR
|
|
50
|
+
return _STATIC_DIR
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _root() -> pathlib.Path:
|
|
54
|
+
return tools_module._storage_root or STORAGE_ROOT
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _storage(project_id: str) -> ProjectStorage:
|
|
58
|
+
return ProjectStorage(project_id, storage_root=tools_module._storage_root)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _require_project(project_id: str) -> None:
|
|
62
|
+
if not (_root() / project_id).is_dir():
|
|
63
|
+
raise HTTPException(404, f"项目 '{project_id}' 不存在")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _raw(tool):
|
|
67
|
+
fn = getattr(tool, "__wrapped__", None) or getattr(tool, "fn", None)
|
|
68
|
+
if fn is None:
|
|
69
|
+
raise RuntimeError(f"Cannot unwrap tool {tool}")
|
|
70
|
+
return fn
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _outline_summaries(project_id: str) -> list[dict]:
|
|
74
|
+
outlines_dir = _root() / project_id / "outlines"
|
|
75
|
+
if not outlines_dir.exists():
|
|
76
|
+
return []
|
|
77
|
+
summaries = []
|
|
78
|
+
for path in sorted(outlines_dir.glob("*.json")):
|
|
79
|
+
data = load_json(path)
|
|
80
|
+
summaries.append(
|
|
81
|
+
{
|
|
82
|
+
"outline_version": data["outline_version"],
|
|
83
|
+
"is_confirmed": data["is_confirmed"],
|
|
84
|
+
"item_count": len(data["items"]),
|
|
85
|
+
"mtime": path.stat().st_mtime,
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
return summaries
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _export_reports(project_id: str) -> list[dict]:
|
|
92
|
+
exports_dir = _root() / project_id / "exports"
|
|
93
|
+
if not exports_dir.exists():
|
|
94
|
+
return []
|
|
95
|
+
reports = []
|
|
96
|
+
for path in exports_dir.glob("*.report.json"):
|
|
97
|
+
data = load_json(path)
|
|
98
|
+
data["_mtime"] = path.stat().st_mtime
|
|
99
|
+
reports.append(data)
|
|
100
|
+
return sorted(reports, key=lambda r: r["_mtime"])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _latest_artifact_meta(project_id: str) -> dict:
|
|
104
|
+
success_report = _latest_success_report(project_id)
|
|
105
|
+
if success_report:
|
|
106
|
+
art_path = (
|
|
107
|
+
_root()
|
|
108
|
+
/ project_id
|
|
109
|
+
/ "artifacts"
|
|
110
|
+
/ success_report["artifact_id"]
|
|
111
|
+
/ f"r{success_report['artifact_revision']}.json"
|
|
112
|
+
)
|
|
113
|
+
if art_path.exists():
|
|
114
|
+
data = load_json(art_path)
|
|
115
|
+
return {
|
|
116
|
+
"outline_version": data.get("outline_version"),
|
|
117
|
+
"template_id": data.get("template_id"),
|
|
118
|
+
"auto_fit": data.get("auto_fit"),
|
|
119
|
+
}
|
|
120
|
+
return {}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _latest_success_report(project_id: str) -> Optional[dict]:
|
|
124
|
+
for report in reversed(_export_reports(project_id)):
|
|
125
|
+
path = report.get("pptx_path")
|
|
126
|
+
if report["success"] and path and pathlib.Path(path).exists():
|
|
127
|
+
return report
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@asynccontextmanager
|
|
132
|
+
async def lifespan(app: FastAPI):
|
|
133
|
+
tasks.sweep_interrupted(_root())
|
|
134
|
+
yield
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
app = FastAPI(title="Draftboard API", lifespan=lifespan)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@app.exception_handler(ValueError)
|
|
141
|
+
async def value_error_handler(request, exc):
|
|
142
|
+
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@app.exception_handler(KeyError)
|
|
146
|
+
async def key_error_handler(request, exc):
|
|
147
|
+
return JSONResponse(status_code=404, content={"detail": str(exc)})
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@app.exception_handler(tasks.TaskConflictError)
|
|
151
|
+
async def conflict_handler(request, exc):
|
|
152
|
+
return JSONResponse(status_code=409, content={"detail": str(exc)})
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# ── Projects ─────────────────────────────────────────────────────────────────
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class CreateProjectRequest(BaseModel):
|
|
159
|
+
project_id: str
|
|
160
|
+
name: Optional[str] = None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _project_summary(pid: str) -> dict:
|
|
164
|
+
p_dir = _root() / pid
|
|
165
|
+
meta_path = p_dir / "meta.json"
|
|
166
|
+
name = pid
|
|
167
|
+
if meta_path.exists():
|
|
168
|
+
try:
|
|
169
|
+
name = load_json(meta_path).get("name") or pid
|
|
170
|
+
except Exception:
|
|
171
|
+
pass
|
|
172
|
+
|
|
173
|
+
outlines = _outline_summaries(pid)
|
|
174
|
+
reports = _export_reports(pid)
|
|
175
|
+
latest_report = reports[-1] if reports else None
|
|
176
|
+
latest_success = _latest_success_report(pid)
|
|
177
|
+
|
|
178
|
+
assets_dir = p_dir / "assets"
|
|
179
|
+
materials_count = len([f for f in assets_dir.glob("*") if f.is_file()]) if assets_dir.exists() else 0
|
|
180
|
+
|
|
181
|
+
slide_count = 0
|
|
182
|
+
insufficient_evidence_count = 0
|
|
183
|
+
is_confirmed = False
|
|
184
|
+
|
|
185
|
+
if outlines:
|
|
186
|
+
latest_outline_meta = max(outlines, key=lambda o: o["mtime"])
|
|
187
|
+
is_confirmed = latest_outline_meta["is_confirmed"]
|
|
188
|
+
slide_count = latest_outline_meta["item_count"]
|
|
189
|
+
try:
|
|
190
|
+
outline_data = load_json(p_dir / "outlines" / f"{latest_outline_meta['outline_version']}.json")
|
|
191
|
+
for it in outline_data.get("items", []):
|
|
192
|
+
if (
|
|
193
|
+
it.get("evidence_status") in ("unsupported", "insufficient")
|
|
194
|
+
or not it.get("source_ids")
|
|
195
|
+
):
|
|
196
|
+
insufficient_evidence_count += 1
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
elif latest_report:
|
|
200
|
+
slide_count = latest_report.get("slide_count", 0)
|
|
201
|
+
|
|
202
|
+
if latest_success:
|
|
203
|
+
stage = "ready"
|
|
204
|
+
stage_label = "PPT 已就绪"
|
|
205
|
+
elif is_confirmed:
|
|
206
|
+
stage = "confirmed"
|
|
207
|
+
stage_label = "大纲已确认"
|
|
208
|
+
elif outlines:
|
|
209
|
+
stage = "outline_draft"
|
|
210
|
+
stage_label = "大纲待审核"
|
|
211
|
+
elif materials_count > 0:
|
|
212
|
+
stage = "materials_ready"
|
|
213
|
+
stage_label = "素材已导入"
|
|
214
|
+
else:
|
|
215
|
+
stage = "empty"
|
|
216
|
+
stage_label = "待上传素材"
|
|
217
|
+
|
|
218
|
+
mtime = p_dir.stat().st_mtime
|
|
219
|
+
if outlines:
|
|
220
|
+
mtime = max(mtime, max(o["mtime"] for o in outlines))
|
|
221
|
+
if reports:
|
|
222
|
+
mtime = max(mtime, max(r["_mtime"] for r in reports))
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
"project_id": pid,
|
|
226
|
+
"name": name,
|
|
227
|
+
"stage": stage,
|
|
228
|
+
"stage_label": stage_label,
|
|
229
|
+
"slide_count": slide_count,
|
|
230
|
+
"materials_count": materials_count,
|
|
231
|
+
"insufficient_evidence_count": insufficient_evidence_count,
|
|
232
|
+
"download_available": latest_success is not None,
|
|
233
|
+
"mtime": mtime,
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@app.post("/api/projects")
|
|
238
|
+
def create_project(req: CreateProjectRequest):
|
|
239
|
+
if not _PROJECT_ID_RE.fullmatch(req.project_id):
|
|
240
|
+
raise HTTPException(
|
|
241
|
+
400, "项目 ID 只能包含字母、数字、下划线和连字符,且以字母或数字开头"
|
|
242
|
+
)
|
|
243
|
+
if (_root() / req.project_id).exists():
|
|
244
|
+
raise HTTPException(409, f"项目 '{req.project_id}' 已存在")
|
|
245
|
+
try:
|
|
246
|
+
storage = _storage(req.project_id)
|
|
247
|
+
if req.name:
|
|
248
|
+
import json, time
|
|
249
|
+
(storage.root / "meta.json").write_text(
|
|
250
|
+
json.dumps({"project_id": req.project_id, "name": req.name, "created_at": time.time()}, ensure_ascii=False),
|
|
251
|
+
encoding="utf-8"
|
|
252
|
+
)
|
|
253
|
+
return {"project_id": req.project_id, "name": req.name or req.project_id}
|
|
254
|
+
except Exception as exc:
|
|
255
|
+
raise HTTPException(500, f"创建项目目录失败: {exc}")
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@app.get("/api/projects")
|
|
259
|
+
def list_projects():
|
|
260
|
+
root = _root()
|
|
261
|
+
if not root.exists():
|
|
262
|
+
return {"projects": []}
|
|
263
|
+
pids = [p.name for p in root.iterdir() if p.is_dir()]
|
|
264
|
+
return {
|
|
265
|
+
"projects": [_project_summary(pid) for pid in sorted(pids)]
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
@app.get("/api/themes")
|
|
270
|
+
def get_themes():
|
|
271
|
+
return {"themes": list_themes()}
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@app.get("/api/projects/{project_id}")
|
|
275
|
+
def get_project(project_id: str):
|
|
276
|
+
_require_project(project_id)
|
|
277
|
+
summary = _project_summary(project_id)
|
|
278
|
+
reports = _export_reports(project_id)
|
|
279
|
+
latest_success = _latest_success_report(project_id)
|
|
280
|
+
art_meta = _latest_artifact_meta(project_id)
|
|
281
|
+
return {
|
|
282
|
+
"project_id": project_id,
|
|
283
|
+
"name": summary["name"],
|
|
284
|
+
"stage": summary["stage"],
|
|
285
|
+
"stage_label": summary["stage_label"],
|
|
286
|
+
"slide_count": summary["slide_count"],
|
|
287
|
+
"materials_count": summary["materials_count"],
|
|
288
|
+
"insufficient_evidence_count": summary["insufficient_evidence_count"],
|
|
289
|
+
"outlines": _outline_summaries(project_id),
|
|
290
|
+
"generated_outline_version": art_meta.get("outline_version"),
|
|
291
|
+
"latest_template_id": art_meta.get("template_id"),
|
|
292
|
+
"latest_auto_fit": art_meta.get("auto_fit"),
|
|
293
|
+
"latest_report": reports[-1] if reports else None,
|
|
294
|
+
"download_available": latest_success is not None,
|
|
295
|
+
"tasks": [t.model_dump() for t in tasks.list_tasks(_root(), project_id)],
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class UpdateProjectRequest(BaseModel):
|
|
300
|
+
name: str
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@app.patch("/api/projects/{project_id}")
|
|
304
|
+
def update_project(project_id: str, req: UpdateProjectRequest):
|
|
305
|
+
if not _PROJECT_ID_RE.fullmatch(project_id):
|
|
306
|
+
raise HTTPException(400, "非法的项目 ID")
|
|
307
|
+
_require_project(project_id)
|
|
308
|
+
clean_name = req.name.strip()
|
|
309
|
+
if not clean_name:
|
|
310
|
+
raise HTTPException(400, "项目名称不能为空")
|
|
311
|
+
p_dir = _root() / project_id
|
|
312
|
+
meta_path = p_dir / "meta.json"
|
|
313
|
+
meta: dict = {"project_id": project_id, "created_at": time.time()}
|
|
314
|
+
if meta_path.exists():
|
|
315
|
+
try:
|
|
316
|
+
meta.update(load_json(meta_path))
|
|
317
|
+
except Exception:
|
|
318
|
+
pass
|
|
319
|
+
meta["name"] = clean_name
|
|
320
|
+
meta_path.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
|
|
321
|
+
return {"project_id": project_id, "name": clean_name}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@app.delete("/api/projects/{project_id}")
|
|
325
|
+
def delete_project(project_id: str):
|
|
326
|
+
if not _PROJECT_ID_RE.fullmatch(project_id):
|
|
327
|
+
raise HTTPException(400, "非法的项目 ID")
|
|
328
|
+
_require_project(project_id)
|
|
329
|
+
p_dir = _root() / project_id
|
|
330
|
+
shutil.rmtree(p_dir)
|
|
331
|
+
return {"deleted": project_id}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
# ── Materials ────────────────────────────────────────────────────────────────
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
@app.post("/api/projects/{project_id}/materials")
|
|
338
|
+
async def upload_material(project_id: str, file: UploadFile):
|
|
339
|
+
_require_project(project_id)
|
|
340
|
+
name = pathlib.Path(file.filename or "").name
|
|
341
|
+
suffix = pathlib.Path(name).suffix.lower()
|
|
342
|
+
if not name or suffix not in _ALLOWED_EXTENSIONS:
|
|
343
|
+
raise HTTPException(
|
|
344
|
+
400, "只支持上传 .md / .txt / .docx / .pdf / .png / .jpg 文件"
|
|
345
|
+
)
|
|
346
|
+
assets_dir = _storage(project_id).root / "assets"
|
|
347
|
+
assets_dir.mkdir(parents=True, exist_ok=True)
|
|
348
|
+
content = await file.read()
|
|
349
|
+
(assets_dir / name).write_bytes(content)
|
|
350
|
+
try:
|
|
351
|
+
output = _raw(tools_module.read_materials)(project_id=project_id)
|
|
352
|
+
except ValueError as exc:
|
|
353
|
+
(assets_dir / name).unlink(missing_ok=True)
|
|
354
|
+
raise HTTPException(400, str(exc)) from exc
|
|
355
|
+
return {
|
|
356
|
+
"asset_id": pathlib.Path(name).stem,
|
|
357
|
+
"source_fragments": len(output.source_fragments),
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@app.delete("/api/projects/{project_id}/materials/{asset_id}")
|
|
362
|
+
def delete_material(project_id: str, asset_id: str):
|
|
363
|
+
_require_project(project_id)
|
|
364
|
+
assets_dir = _storage(project_id).root / "assets"
|
|
365
|
+
if not assets_dir.exists():
|
|
366
|
+
raise HTTPException(404, f"素材 '{asset_id}' 不存在")
|
|
367
|
+
matches = [
|
|
368
|
+
f
|
|
369
|
+
for f in assets_dir.iterdir()
|
|
370
|
+
if f.is_file() and (f.stem == asset_id or f.name == asset_id)
|
|
371
|
+
]
|
|
372
|
+
if not matches:
|
|
373
|
+
raise HTTPException(404, f"素材 '{asset_id}' 不存在")
|
|
374
|
+
for f in matches:
|
|
375
|
+
f.unlink(missing_ok=True)
|
|
376
|
+
|
|
377
|
+
output = _raw(tools_module.read_materials)(project_id=project_id)
|
|
378
|
+
remaining_sids = {frag.source_id for frag in output.source_fragments}
|
|
379
|
+
|
|
380
|
+
# Clean up dangling references in unconfirmed draft outlines
|
|
381
|
+
storage = _storage(project_id)
|
|
382
|
+
outlines_dir = storage.root / "outlines"
|
|
383
|
+
if outlines_dir.exists():
|
|
384
|
+
for opath in outlines_dir.glob("*.json"):
|
|
385
|
+
try:
|
|
386
|
+
outline = storage.load_outline(opath.stem)
|
|
387
|
+
if outline.is_confirmed:
|
|
388
|
+
continue
|
|
389
|
+
changed = False
|
|
390
|
+
for item in outline.items:
|
|
391
|
+
filtered = [
|
|
392
|
+
sid for sid in item.source_ids if sid in remaining_sids
|
|
393
|
+
]
|
|
394
|
+
if len(filtered) != len(item.source_ids):
|
|
395
|
+
item.source_ids = filtered
|
|
396
|
+
if not item.source_ids:
|
|
397
|
+
item.evidence_status = EvidenceStatus.UNSUPPORTED
|
|
398
|
+
changed = True
|
|
399
|
+
if item.image_asset_id == asset_id:
|
|
400
|
+
item.image_asset_id = None
|
|
401
|
+
if item.layout == SlideLayout.TEXT_IMAGE:
|
|
402
|
+
item.layout = SlideLayout.CONTENT
|
|
403
|
+
changed = True
|
|
404
|
+
if changed:
|
|
405
|
+
storage.save_outline(outline)
|
|
406
|
+
except Exception:
|
|
407
|
+
pass
|
|
408
|
+
|
|
409
|
+
return {
|
|
410
|
+
"deleted": asset_id,
|
|
411
|
+
"remaining_materials": len(output.materials),
|
|
412
|
+
"source_fragments": len(output.source_fragments),
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@app.get("/api/projects/{project_id}/materials")
|
|
417
|
+
def read_materials(project_id: str):
|
|
418
|
+
_require_project(project_id)
|
|
419
|
+
return _raw(tools_module.read_materials)(project_id=project_id).model_dump()
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
@app.get("/api/projects/{project_id}/assets/{asset_ref}")
|
|
423
|
+
def get_image_asset(project_id: str, asset_ref: str):
|
|
424
|
+
_require_project(project_id)
|
|
425
|
+
assets_dir = _root() / project_id / "assets"
|
|
426
|
+
path = _resolve_image_path(asset_ref, assets_dir)
|
|
427
|
+
if path is None:
|
|
428
|
+
raise HTTPException(404, f"图片素材 '{asset_ref}' 不存在")
|
|
429
|
+
media_type = "image/png" if path.suffix.lower() == ".png" else "image/jpeg"
|
|
430
|
+
return FileResponse(path, media_type=media_type)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
# ── Outlines ─────────────────────────────────────────────────────────────────
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
class OutlineGenerateRequest(BaseModel):
|
|
437
|
+
prompt: Optional[str] = None
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@app.post("/api/projects/{project_id}/outline/generate", status_code=202)
|
|
441
|
+
def generate_outline(
|
|
442
|
+
project_id: str,
|
|
443
|
+
req: Optional[OutlineGenerateRequest] = Body(default=None),
|
|
444
|
+
):
|
|
445
|
+
_require_project(project_id)
|
|
446
|
+
user_prompt = req.prompt.strip() if (req and req.prompt) else None
|
|
447
|
+
assets_dir = _root() / project_id / "assets"
|
|
448
|
+
materials = [f for f in assets_dir.glob("*") if f.is_file()] if assets_dir.exists() else []
|
|
449
|
+
if not materials and user_prompt:
|
|
450
|
+
assets_dir.mkdir(parents=True, exist_ok=True)
|
|
451
|
+
(assets_dir / "项目简报.md").write_text(
|
|
452
|
+
f"# 项目创作简报\n\n{user_prompt}\n", encoding="utf-8"
|
|
453
|
+
)
|
|
454
|
+
_raw(tools_module.read_materials)(project_id=project_id)
|
|
455
|
+
materials = [f for f in assets_dir.glob("*") if f.is_file()]
|
|
456
|
+
if not materials:
|
|
457
|
+
raise HTTPException(
|
|
458
|
+
400, "项目中暂无可用素材,请先上传文件或输入主题笔记后再生成大纲"
|
|
459
|
+
)
|
|
460
|
+
record = tasks.submit(
|
|
461
|
+
_root(),
|
|
462
|
+
project_id,
|
|
463
|
+
"outline",
|
|
464
|
+
tasks.outline_work(_root(), project_id, user_prompt=user_prompt),
|
|
465
|
+
)
|
|
466
|
+
return record.model_dump()
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
@app.get("/api/projects/{project_id}/outlines")
|
|
470
|
+
def list_outlines(project_id: str):
|
|
471
|
+
_require_project(project_id)
|
|
472
|
+
return {"outlines": _outline_summaries(project_id)}
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
@app.get("/api/projects/{project_id}/outlines/{version}")
|
|
476
|
+
def get_outline(project_id: str, version: str):
|
|
477
|
+
_require_project(project_id)
|
|
478
|
+
return _storage(project_id).load_outline(version).model_dump()
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
@app.post("/api/projects/{project_id}/outlines/{version}/confirm")
|
|
482
|
+
def confirm_outline(project_id: str, version: str):
|
|
483
|
+
_require_project(project_id)
|
|
484
|
+
return _storage(project_id).confirm_outline(version).model_dump()
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
class OutlineItemEdit(BaseModel):
|
|
488
|
+
outline_item_id: str
|
|
489
|
+
title: str
|
|
490
|
+
summary: str
|
|
491
|
+
layout: Optional[SlideLayout] = None
|
|
492
|
+
source_ids: Optional[list[str]] = None
|
|
493
|
+
column_right: Optional[str] = None
|
|
494
|
+
image_asset_id: Optional[str] = None
|
|
495
|
+
speaker_notes: Optional[str] = None
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
class OutlineEditRequest(BaseModel):
|
|
499
|
+
items: list[OutlineItemEdit]
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
@app.put("/api/projects/{project_id}/outlines/{version}")
|
|
503
|
+
def edit_outline(project_id: str, version: str, req: OutlineEditRequest):
|
|
504
|
+
"""Edit titles, summaries, layouts, notes, and page structure (add/delete/reorder).
|
|
505
|
+
|
|
506
|
+
Editing a confirmed outline never mutates it: a new draft version is
|
|
507
|
+
derived instead, so what was confirmed stays exactly what entered the
|
|
508
|
+
pipeline, and the old PPTX remains valid for that version.
|
|
509
|
+
"""
|
|
510
|
+
_require_project(project_id)
|
|
511
|
+
storage = _storage(project_id)
|
|
512
|
+
outline = storage.load_outline(version)
|
|
513
|
+
if not req.items:
|
|
514
|
+
raise HTTPException(400, "大纲至少保留一页")
|
|
515
|
+
|
|
516
|
+
existing = {item.outline_item_id: item for item in outline.items}
|
|
517
|
+
ids = [e.outline_item_id.strip() for e in req.items]
|
|
518
|
+
if any(not iid for iid in ids):
|
|
519
|
+
raise HTTPException(400, "大纲条目 ID 不能为空")
|
|
520
|
+
if len(ids) != len(set(ids)):
|
|
521
|
+
raise HTTPException(400, "大纲条目 ID 不能重复")
|
|
522
|
+
|
|
523
|
+
new_items: list[OutlineItem] = []
|
|
524
|
+
for edit in req.items:
|
|
525
|
+
iid = edit.outline_item_id.strip()
|
|
526
|
+
if iid in existing:
|
|
527
|
+
item = existing[iid].model_copy(deep=True)
|
|
528
|
+
item.title = edit.title
|
|
529
|
+
item.summary = edit.summary
|
|
530
|
+
if "layout" in edit.model_fields_set:
|
|
531
|
+
item.layout = edit.layout
|
|
532
|
+
if "column_right" in edit.model_fields_set:
|
|
533
|
+
item.column_right = edit.column_right
|
|
534
|
+
if "image_asset_id" in edit.model_fields_set:
|
|
535
|
+
item.image_asset_id = edit.image_asset_id
|
|
536
|
+
if "speaker_notes" in edit.model_fields_set:
|
|
537
|
+
item.speaker_notes = edit.speaker_notes
|
|
538
|
+
if "source_ids" in edit.model_fields_set and edit.source_ids is not None:
|
|
539
|
+
item.source_ids = edit.source_ids
|
|
540
|
+
if not item.source_ids:
|
|
541
|
+
item.evidence_status = EvidenceStatus.UNSUPPORTED
|
|
542
|
+
elif item.evidence_status == EvidenceStatus.UNSUPPORTED:
|
|
543
|
+
item.evidence_status = EvidenceStatus.SUPPORTED
|
|
544
|
+
new_items.append(item)
|
|
545
|
+
else:
|
|
546
|
+
source_ids = edit.source_ids or []
|
|
547
|
+
new_items.append(
|
|
548
|
+
OutlineItem(
|
|
549
|
+
outline_item_id=iid,
|
|
550
|
+
title=edit.title,
|
|
551
|
+
summary=edit.summary,
|
|
552
|
+
source_ids=source_ids,
|
|
553
|
+
evidence_status=(
|
|
554
|
+
EvidenceStatus.SUPPORTED
|
|
555
|
+
if source_ids
|
|
556
|
+
else EvidenceStatus.UNSUPPORTED
|
|
557
|
+
),
|
|
558
|
+
layout=edit.layout,
|
|
559
|
+
column_right=edit.column_right,
|
|
560
|
+
image_asset_id=edit.image_asset_id,
|
|
561
|
+
speaker_notes=edit.speaker_notes,
|
|
562
|
+
)
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
errors = validate_outline(
|
|
566
|
+
new_items,
|
|
567
|
+
storage.load_source_ids(),
|
|
568
|
+
allow_empty_sources_for_unsupported=True,
|
|
569
|
+
)
|
|
570
|
+
if errors:
|
|
571
|
+
raise ValueError("Invalid outline:\n" + "\n".join(errors))
|
|
572
|
+
|
|
573
|
+
if outline.is_confirmed:
|
|
574
|
+
edited = Outline(
|
|
575
|
+
outline_version=f"v-{uuid.uuid4().hex[:8]}",
|
|
576
|
+
project_id=project_id,
|
|
577
|
+
items=new_items,
|
|
578
|
+
is_confirmed=False,
|
|
579
|
+
)
|
|
580
|
+
else:
|
|
581
|
+
edited = outline.model_copy(deep=True)
|
|
582
|
+
edited.items = new_items
|
|
583
|
+
storage.save_outline(edited)
|
|
584
|
+
return edited.model_dump()
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
class SlideRefineRequest(BaseModel):
|
|
588
|
+
title: Optional[str] = None
|
|
589
|
+
summary: Optional[str] = None
|
|
590
|
+
column_right: Optional[str] = None
|
|
591
|
+
layout: Optional[str] = None
|
|
592
|
+
source_ids: Optional[list[str]] = None
|
|
593
|
+
mode: str = "concise"
|
|
594
|
+
instruction: Optional[str] = None
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
@app.post("/api/projects/{project_id}/outlines/{version}/items/{item_id}/refine")
|
|
598
|
+
def refine_outline_item(
|
|
599
|
+
project_id: str,
|
|
600
|
+
version: str,
|
|
601
|
+
item_id: str,
|
|
602
|
+
req: SlideRefineRequest,
|
|
603
|
+
):
|
|
604
|
+
"""Generate a non-destructive AI refinement candidate (Diff preview) for one slide."""
|
|
605
|
+
_require_project(project_id)
|
|
606
|
+
storage = _storage(project_id)
|
|
607
|
+
outline = storage.load_outline(version)
|
|
608
|
+
target = next(
|
|
609
|
+
(it for it in outline.items if it.outline_item_id == item_id), None
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
title = req.title if req.title is not None else (target.title if target else "")
|
|
613
|
+
summary = (
|
|
614
|
+
req.summary
|
|
615
|
+
if req.summary is not None
|
|
616
|
+
else (target.summary if target else "")
|
|
617
|
+
)
|
|
618
|
+
column_right = (
|
|
619
|
+
req.column_right
|
|
620
|
+
if req.column_right is not None
|
|
621
|
+
else (target.column_right if target else None)
|
|
622
|
+
)
|
|
623
|
+
layout = (
|
|
624
|
+
req.layout
|
|
625
|
+
if req.layout is not None
|
|
626
|
+
else (target.layout.value if (target and target.layout) else "content")
|
|
627
|
+
)
|
|
628
|
+
sids = (
|
|
629
|
+
req.source_ids
|
|
630
|
+
if req.source_ids is not None
|
|
631
|
+
else (target.source_ids if target else [])
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
mat_out = _raw(tools_module.read_materials)(project_id=project_id)
|
|
635
|
+
frag_map = {f.source_id: f for f in mat_out.source_fragments}
|
|
636
|
+
mat_map = {m.asset_id: m.content for m in mat_out.materials}
|
|
637
|
+
excerpts: list[str] = []
|
|
638
|
+
for sid in sids:
|
|
639
|
+
frag = frag_map.get(sid)
|
|
640
|
+
if not frag:
|
|
641
|
+
continue
|
|
642
|
+
if frag.content_preview:
|
|
643
|
+
excerpts.append(frag.content_preview)
|
|
644
|
+
elif frag.asset_id in mat_map:
|
|
645
|
+
excerpts.append(mat_map[frag.asset_id][:400])
|
|
646
|
+
|
|
647
|
+
candidate = tasks.refine_slide_item(
|
|
648
|
+
project_id=project_id,
|
|
649
|
+
title=title,
|
|
650
|
+
summary=summary,
|
|
651
|
+
column_right=column_right,
|
|
652
|
+
layout=layout,
|
|
653
|
+
source_excerpts=excerpts,
|
|
654
|
+
mode=req.mode,
|
|
655
|
+
instruction=req.instruction,
|
|
656
|
+
)
|
|
657
|
+
return {
|
|
658
|
+
"outline_item_id": item_id,
|
|
659
|
+
**candidate,
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
# ── Generation ───────────────────────────────────────────────────────────────
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
class GenerateRequest(BaseModel):
|
|
667
|
+
outline_version: str
|
|
668
|
+
template_id: str = "default"
|
|
669
|
+
auto_fit: bool = False
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
@app.post("/api/projects/{project_id}/generate", status_code=202)
|
|
673
|
+
def generate(project_id: str, req: GenerateRequest):
|
|
674
|
+
_require_project(project_id)
|
|
675
|
+
if not is_valid_theme(req.template_id):
|
|
676
|
+
raise HTTPException(400, f"未知主题 '{req.template_id}'")
|
|
677
|
+
resolved_theme = resolve_theme_id(req.template_id)
|
|
678
|
+
storage = _storage(project_id)
|
|
679
|
+
outline = storage.load_outline(req.outline_version)
|
|
680
|
+
if not outline.is_confirmed:
|
|
681
|
+
raise HTTPException(
|
|
682
|
+
400,
|
|
683
|
+
f"大纲 '{req.outline_version}' 尚未确认,请先确认大纲后再生成 PPT",
|
|
684
|
+
)
|
|
685
|
+
record = tasks.submit(
|
|
686
|
+
_root(),
|
|
687
|
+
project_id,
|
|
688
|
+
"generate",
|
|
689
|
+
tasks.generate_work(
|
|
690
|
+
_root(),
|
|
691
|
+
project_id,
|
|
692
|
+
req.outline_version,
|
|
693
|
+
template_id=resolved_theme,
|
|
694
|
+
auto_fit=req.auto_fit,
|
|
695
|
+
),
|
|
696
|
+
)
|
|
697
|
+
return record.model_dump()
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
# ── Tasks / results / download ───────────────────────────────────────────────
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
@app.get("/api/projects/{project_id}/tasks")
|
|
704
|
+
def list_tasks(project_id: str):
|
|
705
|
+
_require_project(project_id)
|
|
706
|
+
return {"tasks": [t.model_dump() for t in tasks.list_tasks(_root(), project_id)]}
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
@app.get("/api/projects/{project_id}/tasks/{task_id}")
|
|
710
|
+
def get_task(project_id: str, task_id: str):
|
|
711
|
+
_require_project(project_id)
|
|
712
|
+
return tasks.load_task(_root(), project_id, task_id).model_dump()
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
@app.get("/api/projects/{project_id}/result")
|
|
716
|
+
def latest_result(project_id: str):
|
|
717
|
+
_require_project(project_id)
|
|
718
|
+
reports = _export_reports(project_id)
|
|
719
|
+
if not reports:
|
|
720
|
+
raise HTTPException(404, "该项目还没有导出结果")
|
|
721
|
+
return reports[-1]
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
@app.get("/api/projects/{project_id}/download")
|
|
725
|
+
def download(project_id: str):
|
|
726
|
+
_require_project(project_id)
|
|
727
|
+
for report in reversed(_export_reports(project_id)):
|
|
728
|
+
path = report.get("pptx_path")
|
|
729
|
+
if report["success"] and path and pathlib.Path(path).exists():
|
|
730
|
+
return FileResponse(
|
|
731
|
+
path,
|
|
732
|
+
media_type=(
|
|
733
|
+
"application/vnd.openxmlformats-officedocument."
|
|
734
|
+
"presentationml.presentation"
|
|
735
|
+
),
|
|
736
|
+
filename=f"{project_id}.pptx",
|
|
737
|
+
)
|
|
738
|
+
raise HTTPException(404, "没有可下载的 PPTX:尚未成功导出过文件")
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
@app.get("/api/projects/{project_id}/download/pdf")
|
|
742
|
+
def download_pdf(project_id: str):
|
|
743
|
+
_require_project(project_id)
|
|
744
|
+
report = _latest_success_report(project_id)
|
|
745
|
+
if not report:
|
|
746
|
+
raise HTTPException(404, "没有可下载的 PDF:尚未成功导出过文件")
|
|
747
|
+
pdir = _preview_dir(project_id, report)
|
|
748
|
+
pdf_path = pdir / "deck.pdf"
|
|
749
|
+
if not pdf_path.exists():
|
|
750
|
+
from draftboard.render import render_preview
|
|
751
|
+
|
|
752
|
+
render_preview(pathlib.Path(report["pptx_path"]), pdir)
|
|
753
|
+
if not pdf_path.exists():
|
|
754
|
+
raise HTTPException(500, "PDF 渲染未生成输出文件")
|
|
755
|
+
return FileResponse(
|
|
756
|
+
pdf_path,
|
|
757
|
+
media_type="application/pdf",
|
|
758
|
+
filename=f"{project_id}.pdf",
|
|
759
|
+
)
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
# ── Per-page preview (same artifact/revision as the download) ────────────────
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def _preview_dir(project_id: str, report: dict) -> pathlib.Path:
|
|
766
|
+
return (
|
|
767
|
+
_root() / project_id / "previews"
|
|
768
|
+
/ f"{report['artifact_id']}-r{report['artifact_revision']}"
|
|
769
|
+
)
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def _preview_payload(project_id: str, report: dict, pages: list[pathlib.Path]) -> dict:
|
|
773
|
+
cache_tag = f"{report['artifact_id']}-r{report['artifact_revision']}"
|
|
774
|
+
return {
|
|
775
|
+
"artifact_id": report["artifact_id"],
|
|
776
|
+
"artifact_revision": report["artifact_revision"],
|
|
777
|
+
"pages": [
|
|
778
|
+
f"/api/projects/{project_id}/preview/{p.name}?v={cache_tag}"
|
|
779
|
+
for p in pages
|
|
780
|
+
],
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
@app.get("/api/projects/{project_id}/preview")
|
|
785
|
+
def get_preview(project_id: str):
|
|
786
|
+
_require_project(project_id)
|
|
787
|
+
report = _latest_success_report(project_id)
|
|
788
|
+
if not report:
|
|
789
|
+
raise HTTPException(404, "尚未成功导出,没有可预览的内容")
|
|
790
|
+
pages = sorted(_preview_dir(project_id, report).glob("page-*.png"))
|
|
791
|
+
if not pages:
|
|
792
|
+
raise HTTPException(404, "预览尚未渲染,可调用 POST preview/render 重新渲染")
|
|
793
|
+
return _preview_payload(project_id, report, pages)
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
@app.post("/api/projects/{project_id}/preview/render")
|
|
797
|
+
@app.post("/api/projects/{project_id}/render-preview")
|
|
798
|
+
def render_preview_now(project_id: str):
|
|
799
|
+
_require_project(project_id)
|
|
800
|
+
from draftboard.render import render_preview
|
|
801
|
+
|
|
802
|
+
report = _latest_success_report(project_id)
|
|
803
|
+
if not report:
|
|
804
|
+
raise HTTPException(404, "尚未成功导出,没有可渲染的内容")
|
|
805
|
+
pages = render_preview(
|
|
806
|
+
pathlib.Path(report["pptx_path"]), _preview_dir(project_id, report)
|
|
807
|
+
)
|
|
808
|
+
return _preview_payload(project_id, report, pages)
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
@app.get("/api/projects/{project_id}/preview/{name}")
|
|
812
|
+
def preview_image(project_id: str, name: str):
|
|
813
|
+
_require_project(project_id)
|
|
814
|
+
if not re.fullmatch(r"page-\d+\.png", name):
|
|
815
|
+
raise HTTPException(400, "非法的预览图片名")
|
|
816
|
+
report = _latest_success_report(project_id)
|
|
817
|
+
if not report:
|
|
818
|
+
raise HTTPException(404, "尚未成功导出")
|
|
819
|
+
path = _preview_dir(project_id, report) / name
|
|
820
|
+
if not path.exists():
|
|
821
|
+
raise HTTPException(404, "预览图片不存在")
|
|
822
|
+
return FileResponse(
|
|
823
|
+
path,
|
|
824
|
+
media_type="image/png",
|
|
825
|
+
headers={"Cache-Control": "no-store"},
|
|
826
|
+
)
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
# ── Single-Port Frontend Hosting (Next.js static export + fallback) ──────────
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
@app.get("/")
|
|
833
|
+
def index():
|
|
834
|
+
return FileResponse(_web_dir() / "index.html")
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
@app.get("/_next/{subpath:path}")
|
|
838
|
+
def next_static_assets(subpath: str):
|
|
839
|
+
web_root = _web_dir().resolve()
|
|
840
|
+
target = (web_root / "_next" / subpath).resolve()
|
|
841
|
+
if not target.is_relative_to(web_root) or not target.is_file():
|
|
842
|
+
raise HTTPException(404, "静态资源不存在")
|
|
843
|
+
return FileResponse(target)
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
@app.get("/p/{rest_of_path:path}")
|
|
847
|
+
def frontend_project_routes(rest_of_path: str):
|
|
848
|
+
web_root = _web_dir().resolve()
|
|
849
|
+
cleaned = rest_of_path.strip("/")
|
|
850
|
+
if not cleaned:
|
|
851
|
+
raise HTTPException(404, "页面不存在")
|
|
852
|
+
|
|
853
|
+
placeholder_dir = (web_root / "p" / "__placeholder__").resolve()
|
|
854
|
+
if "/" not in cleaned and cleaned.endswith(".txt"):
|
|
855
|
+
pid = cleaned[:-4]
|
|
856
|
+
template_path = web_root / "p" / "__placeholder__.txt"
|
|
857
|
+
media_type = "text/plain; charset=utf-8"
|
|
858
|
+
else:
|
|
859
|
+
parts = cleaned.split("/", 1)
|
|
860
|
+
pid = parts[0]
|
|
861
|
+
sub = parts[1] if len(parts) > 1 else ""
|
|
862
|
+
if not sub:
|
|
863
|
+
template_path = web_root / "p" / "__placeholder__.html"
|
|
864
|
+
media_type = "text/html; charset=utf-8"
|
|
865
|
+
elif sub == "preview":
|
|
866
|
+
template_path = placeholder_dir / "preview.html"
|
|
867
|
+
media_type = "text/html; charset=utf-8"
|
|
868
|
+
else:
|
|
869
|
+
template_path = (placeholder_dir / sub).resolve()
|
|
870
|
+
if not template_path.is_relative_to(placeholder_dir):
|
|
871
|
+
raise HTTPException(404, "页面不存在")
|
|
872
|
+
media_type = (
|
|
873
|
+
"text/html; charset=utf-8"
|
|
874
|
+
if template_path.suffix == ".html"
|
|
875
|
+
else "text/plain; charset=utf-8"
|
|
876
|
+
)
|
|
877
|
+
|
|
878
|
+
if not _PROJECT_ID_RE.fullmatch(pid):
|
|
879
|
+
raise HTTPException(404, "非法的项目路径")
|
|
880
|
+
|
|
881
|
+
if not template_path.is_file():
|
|
882
|
+
fallback = web_root / "index.html"
|
|
883
|
+
if fallback.is_file():
|
|
884
|
+
return FileResponse(fallback)
|
|
885
|
+
raise HTTPException(404, "前端页面尚未构建")
|
|
886
|
+
|
|
887
|
+
body = template_path.read_text(encoding="utf-8").replace(
|
|
888
|
+
"__placeholder__", pid
|
|
889
|
+
)
|
|
890
|
+
return Response(content=body, media_type=media_type)
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
@app.get("/{filename}")
|
|
894
|
+
def frontend_root_files(filename: str):
|
|
895
|
+
if "/" in filename or filename.startswith("api"):
|
|
896
|
+
raise HTTPException(404, "资源不存在")
|
|
897
|
+
web_root = _web_dir().resolve()
|
|
898
|
+
target = (web_root / filename).resolve()
|
|
899
|
+
if not target.is_relative_to(web_root) or not target.is_file():
|
|
900
|
+
raise HTTPException(404, "资源不存在")
|
|
901
|
+
return FileResponse(target)
|