Summarization / main.py
ikraamkb's picture
Update main.py
8888b75 verified
raw
history blame
2.41 kB
from fastapi import FastAPI, UploadFile, 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
app = FastAPI()
# CORS Configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Static assets
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/resources", StaticFiles(directory="resources"), name="resources")
# Templates
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(file: UploadFile = File(...), length: str = Form("medium")):
try:
from app import summarize_api
return await summarize_api(file, length)
except ImportError:
return JSONResponse(
{"error": "Summarization module not available"},
status_code=501
)
@app.post("/imagecaption/")
async def caption_image(file: UploadFile):
try:
from appImage import caption_from_frontend
return await caption_from_frontend(file)
except ImportError:
return JSONResponse(
{"error": "Image captioning module not available"},
status_code=501
)
@app.get("/files/{filename}")
async def serve_file(filename: str):
file_path = os.path.join(tempfile.gettempdir(), filename)
if os.path.exists(file_path):
return FileResponse(file_path)
return JSONResponse({"error": "File not found"}, status_code=404)
# Optional: Fallback endpoint if you want a single endpoint
@app.post("/predict")
async def predict(
file: UploadFile,
option: str = Form(...), # "Summarize" or "Captioning"
length: Optional[str] = Form(None) # Only for summarize
):
try:
if option == "Summarize":
return await summarize_document(file, length or "medium")
else:
return await caption_image(file)
except Exception as e:
return JSONResponse(
{"error": str(e)},
status_code=500
)