""" Entrypoint for the Hugging Face Space. FastAPI serves the REST API under /api/* so a static React frontend (deployed on Vercel) can call every feature. All inference, OCR and third-party API work happens here in the Space; the frontend only renders the JSON responses. The existing Gradio demo stays mounted at / as a live preview of the Space. """ from __future__ import annotations import os import sys from pathlib import Path # The Space runs captioning on CPU so public visitors don't need an HF token or # spend ZeroGPU quota. A Space variable can override this if GPU is wanted. os.environ.setdefault("CAPTION_DEVICE", "cpu") import gradio as gr import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware ROOT_DIR = Path(__file__).resolve().parent BACKEND_DIR = ROOT_DIR / "backend" if str(BACKEND_DIR) not in sys.path: sys.path.insert(0, str(BACKEND_DIR)) # Importing app_gradio loads the services exactly once (weights, OCR, LLM). # Its module-level objects are reused below, so models are never loaded twice. from backend.app_gradio import ( # noqa: E402 caption_service, demo, plant_service, prescription_service, product_label_service, ) from backend.app.routes import ( # noqa: E402 caption, health, plant, prescription, product_label, ) app = FastAPI( title="Vision AI API", version="1.0.0", description="Image captioning, prescription reading, food labels and plant identification.", ) # The frontend is served from a different origin (Vercel). There is no login # and no cookie, so allowing any origin is safe. Set CORS_ORIGINS to a comma # separated list of origins to restrict it later. _origins = [o.strip() for o in os.getenv("CORS_ORIGINS", "").split(",") if o.strip()] app.add_middleware( CORSMiddleware, allow_origins=_origins or ["*"], allow_credentials=bool(_origins), allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"], ) # The routes read their services from request.app.state. app.state.caption_service = caption_service app.state.prescription_service = prescription_service app.state.product_label_service = product_label_service app.state.plant_service = plant_service app.include_router(health.router) app.include_router(health.root_router) # GET /health alias app.include_router(caption.router) app.include_router(prescription.router) app.include_router(product_label.router) app.include_router(plant.router) # Keep the Space preview usable: Gradio at /, REST API at /api/*. # Routes registered above are matched before the Gradio mount. app = gr.mount_gradio_app(app, demo, path="/") if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))