File size: 40,184 Bytes
b57ed91
3e64737
 
 
 
2c68bd8
3e64737
ce1eb3c
 
 
cd3e466
 
 
 
 
 
 
e881a6a
 
 
66cb301
ce1eb3c
 
9b7ad24
ce1eb3c
 
 
cd3e466
 
 
db322cc
 
 
 
a703d91
db322cc
 
 
cd3e466
 
 
 
ce1eb3c
db322cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e881a6a
db322cc
 
e881a6a
ce1eb3c
cd3e466
 
 
 
 
ce1eb3c
 
 
 
e581856
 
 
 
 
 
 
 
 
 
 
ce1eb3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e581856
 
 
ce1eb3c
 
 
e581856
66cb301
e881a6a
fcf1816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd3e466
fcf1816
cd3e466
 
fcf1816
 
 
 
 
 
 
 
cd3e466
 
fcf1816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e881a6a
f17f847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a703d91
f17f847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db322cc
 
f17f847
a703d91
f17f847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a703d91
 
 
 
 
 
 
 
e881a6a
db322cc
fcf1816
9b7ad24
e881a6a
 
 
 
 
 
 
 
 
 
 
db322cc
 
fcf1816
e881a6a
9b7ad24
0e95f56
9b7ad24
f17f847
db322cc
e881a6a
a703d91
db322cc
e881a6a
a703d91
e881a6a
f17f847
e881a6a
 
 
db322cc
9b7ad24
e881a6a
a703d91
9b7ad24
db322cc
 
fcf1816
db322cc
e881a6a
db322cc
9b7ad24
e881a6a
fcf1816
e881a6a
db322cc
9b7ad24
e881a6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcf1816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e95f56
db322cc
fcf1816
ce1eb3c
e581856
fcf1816
e581856
ce1eb3c
cd3e466
 
fcf1816
 
ce1eb3c
a703d91
db322cc
6f8fb84
e881a6a
fcf1816
6f8fb84
9b7ad24
 
 
 
fcf1816
6f8fb84
9b7ad24
e881a6a
fcf1816
 
 
 
9b7ad24
ce1eb3c
 
 
0e95f56
6f8fb84
ce1eb3c
 
 
a703d91
 
 
 
 
 
 
 
 
 
ce1eb3c
 
 
a703d91
 
 
 
 
 
 
 
 
 
ce1eb3c
 
 
a703d91
 
 
ce1eb3c
0e95f56
a703d91
 
 
 
 
 
 
 
 
ce1eb3c
a703d91
ce1eb3c
a703d91
 
ce1eb3c
a703d91
 
 
 
 
ce1eb3c
a703d91
 
 
 
 
ce1eb3c
a703d91
 
 
 
 
 
ce1eb3c
 
 
0e95f56
6f8fb84
ce1eb3c
 
 
a703d91
0e95f56
a703d91
 
 
 
 
 
 
 
 
ce1eb3c
e581856
ce1eb3c
 
a703d91
 
 
 
 
ce1eb3c
a703d91
 
ce1eb3c
 
a703d91
 
 
 
 
ce1eb3c
 
a703d91
 
ce1eb3c
a703d91
ce1eb3c
 
a703d91
6f8fb84
a703d91
 
ce1eb3c
a703d91
cd3e466
a703d91
 
ce1eb3c
a703d91
ce1eb3c
a703d91
ce1eb3c
a703d91
ce1eb3c
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e64737
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e64737
ce1eb3c
 
6f8fb84
ce1eb3c
 
 
a703d91
431b892
a703d91
 
ce1eb3c
a703d91
 
 
ce1eb3c
a703d91
 
ce1eb3c
a703d91
 
 
ce1eb3c
a703d91
 
 
ce1eb3c
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce1eb3c
 
a703d91
431b892
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e64737
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce1eb3c
a703d91
ce1eb3c
 
 
0e95f56
 
ce1eb3c
a703d91
 
ce1eb3c
a703d91
 
 
ce1eb3c
 
a703d91
 
 
 
 
 
 
ce1eb3c
 
a703d91
 
 
 
ce1eb3c
 
a703d91
 
 
 
 
 
 
 
 
ce1eb3c
 
a703d91
 
ce1eb3c
a703d91
 
 
ce1eb3c
a703d91
ce1eb3c
 
a703d91
 
 
 
 
ce1eb3c
a703d91
 
 
9cf39ac
a703d91
 
 
 
 
 
ce1eb3c
a703d91
 
 
 
 
 
ce1eb3c
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce1eb3c
a703d91
 
 
 
 
 
647dadd
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e95f56
a703d91
 
 
 
 
0e95f56
a703d91
 
 
 
 
 
 
 
 
 
0e95f56
a703d91
 
 
 
 
 
 
0e95f56
a703d91
 
 
 
 
 
 
 
ce1eb3c
e881a6a
a703d91
 
 
 
 
e881a6a
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
b6b0c94
a703d91
 
 
 
 
 
 
 
 
 
 
 
 
 
