from fastapi import FastAPI, UploadFile, File, Form, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse, JSONResponse, FileResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import os import tempfile from typing import Optional # Initialize FastAPI app = FastAPI() # CORS Policy: allow everything (because Hugging Face Spaces needs it open) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Static files and templates app.mount("/static", StaticFiles(directory="static"), name="static") app.mount("/resources", StaticFiles(directory="resources"), name="resources") templates = Jinja2Templates(directory="templates") # --- Serve Frontend --- @app.get("/", response_class=HTMLResponse) async def serve_home(request: Request): return templates.TemplateResponse("HomeS.html", {"request": request}) # --- API Endpoints that frontend needs --- @app.post("/summarize/") async def summarize_document_endpoint(file: UploadFile = File(...), length: str = Form("medium")): try: from app import summarize_api return await summarize_api(file, length) except Exception as e: return JSONResponse({"error": f"Summarization failed: {str(e)}"}, status_code=500) @app.post("/imagecaption/") async def caption_image_endpoint(file: UploadFile = File(...)): try: from appImage import caption_from_frontend return await caption_from_frontend(file) except Exception as e: return JSONResponse({"error": f"Image captioning failed: {str(e)}"}, status_code=500) # --- Serve generated audio/pdf files --- @app.get("/files/{filename}") async def serve_file(filename: str): path = os.path.join(tempfile.gettempdir(), filename) if os.path.exists(path): return FileResponse(path) return JSONResponse({"error": "File not found"}, status_code=404) # (Optional) Unified prediction endpoint — Only if you want @app.post("/predict") async def predict( file: UploadFile = File(...), option: str = Form(...), # "Summarize" or "Captioning" length: Optional[str] = Form(None) # Only for Summarize ): try: if option == "Summarize": return await summarize_document_endpoint(file, length or "medium") elif option == "Captioning": return await caption_image_endpoint(file) else: return JSONResponse({"error": "Invalid option"}, status_code=400) except Exception as e: return JSONResponse({"error": f"Prediction failed: {str(e)}"}, status_code=500)