Spaces:
Running
Running
# main.py | |
from fastapi import FastAPI, UploadFile, File, Form, Request | |
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse | |
from fastapi.staticfiles import StaticFiles | |
from fastapi.templating import Jinja2Templates | |
from fastapi.middleware.cors import CORSMiddleware | |
import tempfile, os | |
from app import summarize_document | |
from appImage import caption_image | |
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") | |
# Serve homepage | |
async def serve_home(request: Request): | |
return templates.TemplateResponse("HomeS.html", {"request": request}) | |
# Document summarization endpoint | |
async def summarize_api(file: UploadFile = File(...), length: str = Form("medium")): | |
try: | |
contents = await file.read() | |
with tempfile.NamedTemporaryFile(delete=False) as tmp_file: | |
tmp_file.write(contents) | |
tmp_path = tmp_file.name | |
file_ext = tmp_path.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) | |
except Exception as e: | |
print(f"Error during summarization: {str(e)}") # << SUPER IMPORTANT FOR DEBUG | |
return JSONResponse({"detail": f"Internal server error: {str(e)}"}, status_code=500) | |
# Image captioning endpoint | |
async def caption(file: UploadFile = File(...)): | |
try: | |
result = await caption_image(file) | |
return JSONResponse(result) | |
except Exception as e: | |
return JSONResponse({"error": f"Image captioning failed: {str(e)}"}, status_code=500) | |
# Serve audio/pdf generated | |
async def serve_file(filename: str): | |
filepath = os.path.join(tempfile.gettempdir(), filename) | |
if os.path.exists(filepath): | |
return FileResponse(filepath) | |
return JSONResponse({"error": "File not found"}, status_code=404) | |