# main.py from fastapi import FastAPI, UploadFile, File, Form, Request from fastapi.responses import HTMLResponse, JSONResponse, FileResponse from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from fastapi.templating import Jinja2Templates import tempfile, os from app_logic import extract_text, generate_summary, text_to_speech, create_pdf from app_image_logic import generate_caption app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"]) app.mount("/static", StaticFiles(directory="static"), name="static") app.mount("/resources", StaticFiles(directory="resources"), name="resources") templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def serve_home(request: Request): return templates.TemplateResponse("HomeS.html", {"request": request}) @app.post("/summarize/") async def summarize_document_endpoint(file: UploadFile = File(...), length: str = Form("medium")): contents = await file.read() with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.write(contents) tmp_path = tmp.name file_ext = file.filename.split('.')[-1].lower() text, error = extract_text(tmp_path, file_ext) if error: return JSONResponse({"detail": error}, status_code=400) if not text or len(text.split()) < 30: return JSONResponse({"detail": "Document too short to summarize"}, status_code=400) summary = generate_summary(text, length) audio_path = text_to_speech(summary) pdf_path = create_pdf(summary, file.filename) response = {"summary": summary} if audio_path: response["audioUrl"] = f"/files/{os.path.basename(audio_path)}" if pdf_path: response["pdfUrl"] = f"/files/{os.path.basename(pdf_path)}" return JSONResponse(response) @app.post("/imagecaption/") async def caption_image_endpoint(file: UploadFile = File(...)): contents = await file.read() with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp: tmp.write(contents) image_path = tmp.name caption = generate_caption(image_path) return JSONResponse({"caption": caption}) @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)