import os import tempfile import io import json import numpy as np import cv2 from PIL import Image from pdf2image import convert_from_bytes from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.responses import JSONResponse, StreamingResponse import uvicorn # Get API key from environment GENAI_API_KEY = os.getenv("GENAI_API_KEY") if not GENAI_API_KEY: raise Exception("GENAI_API_KEY not set in environment") # Import the Google GenAI client libraries. from google import genai from google.genai import types # Initialize the GenAI client with the API key. client = genai.Client(api_key=GENAI_API_KEY) app = FastAPI(title="Student Result Card API") # Use system temporary directory to store the results file. TEMP_FOLDER = tempfile.gettempdir() RESULT_FILE = os.path.join(TEMP_FOLDER, "result_cards.json") ############################################################## # Preprocessing & Extraction Functions ############################################################## def extract_json_from_output(output_str: str): """ Extracts a JSON object from a string containing extra text. """ start = output_str.find('{') end = output_str.rfind('}') if start == -1 or end == -1: print("No JSON block found in the output.") return None json_str = output_str[start:end+1] try: result = json.loads(json_str) return result except json.JSONDecodeError as e: print("Error decoding JSON:", e) return None def parse_all_answers(image_input: Image.Image) -> str: """ Extracts answers from an image of a 15-question answer sheet. Returns the response text (JSON string). """ output_format = """ Answer in the following JSON format. Do not write anything else: { "Answers": { "1": "