File size: 8,529 Bytes
48322a4
 
 
 
 
 
 
 
 
 
 
dd45e7a
 
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f311640
 
 
48322a4
 
 
 
 
 
 
 
f311640
 
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f311640
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f311640
dd45e7a
 
 
 
 
 
 
 
 
 
48322a4
f311640
48322a4
 
 
 
 
f311640
 
48322a4
 
 
 
 
 
f311640
 
48322a4
 
 
 
 
f311640
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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)