import asyncio import json import logging import time import os from typing import Annotated import uvicorn from fastapi import FastAPI, Query, Request from fastapi.responses import HTMLResponse, Response from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from cdf_parser import CdfParser from render import Renderer def handle_pdb(sig, frame): import pdb pdb.Pdb().set_trace(frame) logging.basicConfig(level=logging.DEBUG) app = FastAPI() templates = Jinja2Templates(directory="templates") renderer: Renderer = Renderer(debug=True, concurrent_workers=8, storage_state="894799196@qq.com.json") @app.on_event(r"startup") def startup(): # FIXME: This background task cannot catch an exception asyncio.gather(renderer.run()) @app.get("/", response_class=Response) async def render(): with open("web-2-J7IzVHyi0Zc.cdf", "rb") as f: cdf = f.read() rendered_page = await renderer.render_page(cdf) if rendered_page is None: return Response(status_code=500) return Response(content=await renderer.render_page(cdf), media_type="image/png") app.mount("/file", StaticFiles(directory="."), name="file") @app.get("/file", response_class=HTMLResponse) def list_files(request: Request): files = os.listdir("./") files_paths = sorted([f"/file/{f}" for f in files]) # print(files_paths) return templates.TemplateResponse( "list_files.html", {"request": request, "files": files_paths} ) @app.get("/worker/{worker_id}") async def get_worker(worker_id: int): return Response(content=await renderer.worker_screenshot(worker_id), media_type="image/png") @app.get("/worker_content/{worker_id}") async def get_content(worker_id: int): return Response(content=await renderer.worker_content(worker_id)) @app.post("/render") async def render_cdf(cdf_dict: dict): cdf = json.dumps(cdf_dict) rendered_page = await renderer.render_page(cdf) if rendered_page is None: return Response(status_code=500) return Response(content=rendered_page, media_type="image/png") if __name__ == "__main__": uvicorn.run("serve:app", host="0.0.0.0", port=8000, log_level="debug")