MedhaCodes/Question-answering-APP
0
1from fastapi import FastAPI, Request2from fastapi.responses import HTMLResponse, JSONResponse3from fastapi.staticfiles import StaticFiles4from fastapi.templating import Jinja2Templates5from transformers import AutoTokenizer, AutoModelForQuestionAnswering, pipeline6import os7 8app = FastAPI(title="QA Dashboard Pro")9 10MODEL_PATH = "MedhaCodes/qna_finetuned_model"11 12qa_pipeline = pipeline(13 "question-answering",14 model=AutoModelForQuestionAnswering.from_pretrained(MODEL_PATH),15 tokenizer=AutoTokenizer.from_pretrained(MODEL_PATH)16)17 18# Mount static files (CSS, JS)19app.mount(20 "/static",21 StaticFiles(directory=os.path.join(os.path.dirname(__file__), "static")),22 name="static"23)24 25# Load templates26templates = Jinja2Templates(directory="templates")27 28@app.get("/", response_class=HTMLResponse)29async def home(request: Request):30 return templates.TemplateResponse("index.html", {"request": request})31 32@app.post("/predict")33async def predict(request: Request):34 data = await request.json()35 context = data.get("context")36 questions_text = data.get("question")37 38 if not context or not questions_text:39 return JSONResponse({"error": "Please provide both context and question"}, status_code=400)40 41 questions = [q.strip() for q in questions_text.strip().split("\n") if q.strip()]42 answers = []43 44 for i, q in enumerate(questions, start=1):45 try:46 result = qa_pipeline(question=q, context=context)47 answers.append({48 "question": q,49 "answer": result["answer"],50 "score": round(result["score"], 4)51 })52 except Exception as e:53 answers.append({"question": q, "answer": f"Error: {e}", "score": 0})54 55 return {"results": answers}56 