File size: 2,307 Bytes
7f269b9
7fa9057
7f269b9
7fa9057
 
7f269b9
7fa9057
7f269b9
7fa9057
 
 
 
7f269b9
7fa9057
 
 
 
 
7f269b9
7fa9057
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f269b9
 
7fa9057
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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)