server.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. """Local-only workbench API; model output never reaches a shell."""
  2. from __future__ import annotations
  3. import io
  4. import json
  5. import os
  6. import re
  7. import threading
  8. import time
  9. import uuid
  10. import zipfile
  11. from pathlib import Path
  12. from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
  13. from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response
  14. from fastapi.staticfiles import StaticFiles
  15. from pydantic import BaseModel, ConfigDict, Field
  16. from typing import Literal
  17. from .artifacts import write_result
  18. from .figma import fetch_figma, parse_figma_url
  19. from .pipeline import run_pipeline
  20. ROOT = Path(__file__).resolve().parent.parent
  21. RUN_ROOT = ROOT / "outputs/runs"
  22. MAX_BODY = 2 * 1024 * 1024
  23. app = FastAPI(title="FrameCraft", version="0.1.0", docs_url="/api/docs")
  24. _runs: dict[str, dict] = {}
  25. _lock = threading.RLock()
  26. _slots = threading.BoundedSemaphore(2)
  27. class RunRequest(BaseModel):
  28. model_config = ConfigDict(extra="forbid")
  29. source: Literal["sample", "json", "figma"] = "sample"
  30. payload: dict | None = None
  31. figma_url: str = Field(default="", max_length=2048)
  32. node_id: str | None = Field(default=None, max_length=100)
  33. mode: Literal["demo", "live"] = "demo"
  34. brief: str = Field(default="", max_length=2000)
  35. def _availability() -> dict:
  36. return {
  37. "status": "ok",
  38. "live_available": bool((os.getenv("LLM_API_KEY") or os.getenv("OPENAI_API_KEY"))
  39. and (os.getenv("LLM_MODEL_ID") or os.getenv("MODEL_NAME"))),
  40. "figma_available": bool(os.getenv("FIGMA_ACCESS_TOKEN")),
  41. }
  42. def _safe_error(exc: Exception) -> str:
  43. message = str(exc)
  44. for key, value in os.environ.items():
  45. if any(word in key for word in ("KEY", "TOKEN", "PASSWORD", "SECRET")) and len(value) > 5:
  46. message = message.replace(value, "[redacted]")
  47. return message[:800]
  48. @app.middleware("http")
  49. async def local_request_guard(request: Request, call_next):
  50. # The app is a localhost utility, not an authenticated multi-user service.
  51. host = request.url.hostname
  52. if host not in ("localhost", "127.0.0.1", "testserver"):
  53. return JSONResponse({"detail": "仅支持 localhost 访问。"}, status_code=400)
  54. if request.method == "POST":
  55. origin = request.headers.get("origin")
  56. allowed = {f"http://127.0.0.1:{request.url.port or 80}", f"http://localhost:{request.url.port or 80}"}
  57. if origin and origin not in allowed:
  58. return JSONResponse({"detail": "不允许跨站提交生成请求。"}, status_code=403)
  59. size = 0
  60. pieces = []
  61. async for part in request.stream():
  62. size += len(part)
  63. if size > MAX_BODY:
  64. return JSONResponse({"detail": "请求超过 2 MB,请缩小设计 JSON。"}, status_code=413)
  65. pieces.append(part)
  66. request._body = b"".join(pieces)
  67. response = await call_next(request)
  68. response.headers["X-Content-Type-Options"] = "nosniff"
  69. response.headers["Referrer-Policy"] = "no-referrer"
  70. response.headers["Cache-Control"] = "no-store"
  71. return response
  72. @app.get("/api/health")
  73. def health():
  74. return _availability()
  75. @app.get("/api/sample")
  76. def sample():
  77. return json.loads((ROOT / "data/sample-design.json").read_text(encoding="utf-8"))
  78. def _record(run_id: str, event: dict):
  79. with _lock:
  80. _runs[run_id]["events"].append(dict(event))
  81. def _work(run_id: str, spec: RunRequest):
  82. try:
  83. with _lock:
  84. _runs[run_id]["status"] = "running"
  85. selected = spec.node_id
  86. if spec.source == "sample":
  87. payload = sample()
  88. elif spec.source == "figma":
  89. _record(run_id, {"stage": "import", "status": "running", "message": "正在读取选中的 Figma 节点…"})
  90. payload, selected = fetch_figma(spec.figma_url, os.getenv("FIGMA_ACCESS_TOKEN", ""), spec.node_id)
  91. else:
  92. payload = spec.payload
  93. result = run_pipeline(payload, node_id=selected, mode=spec.mode, brief=spec.brief,
  94. on_event=lambda event: _record(run_id, event))
  95. output = write_result(result, RUN_ROOT / run_id)
  96. public = {k: v for k, v in result.items() if k not in ("events", "files")}
  97. # Export both source files and evidence files.
  98. artifacts = {str(path.relative_to(output)): path.read_text(encoding="utf-8")
  99. for path in output.rglob("*") if path.is_file()}
  100. public["files"] = [{"path": path, "size": len(content.encode("utf-8"))}
  101. for path, content in sorted(artifacts.items())]
  102. with _lock:
  103. _runs[run_id].update(status="completed", result=public, _files=artifacts)
  104. except Exception as exc:
  105. error = _safe_error(exc)
  106. with _lock:
  107. _runs[run_id].update(status="failed", error=error)
  108. _record(run_id, {"stage": "error", "status": "failed", "message": error})
  109. finally:
  110. _slots.release()
  111. @app.post("/api/runs", status_code=202)
  112. def create_run(spec: RunRequest, tasks: BackgroundTasks):
  113. availability = _availability()
  114. if spec.mode == "live" and not availability["live_available"]:
  115. raise HTTPException(400, "在线模式需要在项目 .env 中配置 LLM_API_KEY 和 LLM_MODEL_ID。")
  116. if spec.source == "json" and spec.payload is None:
  117. raise HTTPException(400, "请上传 Figma REST 格式的 JSON 对象。")
  118. if spec.source == "figma":
  119. try:
  120. parse_figma_url(spec.figma_url, spec.node_id)
  121. except ValueError as exc:
  122. raise HTTPException(400, str(exc)) from exc
  123. if not availability["figma_available"]:
  124. raise HTTPException(400, "请在项目 .env 中配置 FIGMA_ACCESS_TOKEN。")
  125. if not _slots.acquire(blocking=False):
  126. raise HTTPException(429, "已有两个任务正在运行,请等待完成后重试。")
  127. run_id = uuid.uuid4().hex
  128. with _lock:
  129. if len(_runs) >= 24:
  130. old = next((key for key, run in _runs.items() if run["status"] in ("completed", "failed")), None)
  131. if old:
  132. _runs.pop(old)
  133. _runs[run_id] = {"id": run_id, "status": "queued", "events": [], "created_at": time.time()}
  134. tasks.add_task(_work, run_id, spec)
  135. return {"id": run_id, "status": "queued"}
  136. def _get_run(run_id: str) -> dict:
  137. if not re.fullmatch(r"[0-9a-f]{32}", run_id):
  138. raise HTTPException(404, "任务不存在。")
  139. with _lock:
  140. run = _runs.get(run_id)
  141. if run is None:
  142. raise HTTPException(404, "任务不存在或已离开当前会话。已保存的产物仍在 outputs/runs 中。")
  143. return run
  144. @app.get("/api/runs/{run_id}")
  145. def get_run(run_id: str):
  146. run = _get_run(run_id)
  147. with _lock:
  148. return {key: value for key, value in run.items() if not key.startswith("_")}
  149. def _files(run_id: str) -> dict[str, str]:
  150. run = _get_run(run_id)
  151. if run["status"] != "completed":
  152. raise HTTPException(409, "任务尚未完成。")
  153. return run["_files"]
  154. @app.get("/api/runs/{run_id}/files", response_class=PlainTextResponse)
  155. def get_file(run_id: str, path: str):
  156. files = _files(run_id)
  157. if path not in files:
  158. raise HTTPException(404, "产物中没有此文件。")
  159. return PlainTextResponse(files[path])
  160. @app.get("/api/runs/{run_id}/preview", response_class=HTMLResponse)
  161. def preview(run_id: str):
  162. return HTMLResponse(_files(run_id)["preview.html"], headers={
  163. "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'self'; sandbox",
  164. })
  165. @app.get("/api/runs/{run_id}/download")
  166. def download(run_id: str):
  167. buffer = io.BytesIO()
  168. with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
  169. for path, content in _files(run_id).items():
  170. archive.writestr(path, content)
  171. return Response(buffer.getvalue(), media_type="application/zip", headers={
  172. "Content-Disposition": f'attachment; filename="framecraft-{run_id[:8]}.zip"',
  173. })
  174. app.mount("/", StaticFiles(directory=ROOT / "web", html=True), name="workbench")