import pandas as pd import re import fitz import os import uuid import sys from fastapi import UploadFile from src.logger import logging from src.exception import CustomException from src.utils import cleanup_after_download, ensure_artifacts_directory # Import strict subject mapping and resolution helper from src.subject_mapping import SUBJECT_MAP, resolve_subject_code def get_lines_from_words(words, y_tolerance=4): """ Groups individual words into horizontal lines based on their vertical (Y) coordinates. Uses a moving average of the Y-center to handle slight pixel variations in PDFs. """ lines = [] # Sort words primarily by top Y coordinate, then left X coordinate sorted_words = sorted(words, key=lambda w: (w[1], w[0])) current_line = [] current_line_y_center = None for word in sorted_words: x0, y0, x1, y1, text, block_no, line_no, word_no = word word_y_center = (y0 + y1) / 2 if current_line_y_center is None: current_line_y_center = word_y_center current_line.append(word) elif abs(word_y_center - current_line_y_center) <= y_tolerance: current_line.append(word) # Update line center as a moving average current_line_y_center = (current_line_y_center * (len(current_line)-1) + word_y_center) / len(current_line) else: current_line.sort(key=lambda w: w[0]) lines.append(current_line) current_line = [word] current_line_y_center = word_y_center if current_line: current_line.sort(key=lambda w: w[0]) lines.append(current_line) return lines @cleanup_after_download(delay_seconds=60) def process_file_fast(ledger: UploadFile, exclude_common_subjects: bool = False): """ Extracts student academic records using coordinate-based column intersection. """ try: logging.info(f"Started coordinate-based extraction using PyMuPDF for file: {ledger.filename}") artifacts_dir = ensure_artifacts_directory() csv_path = os.path.join(artifacts_dir, f"cleaned_{uuid.uuid4().hex}.csv") all_student_records = [] # State variables to maintain current student across multiple lines/pages current_prn = None current_seat = None current_name = None current_subjects = {} pdf_document = fitz.open(stream=ledger.file.read(), filetype="pdf") # Tracks the X-coordinate center of the "Tot" (Total Marks) column tot_center_x = None # Sort subject map keys descending by length to catch "CA 101 - T" before just "CA 101" sorted_subject_codes = sorted(SUBJECT_MAP.keys(), key=len, reverse=True) for i, page in enumerate(pdf_document): logging.info(f"Processing Page {i + 1}...") words = page.get_text("words") if not words: continue # Dynamically locate the 'Tot' column header's X coordinate on this page for w in words: # Account for slight capitalization variations in OCR if w[4].strip().upper() in ["TOT", "TOTAL"]: tot_center_x = (w[0] + w[2]) / 2 break if tot_center_x is None: logging.warning(f"'Tot' column not found on page {i+1}. Relying on previous coordinate.") # Reconstruct the page visually using Y-coordinates lines = get_lines_from_words(words, y_tolerance=4) for line in lines: line_text = " ".join([w[4] for w in line]) # 1. DECOUPLED HEADER EXTRACTION prn_match = re.search(r'PRN[:\s]*(\d+)', line_text, re.IGNORECASE) seat_match = re.search(r'Seat No\.?[:\s]*([A-Z0-9]+)', line_text, re.IGNORECASE) name_match = re.search(r'NAME[:\s]*([A-Za-z\s]+?)(?:\s+Mother|\s+PRN|\s+Seat|$)', line_text, re.IGNORECASE) new_prn_found = prn_match.group(1) if prn_match else None # If a new PRN is detected, push the previous student to the final list and reset if new_prn_found and new_prn_found != current_prn: if current_prn is not None: all_student_records.append({ "PRN": current_prn, "Seat No": current_seat or "", "NAME": current_name or "", "Subjects": current_subjects }) current_prn = new_prn_found current_seat = None current_name = None current_subjects = {} if seat_match: current_seat = seat_match.group(1) if name_match: current_name = name_match.group(1).strip() # 2. STRICT COORDINATE-BASED MARKS EXTRACTION matched_subject = None if line: first_word_text = line[0][4].strip() resolved = resolve_subject_code(first_word_text) if resolved and resolved in SUBJECT_MAP: matched_subject = resolved else: for code in sorted_subject_codes: if line_text.upper().startswith(code.upper()): matched_subject = code break if matched_subject: if current_prn and tot_center_x is not None: # Find the specific text block closest to the 'Tot' column's X-center closest_word = None min_dist = float('inf') # Iterate through ALL words in the line (a multi-word subject spans several blocks) for w in line: w_center_x = (w[0] + w[2]) / 2 dist = abs(w_center_x - tot_center_x) if dist < min_dist: min_dist = dist closest_word = w[4] # Expanded tolerance to 50 pixels to account for the wider 2025 NEP layout columns if min_dist < 50 and closest_word: # Strip out any non-numeric noise marks_str = re.sub(r'[^\w]', '', closest_word) try: # Only assign if it's a valid integer marks = int(marks_str) current_subjects[matched_subject] = marks except ValueError: # Ignore FFF, AAA, or other non-integer string grades. pass # Catch the final student record after the loop finishes if current_prn is not None: all_student_records.append({ "PRN": current_prn, "Seat No": current_seat or "", "NAME": current_name or "", "Subjects": current_subjects }) if not all_student_records: raise ValueError("No student records were extracted from the PDF.") # Flatten records for DataFrame insertion flattened_records = [ {"PRN": r["PRN"], "NAME": r["NAME"], "Seat No": r["Seat No"], **r["Subjects"]} for r in all_student_records ] df = pd.DataFrame(flattened_records) df = df.fillna('').astype(str) df.to_csv(csv_path, index=False) logging.info(f"Coordinate-based extraction finished. CSV created with {len(df)} records at {csv_path}.") return csv_path except Exception as e: logging.critical(f"An error occurred in the fast processing function: {e}") raise CustomException(e, sys)