Spaces:
Paused
Paused
Download routes/qa.py from modventures/room-visualizer: direct link, hf CLI and curl.
- Browser
- Download file 5.95 kB
-
https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/routes/qa.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer/routes/qa.py
-
curl -L -o qa.py https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/routes/qa.py
5.95 kB
| """QA run management and reporting routes.""" | |
| import asyncio | |
| import json | |
| import mimetypes | |
| import time | |
| import uuid | |
| from fastapi import APIRouter, BackgroundTasks, Body, Query, Request, Response | |
| from fastapi.responses import StreamingResponse | |
| from config.qa import QA_BACKEND_URL, QA_MAX_IMAGES, QA_MAX_TESTS | |
| from enums import QaStatus | |
| from errors import bad_request, not_found | |
| from qa.constants import QA_TILE_DESCRIPTIONS | |
| from qa.images import dedupe_qa_image_keys, list_qa_spaces_images | |
| from qa.report import build_qa_report_html | |
| from qa.runner import run_qa_task | |
| from qa.scenarios import normalize_qa_tile, parse_tile_descriptions | |
| from qa.store import qa_iso_now, qa_run_root, qa_sse_event, read_qa_run, write_qa_run | |
| router = APIRouter(prefix="/qa", tags=["qa"]) | |
| async def qa_images( | |
| range: str = Query("week"), | |
| from_value: str | None = Query(None, alias="from"), | |
| to: str | None = Query(None), | |
| max_items: int = Query(100, ge=1, le=500), | |
| ): | |
| return {"images": list_qa_spaces_images(range, from_value, to, min(max_items, QA_MAX_IMAGES))} | |
| async def create_qa_run( | |
| request: Request, | |
| background_tasks: BackgroundTasks, | |
| payload: dict = Body(...), | |
| ): | |
| raw_image_keys = payload.get("imageKeys") | |
| if not isinstance(raw_image_keys, list): | |
| bad_request("imageKeys must be a non-empty array.") | |
| image_keys = [str(key).strip() for key in raw_image_keys if isinstance(key, str) and str(key).strip()] | |
| if not image_keys: | |
| bad_request("Select at least one image.") | |
| image_keys = dedupe_qa_image_keys(image_keys) | |
| if not image_keys: | |
| bad_request("All selected images were duplicates.") | |
| if len(image_keys) > QA_MAX_IMAGES: | |
| bad_request(f"Select at most {QA_MAX_IMAGES} images.") | |
| raw_tiles = payload.get("tiles") | |
| if raw_tiles is None: | |
| raw_tiles = list(QA_TILE_DESCRIPTIONS) | |
| if not isinstance(raw_tiles, list): | |
| bad_request("tiles must be an array.") | |
| tiles = [] | |
| for tile in raw_tiles: | |
| if not isinstance(tile, str) or not tile.strip(): | |
| continue | |
| normalized = normalize_qa_tile(tile) | |
| if normalized not in tiles: | |
| tiles.append(normalized) | |
| if not tiles: | |
| bad_request("Select at least one tile.") | |
| total = len(image_keys) * len(tiles) | |
| if total > QA_MAX_TESTS: | |
| bad_request(f"QA matrix is too large. Max tests: {QA_MAX_TESTS}.") | |
| run_id = f"qa_{uuid.uuid4().hex}" | |
| use_gemini = bool(payload.get("useGemini", True)) | |
| descriptions = parse_tile_descriptions(payload.get("tileDescriptions")) | |
| backend_url = QA_BACKEND_URL or str(request.base_url).rstrip("/") | |
| run = { | |
| "id": run_id, | |
| "status": QaStatus.QUEUED, | |
| "createdAt": qa_iso_now(), | |
| "updatedAt": qa_iso_now(), | |
| "total": total, | |
| "completed": 0, | |
| "passed": 0, | |
| "failed": 0, | |
| "imageKeys": image_keys, | |
| "tiles": tiles, | |
| "useGemini": use_gemini, | |
| "reportUrl": f"/qa/runs/{run_id}/report", | |
| "results": [], | |
| } | |
| write_qa_run(run) | |
| background_tasks.add_task(run_qa_task, run_id, image_keys, tiles, descriptions, use_gemini, backend_url) | |
| return run | |
| async def qa_run_status(run_id: str): | |
| return read_qa_run(run_id) | |
| async def qa_run_events(run_id: str, request: Request): | |
| read_qa_run(run_id) | |
| async def event_stream(): | |
| last_payload = "" | |
| last_keepalive = time.monotonic() | |
| while True: | |
| if await request.is_disconnected(): | |
| break | |
| run = read_qa_run(run_id) | |
| payload = json.dumps(run, sort_keys=True) | |
| if payload != last_payload: | |
| last_payload = payload | |
| yield qa_sse_event("run", run) | |
| if run.get("status") not in {QaStatus.QUEUED, QaStatus.RUNNING}: | |
| break | |
| elif time.monotonic() - last_keepalive >= 15: | |
| last_keepalive = time.monotonic() | |
| yield ": keepalive\n\n" | |
| await asyncio.sleep(1) | |
| return StreamingResponse( | |
| event_stream(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache, no-transform", | |
| "Connection": "keep-alive", | |
| "X-Accel-Buffering": "no", | |
| }, | |
| ) | |
| async def qa_run_report(run_id: str): | |
| run = read_qa_run(run_id) | |
| return Response(content=build_qa_report_html(run), media_type="text/html", headers={"Cache-Control": "no-store"}) | |
| async def qa_run_markdown_report(run_id: str): | |
| root = qa_run_root(run_id) | |
| report_path = root / "qa-summary.md" | |
| if not report_path.exists(): | |
| run = read_qa_run(run_id) | |
| content = "\n".join([ | |
| "# Real Browser QA Summary", | |
| "", | |
| f"Status: {run.get('status', 'unknown')}", | |
| "", | |
| run.get("error") or "The QA summary has not been generated yet.", | |
| "", | |
| ]) | |
| return Response(content=content, media_type="text/markdown", headers={"Cache-Control": "no-store"}) | |
| return Response(content=report_path.read_text(), media_type="text/markdown", headers={"Cache-Control": "no-store"}) | |
| async def qa_run_asset(run_id: str, asset_path: str): | |
| root = qa_run_root(run_id).resolve() | |
| target = (root / asset_path).resolve() | |
| if root != target and root not in target.parents: | |
| bad_request("Invalid QA asset path.") | |
| if not target.exists() or not target.is_file(): | |
| not_found("QA asset not found.") | |
| media_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream" | |
| return Response(content=target.read_bytes(), media_type=media_type, headers={"Cache-Control": "private, max-age=3600"}) | |