ce1eb3c
2c68bd8
ce1eb3c
6e6aad7
2c68bd8
ce1eb3c
 
db322cc
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
import gradio as gr
import pandas as pd
import json
import os
import re
from PyPDF2 import PdfReader
from collections import defaultdict
from typing import Dict, List, Optional, Tuple, Union
import html
from pathlib import Path
import fitz  # PyMuPDF for better PDF text extraction
import pytesseract
from PIL import Image
import io
import secrets
import string
from huggingface_hub import HfApi, HfFolder
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import time

# ========== CONFIGURATION ==========
PROFILES_DIR = "student_profiles"
ALLOWED_FILE_TYPES = [".pdf", ".png", ".jpg", ".jpeg"]
MAX_FILE_SIZE_MB = 5
MIN_AGE = 5
MAX_AGE = 120
SESSION_TOKEN_LENGTH = 32
HF_TOKEN = os.getenv("HF_TOKEN")

# Model configuration
MODEL_CHOICES = {
    "TinyLlama (Fastest)": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
    "Phi-2 (Balanced)": "microsoft/phi-2",
    "DeepSeek-V3 (Most Powerful)": "deepseek-ai/deepseek-llm-7b"
}
DEFAULT_MODEL = "TinyLlama (Fastest)"

# Initialize Hugging Face API
if HF_TOKEN:
    hf_api = HfApi(token=HF_TOKEN)
    HfFolder.save_token(HF_TOKEN)

# ========== OPTIMIZED MODEL LOADING ==========
class ModelLoader:
    def __init__(self):
        self.model = None
        self.tokenizer = None
        self.loaded = False
        self.loading = False
        self.error = None
        self.current_model = None
    
    def load_model(self, model_name, progress=gr.Progress()):
        """Lazy load the model with progress feedback"""
        if self.loaded and self.current_model == model_name:
            return self.model, self.tokenizer
            
        self.loading = True
        self.error = None
        try:
            progress(0, desc=f"Loading {model_name}...")
            
            # Clear previous model if any
            if self.model:
                del self.model
                del self.tokenizer
                torch.cuda.empty_cache()
            
            # Load tokenizer first
            self.tokenizer = AutoTokenizer.from_pretrained(
                MODEL_CHOICES[model_name],
                trust_remote_code=True
            )
            progress(0.3, desc="Loaded tokenizer...")
            
            # Load model with appropriate settings
            self.model = AutoModelForCausalLM.from_pretrained(
                MODEL_CHOICES[model_name],
                trust_remote_code=True,
                torch_dtype=torch.float16,
                device_map="auto" if torch.cuda.is_available() else None,
                low_cpu_mem_usage=True
            )
            
            progress(0.9, desc="Finalizing...")
            self.loaded = True
            self.current_model = model_name
            return self.model, self.tokenizer
            
        except Exception as e:
            self.error = str(e)
            print(f"Error loading model: {self.error}")
            return None, None
        finally:
            self.loading = False

# Initialize model loader
model_loader = ModelLoader()

# ========== UTILITY FUNCTIONS ==========
def generate_session_token() -> str:
    """Generate a random session token for user identification."""
    alphabet = string.ascii_letters + string.digits
    return ''.join(secrets.choice(alphabet) for _ in range(SESSION_TOKEN_LENGTH))

def sanitize_input(text: str) -> str:
    """Sanitize user input to prevent XSS and injection attacks."""
    return html.escape(text.strip())

def validate_name(name: str) -> str:
    """Validate name input."""
    name = name.strip()
    if not name:
        raise gr.Error("Name cannot be empty")
    if len(name) > 100:
        raise gr.Error("Name is too long (max 100 characters)")
    if any(c.isdigit() for c in name):
        raise gr.Error("Name cannot contain numbers")
    return name

def validate_age(age: Union[int, float, str]) -> int:
    """Validate and convert age input."""
    try:
        age_int = int(age)
        if not MIN_AGE <= age_int <= MAX_AGE:
            raise gr.Error(f"Age must be between {MIN_AGE} and {MAX_AGE}")
        return age_int
    except (ValueError, TypeError):
        raise gr.Error("Please enter a valid age number")

def validate_file(file_obj) -> None:
    """Validate uploaded file."""
    if not file_obj:
        raise gr.Error("No file uploaded")
    
    file_ext = os.path.splitext(file_obj.name)[1].lower()
    if file_ext not in ALLOWED_FILE_TYPES:
        raise gr.Error(f"Invalid file type. Allowed: {', '.join(ALLOWED_FILE_TYPES)}")
    
    file_size = os.path.getsize(file_obj.name) / (1024 * 1024)  # MB
    if file_size > MAX_FILE_SIZE_MB:
        raise gr.Error(f"File too large. Max size: {MAX_FILE_SIZE_MB}MB")

