387 lines
17 KiB
Python
387 lines
17 KiB
Python
"""CADmind 演示用网页后端:一个极简的Flask服务,把已有的理解层/生成层管线包成HTTP接口,
|
|
给前端聊天页面用。不做用户认证/多租户隔离——这是给你自己/小范围测试用的演示服务,
|
|
不是生产环境的多用户系统。
|
|
|
|
接口:
|
|
GET / 服务信息(前端独立启动)
|
|
POST /api/generate {text, images?} -> 生成新零件(images最多5张base64图片,
|
|
旧版单图字段image_base64继续兼容)
|
|
POST /api/modify {part_name, text, images?} -> 修改已有零件
|
|
GET /api/parts 列出已生成的零件
|
|
GET /files/<part>/model.stl STL文件(前端拿去渲染)
|
|
GET /files/<part>/model.step STEP文件(下载用)
|
|
"""
|
|
|
|
import sys
|
|
import os
|
|
import json
|
|
import traceback
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from dotenv import load_dotenv
|
|
from flask import Flask, jsonify, request, send_file
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
load_dotenv(BASE_DIR / ".env")
|
|
sys.path.insert(0, str(BASE_DIR))
|
|
|
|
from engine.llm_client import MAX_IMAGES # noqa: E402
|
|
from engine.pipeline import PipelineError, generate_from_description_best, modify_existing_part # noqa: E402
|
|
from engine.validation import safe_name # noqa: E402
|
|
from engine.quality_pipeline import resume_quality # noqa: E402
|
|
from engine.isolated import run_isolated # noqa: E402
|
|
from web.messages import failure_response, outcome, questions, issue_text, question_items
|
|
|
|
app = Flask(__name__, static_folder=None)
|
|
app.config["MAX_CONTENT_LENGTH"] = 140 * 1024 * 1024
|
|
|
|
|
|
def _cors_origins() -> set[str]:
|
|
configured = os.environ.get("CADMIND_CORS_ORIGINS", "")
|
|
return {origin.strip().rstrip("/") for origin in configured.split(",") if origin.strip()}
|
|
|
|
|
|
@app.after_request
|
|
def add_cors_headers(response):
|
|
origin = request.headers.get("Origin", "").rstrip("/")
|
|
if origin and origin in _cors_origins():
|
|
response.headers["Access-Control-Allow-Origin"] = origin
|
|
response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS"
|
|
response.headers["Access-Control-Allow-Headers"] = "Content-Type"
|
|
response.headers["Access-Control-Max-Age"] = "600"
|
|
response.headers.add("Vary", "Origin")
|
|
return response
|
|
|
|
|
|
def _extract_images(data: dict) -> list[str]:
|
|
"""参考图经常要正视图/侧视图/俯视图分开拍,一张图塞不下这么多信息——
|
|
新版前端传images(数组),旧版单图字段image_base64继续兼容,最多取MAX_IMAGES张。"""
|
|
images = data.get("images")
|
|
if not images:
|
|
single = data.get("image_base64")
|
|
images = [single] if single else []
|
|
if not isinstance(images, list) or any(not isinstance(img, str) for img in images):
|
|
raise ValueError("images 必须是 base64 字符串数组")
|
|
if len(images) > MAX_IMAGES:
|
|
raise ValueError(f"最多上传 {MAX_IMAGES} 张图片")
|
|
return [img for img in images if img]
|
|
|
|
|
|
def _existing_part_names():
|
|
out_dir = BASE_DIR / "output"
|
|
if not out_dir.exists():
|
|
return []
|
|
return sorted(p.name for p in out_dir.iterdir() if p.is_dir() and not p.is_symlink()
|
|
and (p / "report.json").exists() and not (p / ".deleted.json").exists())
|
|
|
|
|
|
def _report_to_response(report: dict) -> dict:
|
|
unfinished = report.get("unfinished_geometry")
|
|
if unfinished is None:
|
|
try:
|
|
from engine.quality_models import Brief
|
|
from engine.reference_contract import unfinished_geometry
|
|
unfinished = unfinished_geometry(Brief.model_validate(report["requirements"]), report.get("reviews", []), report.get("quality_status") == "passed")
|
|
except (ValueError, KeyError, TypeError):
|
|
unfinished = []
|
|
part_name = report["part_name"]
|
|
reason = report.get("quality_reason") or report.get("fallback_reason")
|
|
asks = questions(BASE_DIR, part_name)
|
|
return {
|
|
"ok": True,
|
|
"part_name": part_name,
|
|
"display_name": report.get("display_name", part_name),
|
|
"volume_mm3": report.get("volume_mm3"),
|
|
"assumptions": report.get("llm_assumptions", []),
|
|
"degraded_fallback": bool(report.get("degraded_fallback")),
|
|
"placeholder": bool(report.get("is_fallback_placeholder")),
|
|
"quality_status": report.get("quality_status", "failed" if report.get("is_fallback_placeholder") else
|
|
"approximate" if report.get("degraded_fallback") else "unverified"),
|
|
"remaining_issues": [issue_text(v) for v in report.get("remaining_issues", [])],
|
|
"geometry_issues": [issue_text(v) for v in report.get("geometry_issues", [])] if "geometry_issues" in report else None,
|
|
"review_errors": [issue_text(v) for v in report.get("review_errors", [])],
|
|
"information_needed": report.get("information_needed", report.get("unresolved", [])),
|
|
"manufacturing_notes": report.get("manufacturing_notes", []),
|
|
"design_choices": report.get("design_choices", []),
|
|
"reference_sources": report.get("reference_sources", []),
|
|
"description": report.get("source_description", ""),
|
|
"candidate_parameters": report.get("candidate_parameters", []),
|
|
"unfinished_geometry": unfinished,
|
|
"completed_stages": report.get("completed_stages", []),
|
|
"quality_reason": outcome(reason)[1] if reason else None,
|
|
"questions": asks, "can_clarify": bool(asks),
|
|
"next_action": "answer_questions" if asks else "resume" if report.get("quality_status") == "partial" else None,
|
|
"question_items": question_items(BASE_DIR,part_name),
|
|
"diagnostic_id": part_name,
|
|
"modification_failed": bool(report.get("modification_failed")),
|
|
"modification_failed_reason": outcome(report["modification_failed_reason"])[1] if report.get("modification_failed_reason") else None,
|
|
"can_resume": bool(report.get("quality_mode") and report.get("quality_status") == "partial" and not asks),
|
|
"review_url": f"/files/{part_name}/report.json",
|
|
"stl_url": f"/files/{part_name}/model.stl",
|
|
"step_url": f"/files/{part_name}/model.step",
|
|
}
|
|
|
|
|
|
def _pipeline_error_response(exc):
|
|
job_id = getattr(exc, "job_id", None)
|
|
traceback.print_exc()
|
|
return jsonify(failure_response(str(exc), BASE_DIR, job_id)), 503 if job_id else 500
|
|
|
|
|
|
from web.tasks import TaskManager
|
|
from engine.images import normalize_images
|
|
|
|
tasks = TaskManager(BASE_DIR, _report_to_response)
|
|
|
|
|
|
@app.route("/api/tasks", methods=["POST"])
|
|
def start_task():
|
|
data = request.get_json(force=True)
|
|
try:
|
|
if not isinstance(data, dict):
|
|
raise ValueError("请求必须为对象")
|
|
action = data.get("action", "generate")
|
|
if action not in ("generate", "modify", "resume"):
|
|
raise ValueError("未知任务类型")
|
|
values = {}
|
|
if action != "resume":
|
|
text = data.get("text")
|
|
if not isinstance(text, str) or not text.strip():
|
|
raise ValueError("描述不能为空")
|
|
images = _extract_images(data)
|
|
normalize_images(images) # Reject invalid images before starting a worker/API call.
|
|
values.update(text=text.strip(), images=images)
|
|
if action != "generate":
|
|
part_name = safe_name(data.get("part_name"))
|
|
if not (BASE_DIR / "output" / part_name / "request.json").exists() and action == "resume":
|
|
raise ValueError("找不到可恢复的任务")
|
|
values["part_name"] = part_name
|
|
if action == "resume":
|
|
clarification = data.get("clarification", "")
|
|
if not isinstance(clarification, str) or len(clarification) > 12000:
|
|
raise ValueError("补充说明需为不超过 12000 字的文字")
|
|
if questions(BASE_DIR, values["part_name"]) and not clarification.strip():
|
|
raise ValueError("请先填写需要确认的尺寸或要求,再继续")
|
|
if clarification.strip():
|
|
values["clarification"] = clarification.strip()
|
|
task_id = tasks.start(action, values)
|
|
return jsonify({"ok": True, "task_id": task_id}), 202
|
|
except ValueError as exc:
|
|
return jsonify({"ok": False, "error": str(exc)}), 400
|
|
|
|
|
|
@app.route("/api/tasks/<task_id>", methods=["GET", "DELETE"])
|
|
def task_status(task_id):
|
|
try:
|
|
if request.method == "DELETE":
|
|
tasks.cancel(task_id)
|
|
return jsonify(tasks.status(task_id))
|
|
except KeyError:
|
|
return jsonify({"ok": False, "error": "任务不存在或服务已重启;已保存的建模进度不会被删除"}), 404
|
|
|
|
|
|
@app.route("/api/interrupted")
|
|
def interrupted_jobs():
|
|
jobs = []
|
|
folders = sorted((BASE_DIR / "output").glob("quality_*"), reverse=True)
|
|
resumed = set()
|
|
for folder in folders:
|
|
try:
|
|
resumed.add(json.loads((folder / "resume.json").read_text())["parent_job"])
|
|
except (OSError, ValueError, KeyError):
|
|
pass
|
|
for folder in folders:
|
|
try:
|
|
state = json.loads((folder / "job.json").read_text())
|
|
original = json.loads((folder / "request.json").read_text())
|
|
if state["status"] == "failed" and folder.name not in resumed:
|
|
jobs.append({"part_name": folder.name, "text": original["text"], "can_resume": True,
|
|
"error": "上次任务未完成,原图和已完成的操作已保存。"})
|
|
except (OSError, ValueError, KeyError):
|
|
continue
|
|
if len(jobs) >= 5:
|
|
break
|
|
return jsonify({"jobs": jobs})
|
|
|
|
|
|
@app.route("/api/health")
|
|
def health():
|
|
revision = BASE_DIR / "REVISION"
|
|
with tasks.lock:
|
|
active = sum(not t["done"] for t in tasks.tasks.values())
|
|
return jsonify({"ok": True, "revision": revision.read_text().strip() if revision.exists() else "development", "active_tasks": active})
|
|
|
|
|
|
@app.route("/")
|
|
def index():
|
|
return jsonify({"service": "CADmind API", "ok": True, "health_url": "/api/health"})
|
|
|
|
|
|
@app.route("/api/parts/catalog")
|
|
def part_catalog():
|
|
entries = []
|
|
for name in _existing_part_names():
|
|
folder = BASE_DIR / "output" / name
|
|
if not (folder / "model.stl").is_file():
|
|
continue
|
|
try:
|
|
report = json.loads((folder / "report.json").read_text())
|
|
if not isinstance(report, dict):
|
|
continue
|
|
entries.append({
|
|
"part_name": name,
|
|
"display_name": report.get("display_name") or report.get("name") or name,
|
|
"quality_status": report.get("quality_status", "unverified"),
|
|
"modified_at": (folder / "report.json").stat().st_mtime,
|
|
"volume_mm3": report.get("volume_mm3"),
|
|
})
|
|
except (OSError, ValueError, TypeError):
|
|
continue
|
|
entries.sort(key=lambda entry: entry["modified_at"], reverse=True)
|
|
return jsonify({"parts": entries[:200], "total": len(entries)})
|
|
|
|
|
|
@app.route("/api/parts/<part_name>")
|
|
def part_detail(part_name):
|
|
try:
|
|
folder = BASE_DIR / "output" / safe_name(part_name)
|
|
if (folder / ".deleted.json").exists():
|
|
raise ValueError("Deleted part")
|
|
report = json.loads((folder / "report.json").read_text())
|
|
if not isinstance(report, dict) or not (folder / "model.stl").is_file():
|
|
raise ValueError("No readable model")
|
|
report["part_name"] = part_name
|
|
result = _report_to_response(report)
|
|
result["description"] = report.get("source_description", "")
|
|
if not result["description"] and (folder / "request.json").exists():
|
|
# A damaged optional request must not prevent opening an existing model.
|
|
try:
|
|
original = json.loads((folder / "request.json").read_text())
|
|
if isinstance(original, dict):
|
|
result["description"] = original.get("text", "")
|
|
except (OSError, ValueError):
|
|
pass
|
|
return jsonify(result)
|
|
except (OSError, ValueError, KeyError, TypeError):
|
|
return jsonify({"ok": False, "message": "这个零件暂时无法读取,请选择其他零件。"}), 404
|
|
|
|
|
|
@app.route("/api/parts/<part_name>", methods=["DELETE"])
|
|
def delete_part(part_name):
|
|
try:
|
|
folder = BASE_DIR / "output" / safe_name(part_name)
|
|
if folder.is_symlink() or not (folder / "report.json").is_file():
|
|
raise ValueError("Unknown part")
|
|
# Preserve source files used by descendant revisions; deletion is reversible.
|
|
from engine.job import write_json
|
|
write_json(folder / ".deleted.json", {"deleted_at": time.time()})
|
|
return jsonify({"ok": True, "part_name": part_name})
|
|
except (ValueError, OSError):
|
|
return jsonify({"ok": False, "message": "无法删除这个零件,请刷新后重试。"}), 404
|
|
|
|
|
|
@app.route("/api/parts/<part_name>/restore", methods=["POST"])
|
|
def restore_part(part_name):
|
|
try:
|
|
folder = BASE_DIR / "output" / safe_name(part_name)
|
|
if folder.is_symlink() or not (folder / "report.json").is_file():
|
|
raise ValueError("Unknown part")
|
|
(folder / ".deleted.json").unlink(missing_ok=True)
|
|
return jsonify({"ok": True, "part_name": part_name})
|
|
except (ValueError, OSError):
|
|
return jsonify({"ok": False, "message": "无法恢复这个零件,请刷新后重试。"}), 404
|
|
|
|
|
|
@app.route("/api/parts")
|
|
def list_parts():
|
|
return jsonify({"parts": _existing_part_names()})
|
|
|
|
|
|
@app.route("/api/generate", methods=["POST"])
|
|
def api_generate():
|
|
data = request.get_json(force=True) or {}
|
|
if not isinstance(data, dict) or not isinstance(data.get("text", ""), str):
|
|
return jsonify({"ok": False, "error": "请求必须为对象,text 必须为字符串"}), 400
|
|
text = (data.get("text") or "").strip()
|
|
if not text:
|
|
return jsonify({"ok": False, "error": "描述不能为空"}), 400
|
|
|
|
try:
|
|
images = _extract_images(data)
|
|
mode = data.get("mode", "quality")
|
|
if mode not in ("quality", "legacy"):
|
|
raise ValueError("mode 只能为 quality 或 legacy")
|
|
report = run_isolated("generate" if mode == "quality" else "legacy", BASE_DIR, text=text, images=images)
|
|
return jsonify(_report_to_response(report))
|
|
except ValueError as e:
|
|
return jsonify({"ok": False, "error": str(e)}), 400
|
|
except PipelineError as e:
|
|
return _pipeline_error_response(e)
|
|
except Exception as e: # noqa: BLE001 - 演示服务,异常也要以JSON形式回给前端,不能只是500页面
|
|
traceback.print_exc()
|
|
return jsonify(failure_response(str(e), BASE_DIR)), 500
|
|
|
|
|
|
@app.route("/api/modify", methods=["POST"])
|
|
def api_modify():
|
|
data = request.get_json(force=True) or {}
|
|
if not isinstance(data, dict) or any(not isinstance(data.get(k, ""), str) for k in ("part_name", "text")):
|
|
return jsonify({"ok": False, "error": "part_name 和 text 必须为字符串"}), 400
|
|
part_name = (data.get("part_name") or "").strip()
|
|
text = (data.get("text") or "").strip()
|
|
if not part_name or not text:
|
|
return jsonify({"ok": False, "error": "part_name 和 text 都不能为空"}), 400
|
|
|
|
try:
|
|
images = _extract_images(data)
|
|
safe_name(part_name)
|
|
report = run_isolated("modify", BASE_DIR, part_name=part_name, text=text, images=images)
|
|
resp = _report_to_response(report)
|
|
resp["modification_failed"] = bool(report.get("modification_failed"))
|
|
return jsonify(resp)
|
|
except ValueError as e:
|
|
return jsonify({"ok": False, "error": str(e)}), 400
|
|
except PipelineError as e:
|
|
return _pipeline_error_response(e)
|
|
except Exception as e: # noqa: BLE001
|
|
traceback.print_exc()
|
|
return jsonify(failure_response(str(e), BASE_DIR)), 500
|
|
|
|
|
|
@app.route("/api/resume", methods=["POST"])
|
|
def api_resume():
|
|
data = request.get_json(force=True) or {}
|
|
if not isinstance(data, dict):
|
|
return jsonify({"ok": False, "error": "请求必须为对象"}), 400
|
|
try:
|
|
part_name = safe_name(data.get("part_name"))
|
|
clarification = data.get("clarification", "")
|
|
if not isinstance(clarification, str) or len(clarification) > 12000:
|
|
raise ValueError("补充说明需为不超过 12000 字的文字")
|
|
if questions(BASE_DIR, part_name) and not clarification.strip():
|
|
raise ValueError("请先填写需要确认的尺寸或要求,再继续")
|
|
return jsonify(_report_to_response(run_isolated("resume", BASE_DIR, part_name=part_name, clarification=clarification.strip())))
|
|
except ValueError as exc:
|
|
return jsonify({"ok": False, "error": str(exc)}), 400
|
|
except PipelineError as exc:
|
|
return _pipeline_error_response(exc)
|
|
|
|
|
|
@app.route("/files/<part_name>/<filename>")
|
|
def serve_file(part_name, filename):
|
|
try:
|
|
safe_name(part_name)
|
|
except ValueError:
|
|
return jsonify({"error": "无效零件名"}), 400
|
|
if filename not in ("model.stl", "model.step", "report.json", "preview.png"):
|
|
return jsonify({"error": "不支持的文件类型"}), 404
|
|
file_path = BASE_DIR / "output" / part_name / filename
|
|
if not file_path.exists():
|
|
return jsonify({"error": "文件不存在"}), 404
|
|
return send_file(file_path, as_attachment=(filename == "model.step"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=8080, debug=False)
|