CoolFace
Apppublic

FacundoSander/PdfQA

sourceHugging Faceupdated 3y agoView on Hugging Face
1likes
api.py40 linesDownload Raw Back to root
1import os2import tempfile3from fastapi import FastAPI, File, UploadFile, Form, HTTPException4from fastapi.responses import FileResponse5from html import escape6from main import create_qa_object, get_answer, get_source_documents7from fastapi.staticfiles import StaticFiles8 9app = FastAPI()10 11app.mount("/static", StaticFiles(directory="static"), name="static")12 13@app.get("/")14async def get_index_html():15    try:16        return FileResponse("static/index.html")17    except FileNotFoundError:18        raise HTTPException(status_code=404, detail="File not found")19 20@app.post("/ask")21async def ask(api_key: str = Form(...), file: UploadFile = File(...), query: str = Form(...), chain_type: str = Form("stuff"), k: int = Form(2)):22    os.environ["OPENAI_API_KEY"] = api_key23 24    # Crea un archivo temporal y guarda el contenido del archivo subido25    with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:26        temp_file.write(await file.read())27        temp_file_path = temp_file.name28 29    # Utiliza el archivo temporal en las funciones30    qa = create_qa_object(temp_file_path, chain_type, k)31    answer = get_answer(qa, query)32    source = get_source_documents(qa, query)33 34    # Elimina el archivo temporal después de su uso35    os.remove(temp_file_path)36 37    escaped_source = escape(source)38 39    return {"answer": answer, "source": escaped_source}40