# ========== TEXT EXTRACTION FUNCTIONS ==========
def extract_text_from_file(file_path: str, file_ext: str) -> str:
    """Enhanced text extraction with better error handling and fallbacks."""
    text = ""
    
    try:
        if file_ext == '.pdf':
            # First try PyMuPDF for better text extraction
            try:
                doc = fitz.open(file_path)
                for page in doc:
                    text += page.get_text("text") + '\n'
                if not text.strip():
                    raise ValueError("PyMuPDF returned empty text")
            except Exception as e:
                print(f"PyMuPDF failed, trying OCR fallback: {str(e)}")
                text = extract_text_from_pdf_with_ocr(file_path)
        
        elif file_ext in ['.png', '.jpg', '.jpeg']:
            text = extract_text_with_ocr(file_path)
            
        # Clean up the extracted text
        text = clean_extracted_text(text)
        
        if not text.strip():
            raise ValueError("No text could be extracted from the file")
            
        return text
    
    except Exception as e:
        raise gr.Error(f"Text extraction error: {str(e)}")

def extract_text_from_pdf_with_ocr(file_path: str) -> str:
    """Fallback PDF text extraction using OCR."""
    text = ""
    try:
        doc = fitz.open(file_path)
        for page in doc:
            pix = page.get_pixmap()
            img = Image.open(io.BytesIO(pix.tobytes()))
            text += pytesseract.image_to_string(img) + '\n'
    except Exception as e:
        raise ValueError(f"PDF OCR failed: {str(e)}")
    return text

def extract_text_with_ocr(file_path: str) -> str:
    """Extract text from image files using OCR with preprocessing."""
    try:
        image = Image.open(file_path)
        
        # Preprocess image for better OCR results
        image = image.convert('L')  # Convert to grayscale
        image = image.point(lambda x: 0 if x < 128 else 255, '1')  # Thresholding
        
        # Custom Tesseract configuration
        custom_config = r'--oem 3 --psm 6'
        text = pytesseract.image_to_string(image, config=custom_config)
        return text
    except Exception as e:
        raise ValueError(f"OCR processing failed: {str(e)}")

def clean_extracted_text(text: str) -> str:
    """Clean and normalize the extracted text."""
    # Remove multiple spaces and newlines
    text = re.sub(r'\s+', ' ', text).strip()
    
    # Fix common OCR errors
    replacements = {
        '|': 'I',
        '‘': "'",
        '’': "'",
        '“': '"',
        '”': '"',
        'fi': 'fi',
        'fl': 'fl'
    }
    
    for wrong, right in replacements.items():
        text = text.replace(wrong, right)
    
    return text

