from fastapi import APIRouter, UploadFile, File, HTTPException, Form from typing import Dict import json from pathlib import Path import shutil import tempfile from modules.test_analyzer import TestAnalyzer, TestAnalysis from modules.pdf_utils import PDFUtils router = APIRouter() @router.post("/analyze", response_model=TestAnalysis) async def analyze_test( test_file: UploadFile = File(...), marks_data: str = Form(...), api_key: str = Form(...), mode: str = Form('detailed') ): """ Analyze a test PDF and generate feedback based on marks data """ try: print(f"Received request - Mode: {mode}") marks_data_dict = json.loads(marks_data) with tempfile.TemporaryDirectory() as temp_dir: temp_file = Path(temp_dir) / test_file.filename with temp_file.open("wb") as buffer: shutil.copyfileobj(test_file.file, buffer) print("File saved, initializing analyzer...") analyzer = TestAnalyzer(api_key=api_key) print("Extracting PDF content...") pdf_utils = PDFUtils() pdf_content = pdf_utils.extract_text_from_pdf(temp_file) print("Analyzing content...") analysis = analyzer.analyze_test(pdf_content, marks_data_dict, mode) print("Analysis complete") return analysis except json.JSONDecodeError as e: print(f"JSON decode error: {str(e)}") raise HTTPException(status_code=422, detail=f"Invalid marks_data JSON format: {str(e)}") except Exception as e: print(f"Error in analyze_test: {str(e)}") raise HTTPException(status_code=500, detail=str(e))