grading / main.py
Hammad712's picture
Update main.py
7fa9057 verified
raw
history blame
2.31 kB
import os
import shutil
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
from pdf_processor import extract_answers_from_pdf, evaluate_student
app = FastAPI()
# Directory to temporarily store uploaded files.
UPLOAD_DIR = "uploads"
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR)
@app.post("/extract/")
async def extract_pdf(file: UploadFile = File(...)):
"""
Endpoint to extract answers from a PDF file.
"""
try:
file_location = os.path.join(UPLOAD_DIR, file.filename)
with open(file_location, "wb") as f:
shutil.copyfileobj(file.file, f)
result = extract_answers_from_pdf(file_location)
return JSONResponse(content=result.model_dump())
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
if os.path.exists(file_location):
os.remove(file_location)
@app.post("/evaluate/")
async def evaluate_pdfs(answer_key_file: UploadFile = File(...), student_file: UploadFile = File(...)):
"""
Endpoint to evaluate student answers by comparing the answer key and student's answer PDFs.
"""
try:
answer_key_path = os.path.join(UPLOAD_DIR, answer_key_file.filename)
student_path = os.path.join(UPLOAD_DIR, student_file.filename)
with open(answer_key_path, "wb") as f:
shutil.copyfileobj(answer_key_file.file, f)
with open(student_path, "wb") as f:
shutil.copyfileobj(student_file.file, f)
# Extract answers from both PDFs.
answer_key_result = extract_answers_from_pdf(answer_key_path)
student_result = extract_answers_from_pdf(student_path)
# Evaluate the student answers.
evaluation = evaluate_student(answer_key_result, student_result)
return JSONResponse(content=evaluation.model_dump())
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
if os.path.exists(answer_key_path):
os.remove(answer_key_path)
if os.path.exists(student_path):
os.remove(student_path)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)