Spaces:
Sleeping
Sleeping
Download app/main.py from mjpsm/activity-generation-api: direct link, hf CLI and curl.
- Browser
- Download file 3.18 kB
-
https://huggingface.co/spaces/mjpsm/activity-generation-api/resolve/main/app/main.py
- Command line
-
hf download hf://spaces/mjpsm/activity-generation-api/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/mjpsm/activity-generation-api/resolve/main/app/main.py
3.18 kB
| """HTTP entry point for the MyVillage Activity Generation API.""" | |
| from contextlib import asynccontextmanager | |
| import hmac | |
| import logging | |
| import uuid | |
| from fastapi import Depends, FastAPI, Header, HTTPException, Request | |
| from fastapi.responses import JSONResponse | |
| import httpx | |
| from app.config import Settings | |
| from app.models import ActivityRequest, ActivityResponse | |
| from app.pipeline import ActivityPipeline, PipelineError | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") | |
| logger = logging.getLogger("activity_generation") | |
| def create_app(settings: Settings | None = None, transport: httpx.AsyncBaseTransport | None = None) -> FastAPI: | |
| config = settings or Settings.from_env() | |
| config.validate() | |
| async def lifespan(app: FastAPI): | |
| timeout = httpx.Timeout(connect=20.0, read=config.read_timeout_seconds, write=30.0, pool=20.0) | |
| # Send HF_TOKEN only to your own configured Spaces. Do not print it. | |
| headers = {"Authorization": f"Bearer {config.hf_token}"} if config.hf_token else {} | |
| async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers, transport=transport) as client: | |
| app.state.pipeline = ActivityPipeline(config, client) | |
| yield | |
| app = FastAPI( | |
| title="MyVillage Activity Generation API", | |
| description="One endpoint that orchestrates Progression → Composition → Instruction models.", | |
| version="1.0.0", | |
| lifespan=lifespan, | |
| ) | |
| async def index(): | |
| return {"service": "MyVillage Activity Generation API", "docs": "/docs", "health": "/health"} | |
| async def health(): | |
| # Liveness only: this does not wake or ping any GPU/CPU model Spaces. | |
| return {"status": "ok"} | |
| async def authorize(x_api_key: str | None = Header(default=None)) -> None: | |
| if config.api_key and (not x_api_key or not hmac.compare_digest(x_api_key, config.api_key)): | |
| raise HTTPException(status_code=401, detail="Invalid or missing X-API-Key") | |
| async def generate_activity(request: ActivityRequest, http_request: Request, _: None = Depends(authorize)): | |
| request_id = uuid.uuid4().hex | |
| logger.info("request_id=%s activity_generation=start", request_id) | |
| try: | |
| result = await http_request.app.state.pipeline.generate(request) | |
| logger.info("request_id=%s activity_generation=completed", request_id) | |
| return result | |
| except PipelineError as exc: | |
| logger.error("request_id=%s stage=%s code=%s", request_id, exc.stage, exc.code) | |
| # The response never contains private inputs or intermediate outputs. | |
| return JSONResponse(status_code=exc.status_code, content={"detail": exc.public_detail()}, headers={"X-Request-ID": request_id}) | |
| return app | |
| app = create_app() | |