serve_old_web.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Serve the legacy decompose demo from repo-local files.
  2. The legacy `web/index.html` expects assets at root paths such as
  3. `/frameworks.json`, `/payloads.json`, `/prompt-read/...`, and `/data/...`.
  4. This tiny server preserves those paths without changing the old frontend.
  5. """
  6. from __future__ import annotations
  7. import os
  8. from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
  9. from pathlib import Path
  10. from urllib.parse import unquote, urlparse
  11. ROOT = Path(__file__).resolve().parent.parent
  12. WEB = ROOT / "web"
  13. PROMPTS = ROOT / "prompts"
  14. SKILL_EXTRACTION = ROOT / "创作知识提取-skill" / "extraction"
  15. def _load_env_file(path: str | Path) -> dict[str, str]:
  16. p = Path(path)
  17. if not p.is_absolute():
  18. p = ROOT / p
  19. if not p.exists():
  20. return {}
  21. out: dict[str, str] = {}
  22. for line in p.read_text(encoding="utf-8").splitlines():
  23. stripped = line.strip()
  24. if not stripped or stripped.startswith("#") or "=" not in stripped:
  25. continue
  26. key, value = stripped.split("=", 1)
  27. out[key.strip()] = value.strip().strip('"').strip("'")
  28. return out
  29. def _data_root() -> Path:
  30. env = _load_env_file(os.getenv("CK_ENV_FILE", ".env"))
  31. raw = os.getenv("CK_DATA_DIR") or env.get("CK_DATA_DIR")
  32. if not raw:
  33. raw = "legacy_data" if (ROOT / "legacy_data").exists() else "data"
  34. p = Path(raw)
  35. return p if p.is_absolute() else ROOT / p
  36. class LegacyDemoHandler(SimpleHTTPRequestHandler):
  37. def translate_path(self, path: str) -> str:
  38. parsed = urlparse(path)
  39. clean = unquote(parsed.path)
  40. if clean in {"", "/"}:
  41. return str(WEB / "index.html")
  42. if clean.startswith("/data/"):
  43. return str(_data_root() / clean.removeprefix("/data/"))
  44. if clean.startswith("/runs/"):
  45. return str(WEB / clean.lstrip("/"))
  46. if clean.startswith("/prompt-read/"):
  47. return str(PROMPTS / clean.removeprefix("/prompt-read/"))
  48. if clean.startswith("/prompt-skill/"):
  49. return str(SKILL_EXTRACTION / clean.removeprefix("/prompt-skill/"))
  50. return str(WEB / clean.lstrip("/"))
  51. def main() -> None:
  52. server = ThreadingHTTPServer(("127.0.0.1", 8127), LegacyDemoHandler)
  53. print("Serving legacy demo at http://127.0.0.1:8127/")
  54. server.serve_forever()
  55. if __name__ == "__main__":
  56. main()