def remove_sensitive_info(text: str) -> str:
    """Remove potentially sensitive information from transcript text."""
    # Remove social security numbers
    text = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[REDACTED]', text)
    # Remove student IDs (assuming 6-9 digit numbers)
    text = re.sub(r'\b\d{6,9}\b', '[ID]', text)
    # Remove email addresses
    text = re.sub(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', '[EMAIL]', text)
    return text

# ========== TRANSCRIPT PARSING ==========
class TranscriptParser:
    def __init__(self):
        self.student_data = {}
        self.requirements = {}
        self.current_courses = []
        self.course_history = []
        
    def parse_transcript(self, text: str) -> Dict:
        """Main method to parse transcript text"""
        self._extract_student_info(text)
        self._extract_requirements(text)
        self._extract_course_history(text)
        self._extract_current_courses(text)
        
        return {
            "student_info": self.student_data,
            "requirements": self.requirements,
            "current_courses": self.current_courses,
            "course_history": self.course_history,
            "completion_status": self._calculate_completion()
        }
    
    def _extract_student_info(self, text: str):
        """Extract student personal information"""
        header_match = re.search(
            r"(\d{7}) - ([\w\s,]+)\s*\|\s*Cohort \w+\s*\|\s*Un-weighted GPA ([\d.]+)\s*\|\s*Comm Serv Hours (\d+)",
            text
        )
        if header_match:
            self.student_data = {
                "id": header_match.group(1),
                "name": header_match.group(2).strip(),
                "unweighted_gpa": float(header_match.group(3)),
                "community_service_hours": int(header_match.group(4))
            }
        
        # Extract additional info
        grade_match = re.search(
            r"Current Grade: (\d+)\s*\|\s*YOG (\d{4})\s*\|\s*Weighted GPA ([\d.]+)\s*\|\s*Comm Serv Date \d{2}/\d{2}/\d{4}\s*\|\s*Total Credits Earned ([\d.]+)",
            text
        )
        if grade_match:
            self.student_data.update({
                "current_grade": grade_match.group(1),
                "graduation_year": grade_match.group(2),
                "weighted_gpa": float(grade_match.group(3)),
                "total_credits": float(grade_match.group(4))
            })
    
    def _extract_requirements(self, text: str):
        """Parse the graduation requirements section"""
        req_table = re.findall(
            r"\|([A-Z]-[\w\s]+)\s*\|([^\|]+)\|([\d.]+)\s*\|([\d.]+)\s*\|([\d.]+)\s*\|([^\|]+)\|",
            text
        )
        
        for row in req_table:
            req_name = row[0].strip()
            self.requirements[req_name] = {
                "required": float(row[2]),
                "completed": float(row[4]),
                "status": f"{row[5].strip()}%"
            }
    
    def _extract_course_history(self, text: str):
        """Parse the detailed course history"""
        course_lines = re.findall(
            r"\|([A-Z]-[\w\s&\(\)]+)\s*\|(\d{4}-\d{4})\s*\|(\d{2})\s*\|([A-Z0-9]+)\s*\|([^\|]+)\|([^\|]+)\|([^\|]+)\|([A-Z])\s*\|([YRXW]?)\s*\|([^\|]+)\|",
            text
        )
        
        for course in course_lines:
            self.course_history.append({
                "requirement_category": course[0].strip(),
                "school_year": course[1],
                "grade_level": course[2],
                "course_code": course[3],
                "description": course[4].strip(),
                "term": course[5].strip(),
                "district_number": course[6].strip(),
                "grade": course[7],
                "inclusion_status": course[8],
                "credits": course[9].strip()
            })
    
    def _extract_current_courses(self, text: str):
        """Identify courses currently in progress"""
        in_progress = [c for c in self.course_history if "inProgress" in c["credits"]]
        self.current_courses = [
            {
                "course": c["description"],
                "category": c["requirement_category"],
                "term": c["term"],
                "credits": c["credits"]
            }
            for c in in_progress
        ]
    
    def _calculate_completion(self) -> Dict:
        """Calculate overall completion status"""
        total_required = sum(req["required"] for req in self.requirements.values())
        total_completed = sum(req["completed"] for req in self.requirements.values())
        
        return {
            "total_required": total_required,
            "total_completed": total_completed,
            "percent_complete": round((total_completed / total_required) * 100, 1),
            "remaining_credits": total_required - total_completed
        }
    
    def to_json(self) -> str:
        """Export parsed data as JSON"""
        return json.dumps({
            "student_info": self.student_data,
            "requirements": self.requirements,
            "current_courses": self.current_courses,
            "course_history": self.course_history,
            "completion_status": self._calculate_completion()
        }, indent=2)

def parse_transcript_with_ai(text: str, progress=gr.Progress()) -> Dict:
    """Use AI model to parse transcript text with progress feedback"""
    try:
        # First try structured parsing
        progress(0.1, desc="Parsing transcript structure...")
        parser = TranscriptParser()
        parsed_data = parser.parse_transcript(text)
        progress(0.9, desc="Formatting results...")
        
        # Convert to expected format
        formatted_data = {
            "grade_level": parsed_data["student_info"].get("current_grade", "Unknown"),
            "gpa": {
                "weighted": parsed_data["student_info"].get("weighted_gpa", "N/A"),
                "unweighted": parsed_data["student_info"].get("unweighted_gpa", "N/A")
            },
            "courses": []
        }
        
        # Add courses
        for course in parsed_data["course_history"]:
            formatted_data["courses"].append({
                "code": course["course_code"],
                "name": course["description"],
                "grade": course["grade"],
                "credits": course["credits"],
                "year": course["school_year"],
                "grade_level": course["grade_level"]
            })
        
        progress(1.0)
        return validate_parsed_data(formatted_data)
    
    except Exception as e:
        print(f"Structured parsing failed, falling back to AI: {str(e)}")
        # Fall back to AI parsing if structured parsing fails
        return parse_transcript_with_ai_fallback(text, progress)

def parse_transcript_with_ai_fallback(text: str, progress=gr.Progress()) -> Dict:
    """Fallback AI parsing method when structured parsing fails"""
    # Ensure model is loaded
    if not model_loader.loaded:
        model_loader.load_model(model_loader.current_model or DEFAULT_MODEL, progress)
    
    if not model_loader.model or not model_loader.tokenizer:
        raise gr.Error("AI model failed to load. Please try again or select a different model.")
    
    # Pre-process the text
    text = remove_sensitive_info(text[:15000])  # Limit input size
    
    prompt = f"""
    Analyze this academic transcript and extract structured information:
    - Current grade level
    - Weighted GPA (if available)
    - Unweighted GPA (if available)
    - List of all courses with:
      * Course code
      * Course name
      * Grade received
      * Credits earned
      * Year/semester taken
      * Grade level when taken
    Return the data in JSON format.
    
    Transcript Text:
    {text}
    """
    
    try:
        progress(0.1, desc="Processing transcript with AI...")
        
        # Tokenize and generate response
        inputs = model_loader.tokenizer(prompt, return_tensors="pt").to(model_loader.model.device)
        progress(0.4)
        
        outputs = model_loader.model.generate(
            **inputs,
            max_new_tokens=1500,
            temperature=0.1,
            do_sample=True
        )
        progress(0.8)
        
        # Decode the response
        response = model_loader.tokenizer.decode(outputs[0], skip_special_tokens=True)
        
        # Extract JSON from response
        json_str = response.split('```json')[1].split('```')[0].strip() if '```json' in response else response
        
        # Parse and validate
        parsed_data = json.loads(json_str)
        progress(1.0)
        
        return validate_parsed_data(parsed_data)
    
    except torch.cuda.OutOfMemoryError:
        raise gr.Error("The model ran out of memory. Try with a smaller transcript or use a smaller model.")
    except Exception as e:
        raise gr.Error(f"Error processing transcript: {str(e)}")

def validate_parsed_data(data: Dict) -> Dict:
    """Validate and clean the parsed data structure."""
    if not isinstance(data, dict):
        raise ValueError("Invalid data format")
    
    # Set default structure if missing
    if 'grade_level' not in data:
        data['grade_level'] = 'Unknown'
    
    if 'gpa' not in data:
        data['gpa'] = {'weighted': 'N/A', 'unweighted': 'N/A'}
    
    if 'courses' not in data:
        data['courses'] = []
    
    # Clean course data
    for course in data['courses']:
        if 'grade' in course:
            course['grade'] = course['grade'].upper().strip()
        
        # Ensure numeric credits are strings
        if 'credits' in course and isinstance(course['credits'], (int, float)):
            course['credits'] = str(course['credits'])
    
    return data

def format_transcript_output(data: Dict) -> str:
    """Format the parsed data into human-readable text."""
    output = []
    output.append(f"Student Transcript Summary\n{'='*40}")
    output.append(f"Current Grade Level: {data.get('grade_level', 'Unknown')}")
    
    if 'gpa' in data:
        output.append(f"\nGPA:")
        output.append(f"- Weighted: {data['gpa'].get('weighted', 'N/A')}")
        output.append(f"- Unweighted: {data['gpa'].get('unweighted', 'N/A')}")
    
    if 'courses' in data:
        output.append("\nCourse History:\n" + '='*40)
        
        # Group courses by grade level
        courses_by_grade = defaultdict(list)
        for course in data['courses']:
            grade_level = course.get('grade_level', 'Unknown')
            courses_by_grade[grade_level].append(course)
        
        # Sort grades numerically
        for grade in sorted(courses_by_grade.keys(), key=lambda x: int(x) if x.isdigit() else x):
            output.append(f"\nGrade {grade}:\n{'-'*30}")
            for course in courses_by_grade[grade]:
                course_str = f"- {course.get('code', '')} {course.get('name', 'Unnamed course')}"
                if 'grade' in course:
                    course_str += f" (Grade: {course['grade']})"
                if 'credits' in course:
                    course_str += f" | Credits: {course['credits']}"
                if 'year' in course:
                    course_str += f" | Year: {course['year']}"
                output.append(course_str)
    
    return '\n'.join(output)

def parse_transcript(file_obj, progress=gr.Progress()) -> Tuple[str, Optional[Dict]]:
    """Main function to parse transcript files."""
    try:
        if not file_obj:
            raise ValueError("Please upload a file first")
            
        validate_file(file_obj)
        file_ext = os.path.splitext(file_obj.name)[1].lower()
        
        # Extract text from file
        text = extract_text_from_file(file_obj.name, file_ext)
        
        # Use hybrid parsing approach
        parsed_data = parse_transcript_with_ai(text, progress)
        
        # Format output text
        output_text = format_transcript_output(parsed_data)
        
        # Prepare the data structure for saving
        transcript_data = {
            "grade_level": parsed_data.get('grade_level', 'Unknown'),
            "gpa": parsed_data.get('gpa', {}),
            "courses": defaultdict(list)
        }
        
        # Organize courses by grade level
        for course in parsed_data.get('courses', []):
            grade_level = course.get('grade_level', 'Unknown')
            transcript_data["courses"][grade_level].append(course)
        
        return output_text, transcript_data
    
    except Exception as e:
        return f"Error processing transcript: {str(e)}", None

# ========== LEARNING STYLE QUIZ ==========
class LearningStyleQuiz:
    def __init__(self):
        self.questions = [
            "When learning something new, I prefer to:",
            "I remember information best when I:",
            "When giving directions, I:",
            "When I have to concentrate, I'm most distracted by:",
            "I prefer to get new information in:",
            "When I'm trying to recall something, I:",
            "When I'm angry, I tend to:",
            "I tend to:",
            "When I meet someone new, I remember:",
            "When I'm relaxing, I prefer to:"
        ]
        
        self.options = [
            ["See diagrams and charts", "Listen to an explanation", "Try it out myself"],
            ["See pictures or diagrams", "Hear someone explain it", "Do something with it"],
            ["Draw a map", "Give verbal instructions", "Show them how to get there"],
            ["Untidiness or movement", "Noises", "Other people moving around"],
            ["Written form", "Spoken form", "Demonstration form"],
            ["See a mental picture", "Repeat it to myself", "Feel it or move my hands"],
            ["Visualize the incident", "Shout and yell", "Stomp around and slam doors"],
            ["Talk to myself", "Use my hands when talking", "Move around a lot"],
            ["Their face", "Their name", "Something we did together"],
            ["Watch TV or read", "Listen to music or talk", "Do something active"]
        ]
        
        self.learning_styles = {
            "Visual": "You learn best through seeing. Use visual aids like diagrams, charts, and color-coding.",
            "Auditory": "You learn best through listening. Record lectures, discuss concepts, and use rhymes or songs.",
            "Kinesthetic": "You learn best through movement and touch. Use hands-on activities and take frequent breaks."
        }
    
    def get_quiz_questions(self) -> List[Dict]:
        """Return formatted questions for the quiz interface"""
        return [
            {"question": q, "options": opts} 
            for q, opts in zip(self.questions, self.options)
        ]
    
    def calculate_learning_style(self, answers: List[int]) -> Dict:
        """Calculate the learning style based on user answers"""
        if len(answers) != len(self.questions):
            raise ValueError("Invalid number of answers")
        
        style_counts = {"Visual": 0, "Auditory": 0, "Kinesthetic": 0}
        style_map = {0: "Visual", 1: "Auditory", 2: "Kinesthetic"}
        
        for answer in answers:
            if answer not in [0, 1, 2]:
                raise ValueError("Invalid answer value")
            style = style_map[answer]
            style_counts[style] += 1
        
        primary_style = max(style_counts, key=style_counts.get)
        secondary_styles = [
            style for style, count in style_counts.items() 
            if style != primary_style and count > 0
        ]
        
        return {
            "primary": primary_style,
            "secondary": secondary_styles,
            "description": self.learning_styles[primary_style],
            "scores": style_counts
        }

# Initialize quiz instance
learning_style_quiz = LearningStyleQuiz()

# ========== PROFILE MANAGEMENT ==========
class ProfileManager:
    def __init__(self):
        self.profiles_dir = Path(PROFILES_DIR)
        self.profiles_dir.mkdir(exist_ok=True)
    
    def create_profile(
        self,
        name: str,
        age: int,
        grade_level: str,
        learning_style: Dict,
        transcript_data: Optional[Dict] = None
    ) -> str:
        """Create a new student profile with all collected data"""
        try:
            name = validate_name(name)
            age = validate_age(age)
            
            profile_id = f"{name.lower().replace(' ', '_')}_{age}"
            profile_path = self.profiles_dir / f"{profile_id}.json"
            
            if profile_path.exists():
                raise ValueError("Profile already exists")
            
            profile_data = {
                "id": profile_id,
                "name": name,
                "age": age,
                "grade_level": grade_level,
                "learning_style": learning_style,
                "transcript": transcript_data or {},
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "updated_at": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            
            with open(profile_path, 'w') as f:
                json.dump(profile_data, f, indent=2)
            
            return profile_id
            
        except Exception as e:
            raise gr.Error(f"Error creating profile: {str(e)}")
    
    def get_profile(self, profile_id: str) -> Dict:
        """Retrieve a student profile by ID"""
        try:
            profile_path = self.profiles_dir / f"{profile_id}.json"
            
            if not profile_path.exists():
                raise ValueError("Profile not found")
            
            with open(profile_path, 'r') as f:
                return json.load(f)
                
        except Exception as e:
            raise gr.Error(f"Error loading profile: {str(e)}")
    
    def update_profile(self, profile_id: str, updates: Dict) -> Dict:
        """Update an existing profile with new data"""
        try:
            profile = self.get_profile(profile_id)
            profile.update(updates)
            profile["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
            
            profile_path = self.profiles_dir / f"{profile_id}.json"
            with open(profile_path, 'w') as f:
                json.dump(profile, f, indent=2)
            
            return profile
            
        except Exception as e:
            raise gr.Error(f"Error updating profile: {str(e)}")
    
    def list_profiles(self) -> List[Dict]:
        """List all available student profiles"""
        try:
            profiles = []
            for file in self.profiles_dir.glob("*.json"):
                with open(file, 'r') as f:
                    profile = json.load(f)
                    profiles.append({
                        "id": profile["id"],
                        "name": profile["name"],
                        "age": profile["age"],
                        "grade_level": profile["grade_level"],
                        "created_at": profile["created_at"]
                    })
            return sorted(profiles, key=lambda x: x["name"])
        except Exception as e:
            raise gr.Error(f"Error listing profiles: {str(e)}")

# Initialize profile manager
profile_manager = ProfileManager()

# ========== AI TEACHING ASSISTANT ==========
class TeachingAssistant:
    def __init__(self):
        self.model_loader = model_loader
    
    def generate_study_plan(self, profile_data: Dict, progress=gr.Progress()) -> str:
        """Generate a personalized study plan based on student profile"""
        try:
            # Ensure model is loaded
            if not self.model_loader.loaded:
                self.model_loader.load_model(DEFAULT_MODEL, progress)
            
            learning_style = profile_data.get("learning_style", {})
            transcript = profile_data.get("transcript", {})
            
            # Prepare prompt
            prompt = f"""
            Create a personalized study plan for {profile_data['name']}, a {profile_data['age']}-year-old student in grade {profile_data['grade_level']}.
            
            Learning Style:
            - Primary: {learning_style.get('primary', 'Unknown')}
            - Description: {learning_style.get('description', 'No learning style information')}
            
            Academic History:
            - Current GPA: {transcript.get('gpa', {}).get('weighted', 'N/A')} (weighted)
            - Courses Completed: {len(transcript.get('courses', []))}
            
            Focus on study techniques that match the student's learning style and provide specific recommendations based on their academic history.
            Include:
            1. Daily study routine suggestions
            2. Subject-specific strategies
            3. Recommended resources
            4. Time management tips
            5. Any areas that need improvement
            
            Format the response with clear headings and bullet points.
            """
            
            progress(0.2, desc="Generating study plan...")
            
            # Generate response
            inputs = self.model_loader.tokenizer(prompt, return_tensors="pt").to(self.model_loader.model.device)
            outputs = self.model_loader.model.generate(
                **inputs,
                max_new_tokens=1000,
                temperature=0.7,
                do_sample=True
            )
            
            progress(0.8, desc="Formatting response...")
            
            response = self.model_loader.tokenizer.decode(outputs[0], skip_special_tokens=True)
            return self._format_response(response)
            
        except Exception as e:
            raise gr.Error(f"Error generating study plan: {str(e)}")
    
    def answer_question(self, question: str, context: str = "", progress=gr.Progress()) -> str:
        """Answer student questions with optional context"""
        try:
            if not question.strip():
                return "Please ask a question."
                
            # Ensure model is loaded
            if not self.model_loader.loaded:
                self.model_loader.load_model(DEFAULT_MODEL, progress)
            
            prompt = f"""
            Answer the following student question in a helpful, educational manner.
            {f"Context: {context}" if context else ""}
            
            Question: {question}
            
            Provide a clear, concise answer with examples if helpful. Break down complex concepts.
            If the question is unclear, ask for clarification.
            """
            
            progress(0.3, desc="Processing question...")
            
            # Generate response
            inputs = self.model_loader.tokenizer(prompt, return_tensors="pt").to(self.model_loader.model.device)
            outputs = self.model_loader.model.generate(
                **inputs,
                max_new_tokens=500,
                temperature=0.5,
                do_sample=True
            )
            
            progress(0.8, desc="Formatting answer...")
            
            response = self.model_loader.tokenizer.decode(outputs[0], skip_special_tokens=True)
            return self._format_response(response)
            
        except Exception as e:
            raise gr.Error(f"Error answering question: {str(e)}")
    
    def _format_response(self, text: str) -> str:
        """Format the AI response for better readability"""
        # Clean up common artifacts
        text = text.replace("<|endoftext|>", "").strip()
        
        # Add markdown formatting if not present
        if "#" not in text and "**" not in text:
            # Split into paragraphs and add headings
            sections = text.split("\n\n")
            formatted = []
            for section in sections:
                if section.strip().endswith(":"):
                    formatted.append(f"**{section}**")
                else:
                    formatted.append(section)
            text = "\n\n".join(formatted)
        
        return text

# Initialize teaching assistant
teaching_assistant = TeachingAssistant()

# ========== GRADIO INTERFACE ==========
def create_interface():
    with gr.Blocks(title="Student Profile Assistant", theme="soft") as app:
        session_token = gr.State(generate_session_token())
        
        # Tab navigation
        with gr.Tabs():
            with gr.Tab("Profile Creation"):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("## Student Information")
                        name_input = gr.Textbox(label="Full Name", placeholder="Enter student's full name")
                        age_input = gr.Number(label="Age", minimum=MIN_AGE, maximum=MAX_AGE, step=1)
                        grade_level = gr.Dropdown(
                            label="Grade Level",
                            choices=["9", "10", "11", "12", "Other"],
                            value="9"
                        )
                        
                        gr.Markdown("## Transcript Upload")
                        file_upload = gr.File(label="Upload Transcript", file_types=ALLOWED_FILE_TYPES)
                        parse_btn = gr.Button("Parse Transcript")
                        transcript_output = gr.Textbox(label="Transcript Summary", interactive=False, lines=10)
                        
                    with gr.Column(scale=1):
                        gr.Markdown("## Learning Style Quiz")
                        quiz_components = []
                        for i, question in enumerate(learning_style_quiz.questions):
                            quiz_components.append(
                                gr.Radio(
                                    label=question,
                                    choices=learning_style_quiz.options[i],
                                    type="index"
                                )
                            )
                        
                        quiz_submit = gr.Button("Submit Quiz")
                        learning_style_output = gr.JSON(label="Learning Style Results")
                        
                        gr.Markdown("## Complete Profile")
                        create_profile_btn = gr.Button("Create Profile")
                        profile_status = gr.Textbox(label="Profile Status", interactive=False)
            
            with gr.Tab("Study Tools"):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("## Study Plan Generator")
                        profile_selector = gr.Dropdown(
                            label="Select Profile",
                            choices=[p["id"] for p in profile_manager.list_profiles()],
                            interactive=True
                        )
                        refresh_profiles = gr.Button("Refresh Profiles")
                        study_plan_btn = gr.Button("Generate Study Plan")
                        study_plan_output = gr.Markdown(label="Personalized Study Plan")
                    
                    with gr.Column(scale=1):
                        gr.Markdown("## Ask the Teaching Assistant")
                        question_input = gr.Textbox(label="Your Question", lines=3)
                        context_input = gr.Textbox(label="Additional Context (optional)", lines=2)
                        ask_btn = gr.Button("Ask Question")
                        answer_output = gr.Markdown(label="Answer")
            
            with gr.Tab("Profile Management"):
                gr.Markdown("## Existing Profiles")
                profile_table = gr.Dataframe(
                    headers=["Name", "Age", "Grade Level", "Created At"],
                    datatype=["str", "number", "str", "str"],
                    interactive=False
                )
                refresh_table = gr.Button("Refresh Profiles")
                
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("## Profile Details")
                        selected_profile = gr.Dropdown(
                            label="Select Profile",
                            choices=[p["id"] for p in profile_manager.list_profiles()],
                            interactive=True
                        )
                        view_profile_btn = gr.Button("View Profile")
                        profile_display = gr.JSON(label="Profile Data")
                    
                    with gr.Column():
                        gr.Markdown("## Update Profile")
                        update_grade = gr.Dropdown(
                            label="Update Grade Level",
                            choices=["9", "10", "11", "12", "Other"],
                            interactive=True
                        )
                        update_transcript = gr.File(label="Update Transcript", file_types=ALLOWED_FILE_TYPES)
                        update_btn = gr.Button("Update Profile")
                        update_status = gr.Textbox(label="Update Status", interactive=False)
        
        # ========== EVENT HANDLERS ==========
        # Transcript parsing
        parse_btn.click(
            parse_transcript,
            inputs=[file_upload],
            outputs=[transcript_output, gr.State()],
            show_progress=True
        )
        
        # Learning style quiz
        quiz_submit.click(
            learning_style_quiz.calculate_learning_style,
            inputs=quiz_components,
            outputs=learning_style_output
        )
        
        # Profile creation
        create_profile_btn.click(
            profile_manager.create_profile,
            inputs=[
                name_input,
                age_input,
                grade_level,
                learning_style_output,
                gr.State()
            ],
            outputs=profile_status
        ).then(
            lambda: [p["id"] for p in profile_manager.list_profiles()],
            outputs=profile_selector
        ).then(
            lambda: [p["id"] for p in profile_manager.list_profiles()],
            outputs=selected_profile
        ).then(
            lambda: profile_manager.list_profiles(),
            outputs=profile_table
        )
        
        # Study tools
        refresh_profiles.click(
            lambda: [p["id"] for p in profile_manager.list_profiles()],
            outputs=profile_selector
        )
        
        study_plan_btn.click(
            lambda profile_id: profile_manager.get_profile(profile_id),
            inputs=profile_selector,
            outputs=gr.State()
        ).then(
            teaching_assistant.generate_study_plan,
            inputs=gr.State(),
            outputs=study_plan_output,
            show_progress=True
        )
        
        # Teaching assistant
        ask_btn.click(
            teaching_assistant.answer_question,
            inputs=[question_input, context_input],
            outputs=answer_output,
            show_progress=True
        )
        
        # Profile management
        refresh_table.click(
            lambda: profile_manager.list_profiles(),
            outputs=profile_table
        ).then(
            lambda: [p["id"] for p in profile_manager.list_profiles()],
            outputs=selected_profile
        )
        
        view_profile_btn.click(
            profile_manager.get_profile,
            inputs=selected_profile,
            outputs=profile_display
        )
        
        update_btn.click(
            lambda profile_id, grade, file_obj: (
                profile_manager.update_profile(
                    profile_id,
                    {"grade_level": grade}
                ) if not file_obj else None,
                parse_transcript(file_obj) if file_obj else (None, None)
            ),
            inputs=[selected_profile, update_grade, update_transcript],
            outputs=[profile_display, gr.State()]
        ).then(
            lambda: "Profile updated successfully!",
            outputs=update_status
        )
        
        # Initialization
        app.load(
            lambda: profile_manager.list_profiles(),
            outputs=profile_table
        ).then(
            lambda: [p["id"] for p in profile_manager.list_profiles()],
            outputs=profile_selector
        ).then(
            lambda: [p["id"] for p in profile_manager.list_profiles()],
            outputs=selected_profile
        )
        
        return app

# Create the interface
app = create_interface()

# For Hugging Face Spaces deployment
if __name__ == "__main__":
    app.launch()