Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,86 +3,162 @@ import pandas as pd
|
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
import re
|
| 6 |
-
from PyPDF2 import PdfReader
|
| 7 |
from collections import defaultdict
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
# ==========
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
# ========== TRANSCRIPT PARSING ==========
|
| 21 |
-
def extract_gpa(text, gpa_type):
|
|
|
|
| 22 |
pattern = rf'{gpa_type}\s*([\d\.]+)'
|
| 23 |
match = re.search(pattern, text)
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
def extract_courses_from_table(text):
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
r'(\d{4}-\d{4})\s*' # School year
|
| 29 |
r'\|?\s*(\d+)\s*' # Grade level
|
| 30 |
r'\|?\s*([A-Z0-9]+)\s*' # Course code
|
| 31 |
-
r'\|?\s*([^\|]+?)\s*' # Course name
|
| 32 |
r'(?:\|\s*[^\|]*){2}' # Skip Term and DstNumber
|
| 33 |
r'\|\s*([A-FW]?)\s*' # Grade (FG column)
|
| 34 |
r'(?:\|\s*[^\|]*)' # Skip Incl column
|
| 35 |
r'\|\s*([\d\.]+|inProgress)' # Credits
|
| 36 |
)
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
courses_by_grade = defaultdict(list)
|
| 39 |
|
| 40 |
-
for
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
course_name = course_name.
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
if
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
courses_by_grade[grade_level].append(course_info)
|
| 59 |
|
| 60 |
return courses_by_grade
|
| 61 |
|
| 62 |
-
def parse_transcript(
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
| 64 |
text = ''
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
|
|
|
| 69 |
gpa_data = {
|
| 70 |
'weighted': extract_gpa(text, 'Weighted GPA'),
|
| 71 |
'unweighted': extract_gpa(text, 'Un-weighted GPA')
|
| 72 |
}
|
| 73 |
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
| 75 |
grade_level = grade_match.group(1) if grade_match else "Unknown"
|
| 76 |
|
| 77 |
courses_by_grade = extract_courses_from_table(text)
|
| 78 |
|
|
|
|
| 79 |
output_text = f"Student Transcript Summary\n{'='*40}\n"
|
| 80 |
output_text += f"Current Grade Level: {grade_level}\n"
|
| 81 |
output_text += f"Weighted GPA: {gpa_data['weighted']}\n"
|
| 82 |
output_text += f"Unweighted GPA: {gpa_data['unweighted']}\n\n"
|
| 83 |
output_text += "Course History:\n{'='*40}\n"
|
| 84 |
|
| 85 |
-
for grade in sorted(courses_by_grade.keys(), key=int):
|
| 86 |
output_text += f"\nGrade {grade}:\n{'-'*30}\n"
|
| 87 |
for course in courses_by_grade[grade]:
|
| 88 |
output_text += f"- {course['name']}"
|
|
@@ -97,355 +173,817 @@ def parse_transcript(file):
|
|
| 97 |
"grade_level": grade_level,
|
| 98 |
"courses": dict(courses_by_grade)
|
| 99 |
}
|
| 100 |
-
|
| 101 |
-
|
|
|
|
| 102 |
|
| 103 |
# ========== LEARNING STYLE QUIZ ==========
|
| 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 |
-
if
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
else:
|
| 204 |
-
result += "
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
result += "
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
# ========== PROFILE MANAGEMENT ==========
|
| 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 |
-
**Age:** {age}
|
| 249 |
-
**Interests:** {interests}
|
| 250 |
-
**Learning Style:** {learning_style}
|
| 251 |
-
#### Transcript:
|
| 252 |
-
{transcript_display(transcript)}
|
| 253 |
-
#### Favorites:
|
| 254 |
-
- Movie: {favorites['movie']} ({favorites['movie_reason']})
|
| 255 |
-
- Show: {favorites['show']} ({favorites['show_reason']})
|
| 256 |
-
- Book: {favorites['book']} ({favorites['book_reason']})
|
| 257 |
-
- Character: {favorites['character']} ({favorites['character_reason']})
|
| 258 |
-
#### Blog:
|
| 259 |
-
{blog if blog else "_No blog provided_"}
|
| 260 |
-
"""
|
| 261 |
-
return markdown_summary
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
if 'gpa' in transcript_dict:
|
| 282 |
-
gpa = transcript_dict['gpa']
|
| 283 |
-
display += "\n**GPA Information**\n"
|
| 284 |
-
display += f"- Unweighted: {gpa.get('unweighted', 'N/A')}\n"
|
| 285 |
-
display += f"- Weighted: {gpa.get('weighted', 'N/A')}\n"
|
| 286 |
|
| 287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
return {}
|
| 292 |
-
files = [f for f in os.listdir("student_profiles") if f.endswith('.json')]
|
| 293 |
-
if files:
|
| 294 |
-
with open(os.path.join("student_profiles", files[0]), "r") as f:
|
| 295 |
-
return json.load(f)
|
| 296 |
-
return {}
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
|
|
|
| 302 |
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
if "Visual" in learning_style:
|
| 320 |
response = ("Based on your visual learning style, I recommend:\n"
|
| 321 |
-
"- Creating mind maps or diagrams\n"
|
| 322 |
-
"- Using color-
|
| 323 |
-
"- Watching educational videos"
|
|
|
|
| 324 |
elif "Auditory" in learning_style:
|
| 325 |
response = ("Based on your auditory learning style, I recommend:\n"
|
| 326 |
-
"- Recording
|
| 327 |
-
"- Participating in study groups\n"
|
| 328 |
-
"- Explaining
|
|
|
|
| 329 |
elif "Reading/Writing" in learning_style:
|
| 330 |
response = ("Based on your reading/writing learning style, I recommend:\n"
|
| 331 |
-
"- Writing detailed
|
| 332 |
-
"- Creating
|
| 333 |
-
"- Reading textbooks
|
|
|
|
| 334 |
elif "Kinesthetic" in learning_style:
|
| 335 |
response = ("Based on your kinesthetic learning style, I recommend:\n"
|
| 336 |
-
"-
|
| 337 |
-
"-
|
| 338 |
-
"- Taking frequent movement breaks"
|
|
|
|
| 339 |
else:
|
| 340 |
response = ("Here are some general study tips:\n"
|
| 341 |
-
"-
|
| 342 |
-
"-
|
| 343 |
-
"-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
return response
|
| 346 |
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
response = "Here's a summary of your courses:\n"
|
| 364 |
-
for grade in sorted(courses.keys(), key=int):
|
| 365 |
-
response += f"\
|
| 366 |
for course in courses[grade]:
|
| 367 |
-
response += f"- {course
|
| 368 |
if 'grade' in course:
|
| 369 |
response += f" (Grade: {course['grade']})"
|
| 370 |
response += "\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
return response
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
# ========== GRADIO INTERFACE ==========
|
| 387 |
-
|
| 388 |
-
with gr.
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
)
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
quiz_components = []
|
| 402 |
-
for i, (question, options) in enumerate(zip(learning_style_questions, learning_style_options)):
|
| 403 |
-
quiz_components.append(gr.Radio(options, label=f"{i+1}. {question}"))
|
| 404 |
-
|
| 405 |
-
learning_output = gr.Textbox(label="Your Learning Style", lines=15)
|
| 406 |
-
gr.Button("Submit Quiz").click(
|
| 407 |
-
fn=learning_style_quiz,
|
| 408 |
-
inputs=quiz_components,
|
| 409 |
-
outputs=learning_output
|
| 410 |
)
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
age = gr.Number(label="How old are you?", precision=0)
|
| 415 |
-
interests = gr.Textbox(label="What are your interests?")
|
| 416 |
-
movie = gr.Textbox(label="Favorite movie?")
|
| 417 |
-
movie_reason = gr.Textbox(label="Why do you like that movie?")
|
| 418 |
-
show = gr.Textbox(label="Favorite TV show?")
|
| 419 |
-
show_reason = gr.Textbox(label="Why do you like that show?")
|
| 420 |
-
book = gr.Textbox(label="Favorite book?")
|
| 421 |
-
book_reason = gr.Textbox(label="Why do you like that book?")
|
| 422 |
-
character = gr.Textbox(label="Favorite character?")
|
| 423 |
-
character_reason = gr.Textbox(label="Why do you like that character?")
|
| 424 |
-
blog_checkbox = gr.Checkbox(label="Do you want to write a blog?", value=False)
|
| 425 |
-
blog_text = gr.Textbox(label="Write your blog here", visible=False, lines=5)
|
| 426 |
-
blog_checkbox.change(lambda x: gr.update(visible=x), inputs=blog_checkbox, outputs=blog_text)
|
| 427 |
-
|
| 428 |
-
with gr.Tab("Step 4: Save & Review"):
|
| 429 |
-
output_summary = gr.Markdown()
|
| 430 |
-
save_btn = gr.Button("Save Profile")
|
| 431 |
-
save_btn.click(
|
| 432 |
-
fn=save_profile,
|
| 433 |
-
inputs=[name, age, interests, transcript_data, learning_output,
|
| 434 |
-
movie, movie_reason, show, show_reason,
|
| 435 |
-
book, book_reason, character, character_reason, blog_text],
|
| 436 |
-
outputs=output_summary
|
| 437 |
)
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
chatbot = gr.ChatInterface(
|
| 442 |
-
fn=generate_response,
|
| 443 |
-
examples=[
|
| 444 |
-
"How should I study for my next test?",
|
| 445 |
-
"What's my GPA information?",
|
| 446 |
-
"Show me my course history",
|
| 447 |
-
"How can I improve my grades?"
|
| 448 |
-
]
|
| 449 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
|
| 451 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
import re
|
| 6 |
+
from PyPDF2 import PdfReader, PdfReadError
|
| 7 |
from collections import defaultdict
|
| 8 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 9 |
+
import html
|
| 10 |
+
from pathlib import Path
|
| 11 |
|
| 12 |
+
# ========== CONFIGURATION ==========
|
| 13 |
+
PROFILES_DIR = "student_profiles"
|
| 14 |
+
ALLOWED_FILE_TYPES = [".pdf"]
|
| 15 |
+
MAX_FILE_SIZE_MB = 5
|
| 16 |
+
MIN_AGE = 5
|
| 17 |
+
MAX_AGE = 120
|
| 18 |
+
|
| 19 |
+
# ========== NER MODEL HANDLING (DISABLED FOR HF SPACES) ==========
|
| 20 |
+
# Disabled for Hugging Face Spaces compatibility
|
| 21 |
+
ner_pipeline = None
|
| 22 |
+
|
| 23 |
+
# ========== UTILITY FUNCTIONS ==========
|
| 24 |
+
def sanitize_input(text: str) -> str:
|
| 25 |
+
"""Sanitize user input to prevent XSS and injection attacks."""
|
| 26 |
+
return html.escape(text.strip())
|
| 27 |
+
|
| 28 |
+
def validate_age(age: Union[int, float, str]) -> int:
|
| 29 |
+
"""Validate and convert age input."""
|
| 30 |
+
try:
|
| 31 |
+
age_int = int(age)
|
| 32 |
+
if not MIN_AGE <= age_int <= MAX_AGE:
|
| 33 |
+
raise gr.Error(f"Age must be between {MIN_AGE} and {MAX_AGE}")
|
| 34 |
+
return age_int
|
| 35 |
+
except (ValueError, TypeError):
|
| 36 |
+
raise gr.Error("Please enter a valid age number")
|
| 37 |
+
|
| 38 |
+
def validate_file(file_obj) -> None:
|
| 39 |
+
"""Validate uploaded file."""
|
| 40 |
+
if not file_obj:
|
| 41 |
+
raise gr.Error("No file uploaded")
|
| 42 |
+
|
| 43 |
+
if not any(file_obj.name.endswith(ext) for ext in ALLOWED_FILE_TYPES):
|
| 44 |
+
raise gr.Error(f"Only {', '.join(ALLOWED_FILE_TYPES)} files are allowed")
|
| 45 |
+
|
| 46 |
+
file_size = os.path.getsize(file_obj.name) / (1024 * 1024) # MB
|
| 47 |
+
if file_size > MAX_FILE_SIZE_MB:
|
| 48 |
+
raise gr.Error(f"File size must be less than {MAX_FILE_SIZE_MB}MB")
|
| 49 |
|
| 50 |
# ========== TRANSCRIPT PARSING ==========
|
| 51 |
+
def extract_gpa(text: str, gpa_type: str) -> str:
|
| 52 |
+
"""Extract GPA information from text with validation."""
|
| 53 |
pattern = rf'{gpa_type}\s*([\d\.]+)'
|
| 54 |
match = re.search(pattern, text)
|
| 55 |
+
if not match:
|
| 56 |
+
return "N/A"
|
| 57 |
+
|
| 58 |
+
gpa_value = match.group(1)
|
| 59 |
+
try:
|
| 60 |
+
gpa_float = float(gpa_value)
|
| 61 |
+
if not 0.0 <= gpa_float <= 5.0: # Assuming 5.0 is max for weighted GPA
|
| 62 |
+
return "Invalid GPA"
|
| 63 |
+
return gpa_value
|
| 64 |
+
except ValueError:
|
| 65 |
+
return "N/A"
|
| 66 |
|
| 67 |
+
def extract_courses_from_table(text: str) -> Dict[str, List[Dict]]:
|
| 68 |
+
"""Extract course information with multiple pattern fallbacks."""
|
| 69 |
+
# Primary pattern with strict formatting
|
| 70 |
+
primary_pattern = re.compile(
|
| 71 |
r'(\d{4}-\d{4})\s*' # School year
|
| 72 |
r'\|?\s*(\d+)\s*' # Grade level
|
| 73 |
r'\|?\s*([A-Z0-9]+)\s*' # Course code
|
| 74 |
+
r'\|?\s*([^\|]+?)\s*' # Course name
|
| 75 |
r'(?:\|\s*[^\|]*){2}' # Skip Term and DstNumber
|
| 76 |
r'\|\s*([A-FW]?)\s*' # Grade (FG column)
|
| 77 |
r'(?:\|\s*[^\|]*)' # Skip Incl column
|
| 78 |
r'\|\s*([\d\.]+|inProgress)' # Credits
|
| 79 |
)
|
| 80 |
|
| 81 |
+
# Fallback pattern for less structured data
|
| 82 |
+
fallback_pattern = re.compile(
|
| 83 |
+
r'(\d{4}-\d{4})\s+' # School year
|
| 84 |
+
r'(\d+)\s+' # Grade level
|
| 85 |
+
r'([A-Z0-9]+)\s+' # Course code
|
| 86 |
+
r'(.+?)\s+' # Course name
|
| 87 |
+
r'([A-FW]?)\s*' # Grade
|
| 88 |
+
r'([\d\.]+|inProgress)' # Credits
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
courses_by_grade = defaultdict(list)
|
| 92 |
|
| 93 |
+
for pattern in [primary_pattern, fallback_pattern]:
|
| 94 |
+
for match in re.finditer(pattern, text):
|
| 95 |
+
year_range, grade_level, course_code, course_name, grade, credits = match.groups()
|
| 96 |
+
|
| 97 |
+
# Clean and format course information
|
| 98 |
+
course_name = course_name.strip()
|
| 99 |
+
if 'DE:' in course_name:
|
| 100 |
+
course_name = course_name.replace('DE:', 'Dual Enrollment:')
|
| 101 |
+
if 'AP' in course_name and 'AP ' not in course_name:
|
| 102 |
+
course_name = course_name.replace('AP', 'AP ')
|
| 103 |
+
|
| 104 |
+
course_info = {
|
| 105 |
+
'name': f"{course_code} {course_name}",
|
| 106 |
+
'year': year_range,
|
| 107 |
+
'credits': credits if credits != 'inProgress' else 'In Progress'
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
if grade and grade.strip():
|
| 111 |
+
course_info['grade'] = grade.strip()
|
| 112 |
+
|
| 113 |
+
courses_by_grade[grade_level].append(course_info)
|
| 114 |
|
| 115 |
+
if courses_by_grade: # If we found matches with this pattern, stop
|
| 116 |
+
break
|
|
|
|
|
|
|
| 117 |
|
| 118 |
return courses_by_grade
|
| 119 |
|
| 120 |
+
def parse_transcript(file_obj) -> Tuple[str, Optional[Dict]]:
|
| 121 |
+
"""Parse transcript file with robust error handling."""
|
| 122 |
+
try:
|
| 123 |
+
validate_file(file_obj)
|
| 124 |
+
|
| 125 |
text = ''
|
| 126 |
+
try:
|
| 127 |
+
reader = PdfReader(file_obj)
|
| 128 |
+
for page in reader.pages:
|
| 129 |
+
page_text = page.extract_text()
|
| 130 |
+
if page_text:
|
| 131 |
+
text += page_text + '\n'
|
| 132 |
+
except PdfReadError:
|
| 133 |
+
raise gr.Error("Failed to read PDF file - may be corrupted")
|
| 134 |
+
except Exception as e:
|
| 135 |
+
raise gr.Error(f"Error processing PDF: {str(e)}")
|
| 136 |
+
|
| 137 |
+
if not text.strip():
|
| 138 |
+
raise gr.Error("No text could be extracted from the PDF")
|
| 139 |
|
| 140 |
+
# Extract GPA data with validation
|
| 141 |
gpa_data = {
|
| 142 |
'weighted': extract_gpa(text, 'Weighted GPA'),
|
| 143 |
'unweighted': extract_gpa(text, 'Un-weighted GPA')
|
| 144 |
}
|
| 145 |
|
| 146 |
+
# Extract grade level with fallback
|
| 147 |
+
grade_match = re.search(r'Current Grade:\s*(\d+)', text) or \
|
| 148 |
+
re.search(r'Grade\s*:\s*(\d+)', text) or \
|
| 149 |
+
re.search(r'Grade\s+(\d+)', text)
|
| 150 |
grade_level = grade_match.group(1) if grade_match else "Unknown"
|
| 151 |
|
| 152 |
courses_by_grade = extract_courses_from_table(text)
|
| 153 |
|
| 154 |
+
# Format output text
|
| 155 |
output_text = f"Student Transcript Summary\n{'='*40}\n"
|
| 156 |
output_text += f"Current Grade Level: {grade_level}\n"
|
| 157 |
output_text += f"Weighted GPA: {gpa_data['weighted']}\n"
|
| 158 |
output_text += f"Unweighted GPA: {gpa_data['unweighted']}\n\n"
|
| 159 |
output_text += "Course History:\n{'='*40}\n"
|
| 160 |
|
| 161 |
+
for grade in sorted(courses_by_grade.keys(), key=lambda x: int(x) if x.isdigit() else x):
|
| 162 |
output_text += f"\nGrade {grade}:\n{'-'*30}\n"
|
| 163 |
for course in courses_by_grade[grade]:
|
| 164 |
output_text += f"- {course['name']}"
|
|
|
|
| 173 |
"grade_level": grade_level,
|
| 174 |
"courses": dict(courses_by_grade)
|
| 175 |
}
|
| 176 |
+
|
| 177 |
+
except Exception as e:
|
| 178 |
+
return f"Error processing transcript: {str(e)}", None
|
| 179 |
|
| 180 |
# ========== LEARNING STYLE QUIZ ==========
|
| 181 |
+
class LearningStyleQuiz:
|
| 182 |
+
def __init__(self):
|
| 183 |
+
self.questions = [
|
| 184 |
+
"When you study for a test, you prefer to:",
|
| 185 |
+
"When you need directions to a new place, you prefer:",
|
| 186 |
+
"When you learn a new skill, you prefer to:",
|
| 187 |
+
"When you're trying to concentrate, you:",
|
| 188 |
+
"When you meet new people, you remember them by:",
|
| 189 |
+
"When you're assembling furniture or a gadget, you:",
|
| 190 |
+
"When choosing a restaurant, you rely most on:",
|
| 191 |
+
"When you're in a waiting room, you typically:",
|
| 192 |
+
"When giving someone instructions, you tend to:",
|
| 193 |
+
"When you're trying to recall information, you:",
|
| 194 |
+
"When you're at a museum or exhibit, you:",
|
| 195 |
+
"When you're learning a new language, you prefer:",
|
| 196 |
+
"When you're taking notes in class, you:",
|
| 197 |
+
"When you're explaining something complex, you:",
|
| 198 |
+
"When you're at a party, you enjoy:",
|
| 199 |
+
"When you're trying to remember a phone number, you:",
|
| 200 |
+
"When you're relaxing, you prefer to:",
|
| 201 |
+
"When you're learning to use new software, you:",
|
| 202 |
+
"When you're giving a presentation, you rely on:",
|
| 203 |
+
"When you're solving a difficult problem, you:"
|
| 204 |
+
]
|
| 205 |
+
|
| 206 |
+
self.options = [
|
| 207 |
+
["Read the textbook (Reading/Writing)", "Listen to lectures (Auditory)", "Use diagrams/charts (Visual)", "Practice problems (Kinesthetic)"],
|
| 208 |
+
["Look at a map (Visual)", "Have someone tell you (Auditory)", "Write down directions (Reading/Writing)", "Try walking/driving there (Kinesthetic)"],
|
| 209 |
+
["Read instructions (Reading/Writing)", "Have someone show you (Visual)", "Listen to explanations (Auditory)", "Try it yourself (Kinesthetic)"],
|
| 210 |
+
["Need quiet (Reading/Writing)", "Need background noise (Auditory)", "Need to move around (Kinesthetic)", "Need visual stimulation (Visual)"],
|
| 211 |
+
["Their face (Visual)", "Their name (Auditory)", "What you talked about (Reading/Writing)", "What you did together (Kinesthetic)"],
|
| 212 |
+
["Read the instructions carefully (Reading/Writing)", "Look at the diagrams (Visual)", "Ask someone to explain (Auditory)", "Start putting pieces together (Kinesthetic)"],
|
| 213 |
+
["Online photos of the food (Visual)", "Recommendations from friends (Auditory)", "Reading the menu online (Reading/Writing)", "Remembering how it felt to eat there (Kinesthetic)"],
|
| 214 |
+
["Read magazines (Reading/Writing)", "Listen to music (Auditory)", "Watch TV (Visual)", "Fidget or move around (Kinesthetic)"],
|
| 215 |
+
["Write them down (Reading/Writing)", "Explain verbally (Auditory)", "Demonstrate (Visual)", "Guide them physically (Kinesthetic)"],
|
| 216 |
+
["See written words in your mind (Visual)", "Hear the information in your head (Auditory)", "Write it down to remember (Reading/Writing)", "Associate it with physical actions (Kinesthetic)"],
|
| 217 |
+
["Read all the descriptions (Reading/Writing)", "Listen to audio guides (Auditory)", "Look at the displays (Visual)", "Touch interactive exhibits (Kinesthetic)"],
|
| 218 |
+
["Study grammar rules (Reading/Writing)", "Listen to native speakers (Auditory)", "Use flashcards with images (Visual)", "Practice conversations (Kinesthetic)"],
|
| 219 |
+
["Write detailed paragraphs (Reading/Writing)", "Record the lecture (Auditory)", "Draw diagrams and charts (Visual)", "Doodle while listening (Kinesthetic)"],
|
| 220 |
+
["Write detailed steps (Reading/Writing)", "Explain verbally with examples (Auditory)", "Draw diagrams (Visual)", "Use physical objects to demonstrate (Kinesthetic)"],
|
| 221 |
+
["Conversations with people (Auditory)", "Watching others or the environment (Visual)", "Writing notes or texting (Reading/Writing)", "Dancing or physical activities (Kinesthetic)"],
|
| 222 |
+
["See the numbers in your head (Visual)", "Say them aloud (Auditory)", "Write them down (Reading/Writing)", "Dial them on a keypad (Kinesthetic)"],
|
| 223 |
+
["Read a book (Reading/Writing)", "Listen to music (Auditory)", "Watch TV/movies (Visual)", "Do something physical (Kinesthetic)"],
|
| 224 |
+
["Read the manual (Reading/Writing)", "Ask someone to show you (Visual)", "Call tech support (Auditory)", "Experiment with the software (Kinesthetic)"],
|
| 225 |
+
["Detailed notes (Reading/Writing)", "Verbal explanations (Auditory)", "Visual slides (Visual)", "Physical demonstrations (Kinesthetic)"],
|
| 226 |
+
["Write out possible solutions (Reading/Writing)", "Talk through it with someone (Auditory)", "Draw diagrams (Visual)", "Build a model or prototype (Kinesthetic)"]
|
| 227 |
+
]
|
| 228 |
+
|
| 229 |
+
self.learning_styles = {
|
| 230 |
+
"Visual": {
|
| 231 |
+
"description": "Visual learners prefer using images, diagrams, and spatial understanding.",
|
| 232 |
+
"tips": [
|
| 233 |
+
"Use color coding in your notes",
|
| 234 |
+
"Create mind maps and diagrams",
|
| 235 |
+
"Watch educational videos",
|
| 236 |
+
"Use flashcards with images",
|
| 237 |
+
"Highlight important information in different colors"
|
| 238 |
+
]
|
| 239 |
+
},
|
| 240 |
+
"Auditory": {
|
| 241 |
+
"description": "Auditory learners learn best through listening and speaking.",
|
| 242 |
+
"tips": [
|
| 243 |
+
"Record lectures and listen to them",
|
| 244 |
+
"Participate in study groups",
|
| 245 |
+
"Explain concepts out loud to yourself",
|
| 246 |
+
"Use rhymes or songs to remember information",
|
| 247 |
+
"Listen to educational podcasts"
|
| 248 |
+
]
|
| 249 |
+
},
|
| 250 |
+
"Reading/Writing": {
|
| 251 |
+
"description": "These learners prefer information displayed as words.",
|
| 252 |
+
"tips": [
|
| 253 |
+
"Write detailed notes",
|
| 254 |
+
"Create summaries in your own words",
|
| 255 |
+
"Read textbooks and articles",
|
| 256 |
+
"Make lists to organize information",
|
| 257 |
+
"Rewrite your notes to reinforce learning"
|
| 258 |
+
]
|
| 259 |
+
},
|
| 260 |
+
"Kinesthetic": {
|
| 261 |
+
"description": "Kinesthetic learners learn through movement and hands-on activities.",
|
| 262 |
+
"tips": [
|
| 263 |
+
"Use hands-on activities",
|
| 264 |
+
"Take frequent movement breaks",
|
| 265 |
+
"Create physical models",
|
| 266 |
+
"Associate information with physical actions",
|
| 267 |
+
"Study while walking or pacing"
|
| 268 |
+
]
|
| 269 |
+
}
|
| 270 |
+
}
|
| 271 |
|
| 272 |
+
def evaluate_quiz(self, answers: List[str]) -> str:
|
| 273 |
+
"""Evaluate quiz answers and generate results."""
|
| 274 |
+
if len(answers) != len(self.questions):
|
| 275 |
+
raise gr.Error("Not all questions were answered")
|
| 276 |
+
|
| 277 |
+
scores = {style: 0 for style in self.learning_styles}
|
| 278 |
+
|
| 279 |
+
for i, answer in enumerate(answers):
|
| 280 |
+
if not answer:
|
| 281 |
+
continue # Skip unanswered questions
|
| 282 |
+
|
| 283 |
+
for j, style in enumerate(self.learning_styles):
|
| 284 |
+
if answer == self.options[i][j]:
|
| 285 |
+
scores[style] += 1
|
| 286 |
+
break
|
| 287 |
+
|
| 288 |
+
total_answered = sum(1 for ans in answers if ans)
|
| 289 |
+
if total_answered == 0:
|
| 290 |
+
raise gr.Error("No answers provided")
|
| 291 |
+
|
| 292 |
+
percentages = {style: (score/total_answered)*100 for style, score in scores.items()}
|
| 293 |
+
sorted_styles = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 294 |
+
|
| 295 |
+
# Generate results report
|
| 296 |
+
result = "## Your Learning Style Results\n\n"
|
| 297 |
+
result += "### Scores:\n"
|
| 298 |
+
for style, score in sorted_styles:
|
| 299 |
+
result += f"- **{style}**: {score}/{total_answered} ({percentages[style]:.1f}%)\n"
|
| 300 |
+
|
| 301 |
+
max_score = max(scores.values())
|
| 302 |
+
primary_styles = [style for style, score in scores.items() if score == max_score]
|
| 303 |
+
|
| 304 |
+
result += "\n### Analysis:\n"
|
| 305 |
+
if len(primary_styles) == 1:
|
| 306 |
+
primary_style = primary_styles[0]
|
| 307 |
+
style_info = self.learning_styles[primary_style]
|
| 308 |
+
|
| 309 |
+
result += f"Your primary learning style is **{primary_style}**\n\n"
|
| 310 |
+
result += f"**{primary_style} Characteristics**:\n"
|
| 311 |
+
result += f"{style_info['description']}\n\n"
|
| 312 |
+
|
| 313 |
+
result += "**Recommended Study Strategies**:\n"
|
| 314 |
+
for tip in style_info['tips']:
|
| 315 |
+
result += f"- {tip}\n"
|
| 316 |
+
|
| 317 |
+
# Add complementary strategies
|
| 318 |
+
complementary = [s for s in sorted_styles if s[0] != primary_style][0][0]
|
| 319 |
+
result += f"\nYou might also benefit from some **{complementary}** strategies:\n"
|
| 320 |
+
for tip in self.learning_styles[complementary]['tips'][:3]:
|
| 321 |
+
result += f"- {tip}\n"
|
| 322 |
else:
|
| 323 |
+
result += "You have multiple strong learning styles:\n"
|
| 324 |
+
for style in primary_styles:
|
| 325 |
+
result += f"- **{style}**\n"
|
| 326 |
+
|
| 327 |
+
result += "\n**Combined Learning Strategies**:\n"
|
| 328 |
+
result += "You may benefit from combining different learning approaches:\n"
|
| 329 |
+
for style in primary_styles:
|
| 330 |
+
result += f"\n**{style}** techniques:\n"
|
| 331 |
+
for tip in self.learning_styles[style]['tips'][:2]:
|
| 332 |
+
result += f"- {tip}\n"
|
| 333 |
+
|
| 334 |
+
return result
|
| 335 |
+
|
| 336 |
+
# Initialize quiz instance
|
| 337 |
+
learning_style_quiz = LearningStyleQuiz()
|
| 338 |
|
| 339 |
# ========== PROFILE MANAGEMENT ==========
|
| 340 |
+
class ProfileManager:
|
| 341 |
+
def __init__(self):
|
| 342 |
+
self.profiles_dir = Path(PROFILES_DIR)
|
| 343 |
+
self.profiles_dir.mkdir(exist_ok=True)
|
| 344 |
|
| 345 |
+
def save_profile(self, name: str, age: Union[int, str], interests: str,
|
| 346 |
+
transcript: Dict, learning_style: str,
|
| 347 |
+
movie: str, movie_reason: str, show: str, show_reason: str,
|
| 348 |
+
book: str, book_reason: str, character: str, character_reason: str,
|
| 349 |
+
blog: str) -> str:
|
| 350 |
+
"""Save student profile with validation."""
|
| 351 |
+
try:
|
| 352 |
+
# Validate required fields
|
| 353 |
+
if not name.strip():
|
| 354 |
+
raise gr.Error("Name is required")
|
| 355 |
+
|
| 356 |
+
name = sanitize_input(name)
|
| 357 |
+
age = validate_age(age)
|
| 358 |
+
interests = sanitize_input(interests)
|
| 359 |
+
|
| 360 |
+
# Prepare favorites data
|
| 361 |
+
favorites = {
|
| 362 |
+
"movie": sanitize_input(movie),
|
| 363 |
+
"movie_reason": sanitize_input(movie_reason),
|
| 364 |
+
"show": sanitize_input(show),
|
| 365 |
+
"show_reason": sanitize_input(show_reason),
|
| 366 |
+
"book": sanitize_input(book),
|
| 367 |
+
"book_reason": sanitize_input(book_reason),
|
| 368 |
+
"character": sanitize_input(character),
|
| 369 |
+
"character_reason": sanitize_input(character_reason)
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
# Prepare full profile data
|
| 373 |
+
data = {
|
| 374 |
+
"name": name,
|
| 375 |
+
"age": age,
|
| 376 |
+
"interests": interests,
|
| 377 |
+
"transcript": transcript if transcript else {},
|
| 378 |
+
"learning_style": learning_style if learning_style else "Not assessed",
|
| 379 |
+
"favorites": favorites,
|
| 380 |
+
"blog": sanitize_input(blog) if blog else ""
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
# Save to JSON file
|
| 384 |
+
filename = f"{name.replace(' ', '_')}_profile.json"
|
| 385 |
+
filepath = self.profiles_dir / filename
|
| 386 |
+
|
| 387 |
+
with open(filepath, "w", encoding='utf-8') as f:
|
| 388 |
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
| 389 |
+
|
| 390 |
+
return self._generate_profile_summary(data)
|
| 391 |
+
|
| 392 |
+
except Exception as e:
|
| 393 |
+
raise gr.Error(f"Error saving profile: {str(e)}")
|
| 394 |
|
| 395 |
+
def load_profile(self, name: str = None) -> Dict:
|
| 396 |
+
"""Load profile by name or return the first one found."""
|
| 397 |
+
try:
|
| 398 |
+
profiles = list(self.profiles_dir.glob("*.json"))
|
| 399 |
+
if not profiles:
|
| 400 |
+
return {}
|
| 401 |
+
|
| 402 |
+
if name:
|
| 403 |
+
# Find profile by name
|
| 404 |
+
name = name.replace(" ", "_")
|
| 405 |
+
profile_file = self.profiles_dir / f"{name}_profile.json"
|
| 406 |
+
if not profile_file.exists():
|
| 407 |
+
raise gr.Error(f"No profile found for {name}")
|
| 408 |
+
else:
|
| 409 |
+
# Load the first profile found
|
| 410 |
+
profile_file = profiles[0]
|
| 411 |
+
|
| 412 |
+
with open(profile_file, "r", encoding='utf-8') as f:
|
| 413 |
+
return json.load(f)
|
| 414 |
+
|
| 415 |
+
except Exception as e:
|
| 416 |
+
print(f"Error loading profile: {str(e)}")
|
| 417 |
+
return {}
|
| 418 |
|
| 419 |
+
def list_profiles(self) -> List[str]:
|
| 420 |
+
"""List all available profile names."""
|
| 421 |
+
profiles = list(self.profiles_dir.glob("*.json"))
|
| 422 |
+
return [p.stem.replace("_profile", "").replace("_", " ") for p in profiles]
|
| 423 |
+
|
| 424 |
+
def _generate_profile_summary(self, data: Dict) -> str:
|
| 425 |
+
"""Generate markdown summary of the profile."""
|
| 426 |
+
transcript = data.get("transcript", {})
|
| 427 |
+
favorites = data.get("favorites", {})
|
| 428 |
+
|
| 429 |
+
markdown = f"""## Student Profile: {data['name']}
|
| 430 |
|
| 431 |
+
### Basic Information
|
| 432 |
+
- **Age:** {data['age']}
|
| 433 |
+
- **Interests:** {data['interests']}
|
| 434 |
+
- **Learning Style:** {data['learning_style'].split('##')[0].strip()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
|
| 436 |
+
### Academic Information
|
| 437 |
+
{self._format_transcript(transcript)}
|
| 438 |
+
|
| 439 |
+
### Favorites
|
| 440 |
+
- **Movie:** {favorites.get('movie', 'Not specified')}
|
| 441 |
+
*Reason:* {favorites.get('movie_reason', 'Not specified')}
|
| 442 |
+
- **TV Show:** {favorites.get('show', 'Not specified')}
|
| 443 |
+
*Reason:* {favorites.get('show_reason', 'Not specified')}
|
| 444 |
+
- **Book:** {favorites.get('book', 'Not specified')}
|
| 445 |
+
*Reason:* {favorites.get('book_reason', 'Not specified')}
|
| 446 |
+
- **Character:** {favorites.get('character', 'Not specified')}
|
| 447 |
+
*Reason:* {favorites.get('character_reason', 'Not specified')}
|
| 448 |
+
|
| 449 |
+
### Personal Blog
|
| 450 |
+
{data.get('blog', '_No blog provided_')}
|
| 451 |
+
"""
|
| 452 |
+
return markdown
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
|
| 454 |
+
def _format_transcript(self, transcript: Dict) -> str:
|
| 455 |
+
"""Format transcript data for display."""
|
| 456 |
+
if not transcript or "courses" not in transcript:
|
| 457 |
+
return "_No transcript information available_"
|
| 458 |
+
|
| 459 |
+
display = "#### Course History\n"
|
| 460 |
+
courses_by_grade = transcript["courses"]
|
| 461 |
+
|
| 462 |
+
if isinstance(courses_by_grade, dict):
|
| 463 |
+
for grade in sorted(courses_by_grade.keys(), key=lambda x: int(x) if x.isdigit() else x):
|
| 464 |
+
display += f"\n**Grade {grade}**\n"
|
| 465 |
+
for course in courses_by_grade[grade]:
|
| 466 |
+
display += f"- {course.get('name', 'Unnamed course')}"
|
| 467 |
+
if 'grade' in course and course['grade']:
|
| 468 |
+
display += f" (Grade: {course['grade']})"
|
| 469 |
+
if 'credits' in course:
|
| 470 |
+
display += f" | Credits: {course['credits']}"
|
| 471 |
+
display += f" | Year: {course.get('year', 'N/A')}\n"
|
| 472 |
+
|
| 473 |
+
if 'gpa' in transcript:
|
| 474 |
+
gpa = transcript['gpa']
|
| 475 |
+
display += "\n**GPA**\n"
|
| 476 |
+
display += f"- Unweighted: {gpa.get('unweighted', 'N/A')}\n"
|
| 477 |
+
display += f"- Weighted: {gpa.get('weighted', 'N/A')}\n"
|
| 478 |
+
|
| 479 |
+
return display
|
| 480 |
|
| 481 |
+
# Initialize profile manager
|
| 482 |
+
profile_manager = ProfileManager()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
|
| 484 |
+
# ========== AI TEACHING ASSISTANT ==========
|
| 485 |
+
class TeachingAssistant:
|
| 486 |
+
def __init__(self):
|
| 487 |
+
self.context_history = []
|
| 488 |
+
self.max_context_length = 5 # Keep last 5 exchanges for context
|
| 489 |
|
| 490 |
+
def generate_response(self, message: str, history: List[Tuple[str, str]]) -> str:
|
| 491 |
+
"""Generate personalized response based on student profile and context."""
|
| 492 |
+
try:
|
| 493 |
+
# Load profile (simplified - in real app would handle multiple profiles)
|
| 494 |
+
profile = profile_manager.load_profile()
|
| 495 |
+
if not profile:
|
| 496 |
+
return "Please complete and save your profile first using the previous tabs."
|
| 497 |
+
|
| 498 |
+
# Update context history
|
| 499 |
+
self._update_context(message, history)
|
| 500 |
+
|
| 501 |
+
# Extract profile information
|
| 502 |
+
name = profile.get("name", "there")
|
| 503 |
+
learning_style = profile.get("learning_style", "")
|
| 504 |
+
grade_level = profile.get("transcript", {}).get("grade_level", "unknown")
|
| 505 |
+
gpa = profile.get("transcript", {}).get("gpa", {})
|
| 506 |
+
interests = profile.get("interests", "")
|
| 507 |
+
courses = profile.get("transcript", {}).get("courses", {})
|
| 508 |
+
favorites = profile.get("favorites", {})
|
| 509 |
+
|
| 510 |
+
# Process message with context
|
| 511 |
+
response = self._process_message(message, profile)
|
| 512 |
+
|
| 513 |
+
# Add follow-up suggestions
|
| 514 |
+
if "study" in message.lower() or "learn" in message.lower():
|
| 515 |
+
response += "\n\nWould you like me to suggest a study schedule based on your courses?"
|
| 516 |
+
elif "course" in message.lower() or "class" in message.lower():
|
| 517 |
+
response += "\n\nWould you like help finding resources for any of these courses?"
|
| 518 |
+
|
| 519 |
+
return response
|
| 520 |
+
|
| 521 |
+
except Exception as e:
|
| 522 |
+
print(f"Error generating response: {str(e)}")
|
| 523 |
+
return "I encountered an error processing your request. Please try again."
|
| 524 |
|
| 525 |
+
def _update_context(self, message: str, history: List[Tuple[str, str]]) -> None:
|
| 526 |
+
"""Maintain conversation context."""
|
| 527 |
+
self.context_history.append(("user", message))
|
| 528 |
+
if history:
|
| 529 |
+
for h in history[-self.max_context_length:]:
|
| 530 |
+
self.context_history.append(("user", h[0]))
|
| 531 |
+
self.context_history.append(("assistant", h[1]))
|
| 532 |
+
|
| 533 |
+
# Trim to maintain max context length
|
| 534 |
+
self.context_history = self.context_history[-(self.max_context_length*2):]
|
| 535 |
|
| 536 |
+
def _process_message(self, message: str, profile: Dict) -> str:
|
| 537 |
+
"""Process user message with profile context."""
|
| 538 |
+
message_lower = message.lower()
|
| 539 |
+
|
| 540 |
+
# Greetings
|
| 541 |
+
if any(greet in message_lower for greet in ["hi", "hello", "hey", "greetings"]):
|
| 542 |
+
return f"Hello {profile.get('name', 'there')}! How can I help you with your learning today?"
|
| 543 |
+
|
| 544 |
+
# Study help
|
| 545 |
+
study_words = ["study", "learn", "prepare", "exam", "test", "homework"]
|
| 546 |
+
if any(word in message_lower for word in study_words):
|
| 547 |
+
return self._generate_study_advice(profile)
|
| 548 |
+
|
| 549 |
+
# Grade help
|
| 550 |
+
grade_words = ["grade", "gpa", "score", "marks", "results"]
|
| 551 |
+
if any(word in message_lower for word in grade_words):
|
| 552 |
+
return self._generate_grade_advice(profile)
|
| 553 |
+
|
| 554 |
+
# Interest help
|
| 555 |
+
interest_words = ["interest", "hobby", "passion", "extracurricular"]
|
| 556 |
+
if any(word in message_lower for word in interest_words):
|
| 557 |
+
return self._generate_interest_advice(profile)
|
| 558 |
+
|
| 559 |
+
# Course help
|
| 560 |
+
course_words = ["courses", "classes", "transcript", "schedule", "subject"]
|
| 561 |
+
if any(word in message_lower for word in course_words):
|
| 562 |
+
return self._generate_course_advice(profile)
|
| 563 |
+
|
| 564 |
+
# Favorites
|
| 565 |
+
favorite_words = ["movie", "show", "book", "character", "favorite"]
|
| 566 |
+
if any(word in message_lower for word in favorite_words):
|
| 567 |
+
return self._generate_favorites_response(profile)
|
| 568 |
+
|
| 569 |
+
# General help
|
| 570 |
+
if "help" in message_lower:
|
| 571 |
+
return self._generate_help_response()
|
| 572 |
+
|
| 573 |
+
# Default response
|
| 574 |
+
return ("I'm your personalized teaching assistant. I can help with study tips, "
|
| 575 |
+
"grade information, course advice, and more. Try asking about how to "
|
| 576 |
+
"study effectively or about your course history.")
|
| 577 |
|
| 578 |
+
def _generate_study_advice(self, profile: Dict) -> str:
|
| 579 |
+
"""Generate study advice based on learning style."""
|
| 580 |
+
learning_style = profile.get("learning_style", "")
|
| 581 |
+
response = ""
|
| 582 |
+
|
| 583 |
if "Visual" in learning_style:
|
| 584 |
response = ("Based on your visual learning style, I recommend:\n"
|
| 585 |
+
"- Creating colorful mind maps or diagrams\n"
|
| 586 |
+
"- Using highlighters to color-code your notes\n"
|
| 587 |
+
"- Watching educational videos on the topics\n"
|
| 588 |
+
"- Creating flashcards with images\n\n")
|
| 589 |
elif "Auditory" in learning_style:
|
| 590 |
response = ("Based on your auditory learning style, I recommend:\n"
|
| 591 |
+
"- Recording your notes and listening to them\n"
|
| 592 |
+
"- Participating in study groups to discuss concepts\n"
|
| 593 |
+
"- Explaining the material out loud to yourself\n"
|
| 594 |
+
"- Finding podcasts or audio lectures on the topics\n\n")
|
| 595 |
elif "Reading/Writing" in learning_style:
|
| 596 |
response = ("Based on your reading/writing learning style, I recommend:\n"
|
| 597 |
+
"- Writing detailed summaries in your own words\n"
|
| 598 |
+
"- Creating organized outlines of the material\n"
|
| 599 |
+
"- Reading additional textbooks or articles\n"
|
| 600 |
+
"- Rewriting your notes to reinforce learning\n\n")
|
| 601 |
elif "Kinesthetic" in learning_style:
|
| 602 |
response = ("Based on your kinesthetic learning style, I recommend:\n"
|
| 603 |
+
"- Creating physical models or demonstrations\n"
|
| 604 |
+
"- Using hands-on activities to learn concepts\n"
|
| 605 |
+
"- Taking frequent movement breaks while studying\n"
|
| 606 |
+
"- Associating information with physical actions\n\n")
|
| 607 |
else:
|
| 608 |
response = ("Here are some general study tips:\n"
|
| 609 |
+
"- Use the Pomodoro technique (25 min study, 5 min break)\n"
|
| 610 |
+
"- Space out your study sessions over time\n"
|
| 611 |
+
"- Test yourself with practice questions\n"
|
| 612 |
+
"- Teach the material to someone else\n\n")
|
| 613 |
+
|
| 614 |
+
# Add time management advice
|
| 615 |
+
response += ("**Time Management Tips**:\n"
|
| 616 |
+
"- Create a study schedule and stick to it\n"
|
| 617 |
+
"- Prioritize difficult subjects when you're most alert\n"
|
| 618 |
+
"- Break large tasks into smaller, manageable chunks\n"
|
| 619 |
+
"- Set specific goals for each study session")
|
| 620 |
|
| 621 |
return response
|
| 622 |
|
| 623 |
+
def _generate_grade_advice(self, profile: Dict) -> str:
|
| 624 |
+
"""Generate response about grades and GPA."""
|
| 625 |
+
gpa = profile.get("transcript", {}).get("gpa", {})
|
| 626 |
+
courses = profile.get("transcript", {}).get("courses", {})
|
| 627 |
+
|
| 628 |
+
response = (f"Your GPA information:\n"
|
| 629 |
+
f"- Unweighted: {gpa.get('unweighted', 'N/A')}\n"
|
| 630 |
+
f"- Weighted: {gpa.get('weighted', 'N/A')}\n\n")
|
| 631 |
+
|
| 632 |
+
# Identify any failing grades
|
| 633 |
+
weak_subjects = []
|
| 634 |
+
for grade_level, course_list in courses.items():
|
| 635 |
+
for course in course_list:
|
| 636 |
+
if course.get('grade', '').upper() in ['D', 'F']:
|
| 637 |
+
weak_subjects.append(course.get('name', 'Unknown course'))
|
| 638 |
+
|
| 639 |
+
if weak_subjects:
|
| 640 |
+
response += ("**Areas for Improvement**:\n"
|
| 641 |
+
f"You might want to focus on these subjects: {', '.join(weak_subjects)}\n\n")
|
| 642 |
+
|
| 643 |
+
response += ("**Grade Improvement Strategies**:\n"
|
| 644 |
+
"- Meet with your teachers to discuss your performance\n"
|
| 645 |
+
"- Identify specific areas where you lost points\n"
|
| 646 |
+
"- Create a targeted study plan for weak areas\n"
|
| 647 |
+
"- Practice with past exams or sample questions")
|
| 648 |
+
|
| 649 |
+
return response
|
| 650 |
|
| 651 |
+
def _generate_interest_advice(self, profile: Dict) -> str:
|
| 652 |
+
"""Generate response based on student interests."""
|
| 653 |
+
interests = profile.get("interests", "")
|
| 654 |
+
response = f"I see you're interested in: {interests}\n\n"
|
| 655 |
+
|
| 656 |
+
response += ("**Suggestions**:\n"
|
| 657 |
+
"- Look for clubs or extracurricular activities related to these interests\n"
|
| 658 |
+
"- Explore career paths that align with these interests\n"
|
| 659 |
+
"- Find online communities or forums about these topics\n"
|
| 660 |
+
"- Consider projects or independent study in these areas")
|
| 661 |
+
|
| 662 |
+
return response
|
| 663 |
|
| 664 |
+
def _generate_course_advice(self, profile: Dict) -> str:
|
| 665 |
+
"""Generate response about courses."""
|
| 666 |
+
courses = profile.get("transcript", {}).get("courses", {})
|
| 667 |
+
grade_level = profile.get("transcript", {}).get("grade_level", "unknown")
|
| 668 |
+
|
| 669 |
response = "Here's a summary of your courses:\n"
|
| 670 |
+
for grade in sorted(courses.keys(), key=lambda x: int(x) if x.isdigit() else x):
|
| 671 |
+
response += f"\n**Grade {grade}**:\n"
|
| 672 |
for course in courses[grade]:
|
| 673 |
+
response += f"- {course.get('name', 'Unnamed course')}"
|
| 674 |
if 'grade' in course:
|
| 675 |
response += f" (Grade: {course['grade']})"
|
| 676 |
response += "\n"
|
| 677 |
+
|
| 678 |
+
response += f"\nAs a grade {grade_level} student, you might want to:\n"
|
| 679 |
+
if grade_level in ["9", "10"]:
|
| 680 |
+
response += ("- Focus on building strong foundational skills\n"
|
| 681 |
+
"- Explore different subjects to find your interests\n"
|
| 682 |
+
"- Start thinking about college/career requirements")
|
| 683 |
+
elif grade_level in ["11", "12"]:
|
| 684 |
+
response += ("- Focus on courses relevant to your college/career goals\n"
|
| 685 |
+
"- Consider taking AP or advanced courses if available\n"
|
| 686 |
+
"- Ensure you're meeting graduation requirements")
|
| 687 |
+
|
| 688 |
return response
|
| 689 |
|
| 690 |
+
def _generate_favorites_response(self, profile: Dict) -> str:
|
| 691 |
+
"""Generate response about favorite items."""
|
| 692 |
+
favorites = profile.get("favorites", {})
|
| 693 |
+
response = "I see you enjoy:\n"
|
| 694 |
+
|
| 695 |
+
if favorites.get('movie'):
|
| 696 |
+
response += f"- Movie: {favorites['movie']} ({favorites.get('movie_reason', 'no reason provided')})\n"
|
| 697 |
+
if favorites.get('show'):
|
| 698 |
+
response += f"- TV Show: {favorites['show']} ({favorites.get('show_reason', 'no reason provided')})\n"
|
| 699 |
+
if favorites.get('book'):
|
| 700 |
+
response += f"- Book: {favorites['book']} ({favorites.get('book_reason', 'no reason provided')})\n"
|
| 701 |
+
if favorites.get('character'):
|
| 702 |
+
response += f"- Character: {favorites['character']} ({favorites.get('character_reason', 'no reason provided')})\n"
|
| 703 |
+
|
| 704 |
+
response += "\nThese preferences suggest you might enjoy:\n"
|
| 705 |
+
response += "- Similar books/movies in the same genre\n"
|
| 706 |
+
response += "- Creative projects related to these stories\n"
|
| 707 |
+
response += "- Analyzing themes or characters in your schoolwork"
|
| 708 |
+
|
| 709 |
+
return response
|
| 710 |
|
| 711 |
+
def _generate_help_response(self) -> str:
|
| 712 |
+
"""Generate help response with available commands."""
|
| 713 |
+
return ("""I can help with:
|
| 714 |
+
- **Study tips**: "How should I study for math?"
|
| 715 |
+
- **Grade information**: "What's my GPA?"
|
| 716 |
+
- **Course advice**: "Show me my course history"
|
| 717 |
+
- **Interest suggestions**: "What clubs match my interests?"
|
| 718 |
+
- **General advice**: "How can I improve my grades?"
|
| 719 |
+
|
| 720 |
+
Try asking about any of these topics!""")
|
| 721 |
+
|
| 722 |
+
# Initialize teaching assistant
|
| 723 |
+
teaching_assistant = TeachingAssistant()
|
| 724 |
|
| 725 |
# ========== GRADIO INTERFACE ==========
|
| 726 |
+
def create_interface():
|
| 727 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Student Learning Assistant") as app:
|
| 728 |
+
# Custom CSS for better styling
|
| 729 |
+
app.css = """
|
| 730 |
+
.gradio-container {
|
| 731 |
+
max-width: 1200px !important;
|
| 732 |
+
margin: 0 auto;
|
| 733 |
+
}
|
| 734 |
+
.tab {
|
| 735 |
+
padding: 20px;
|
| 736 |
+
border-radius: 8px;
|
| 737 |
+
background: white;
|
| 738 |
+
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
| 739 |
+
}
|
| 740 |
+
.progress-bar {
|
| 741 |
+
height: 5px;
|
| 742 |
+
background: linear-gradient(to right, #4CAF50, #8BC34A);
|
| 743 |
+
margin-bottom: 15px;
|
| 744 |
+
border-radius: 3px;
|
| 745 |
+
}
|
| 746 |
+
.quiz-question {
|
| 747 |
+
margin-bottom: 15px;
|
| 748 |
+
padding: 15px;
|
| 749 |
+
background: #f5f5f5;
|
| 750 |
+
border-radius: 5px;
|
| 751 |
+
}
|
| 752 |
+
"""
|
| 753 |
+
|
| 754 |
+
gr.Markdown("""
|
| 755 |
+
# Student Learning Assistant
|
| 756 |
+
**Your personalized education companion**
|
| 757 |
+
Complete each step to get customized learning recommendations.
|
| 758 |
+
""")
|
| 759 |
+
|
| 760 |
+
# Progress tracker
|
| 761 |
+
with gr.Row():
|
| 762 |
+
with gr.Column(scale=1):
|
| 763 |
+
step1 = gr.Button("1. Upload Transcript", variant="primary")
|
| 764 |
+
with gr.Column(scale=1):
|
| 765 |
+
step2 = gr.Button("2. Learning Style Quiz")
|
| 766 |
+
with gr.Column(scale=1):
|
| 767 |
+
step3 = gr.Button("3. Personal Questions")
|
| 768 |
+
with gr.Column(scale=1):
|
| 769 |
+
step4 = gr.Button("4. Save & Review")
|
| 770 |
+
with gr.Column(scale=1):
|
| 771 |
+
step5 = gr.Button("5. AI Assistant")
|
| 772 |
+
|
| 773 |
+
# Tab navigation logic
|
| 774 |
+
def navigate_to_tab(tab_index):
|
| 775 |
+
return {tab: gr.update(visible=(i == tab_index)) for i, tab in enumerate(tabs)}
|
| 776 |
+
|
| 777 |
+
# Main tabs
|
| 778 |
+
with gr.Tabs() as tabs:
|
| 779 |
+
# ===== TAB 1: Transcript Upload =====
|
| 780 |
+
with gr.Tab("Transcript Upload", id=0) as tab1:
|
| 781 |
+
with gr.Row():
|
| 782 |
+
with gr.Column(scale=1):
|
| 783 |
+
gr.Markdown("### Step 1: Upload Your Transcript")
|
| 784 |
+
gr.Markdown("Upload a PDF of your academic transcript to analyze your courses and GPA.")
|
| 785 |
+
|
| 786 |
+
with gr.Group():
|
| 787 |
+
transcript_file = gr.File(
|
| 788 |
+
label="Transcript PDF",
|
| 789 |
+
file_types=ALLOWED_FILE_TYPES,
|
| 790 |
+
type="filepath"
|
| 791 |
+
)
|
| 792 |
+
upload_btn = gr.Button("Upload & Analyze", variant="primary")
|
| 793 |
+
|
| 794 |
+
gr.Markdown("**Note**: Your file is processed locally and not stored permanently.")
|
| 795 |
+
|
| 796 |
+
with gr.Column(scale=2):
|
| 797 |
+
transcript_output = gr.Textbox(
|
| 798 |
+
label="Transcript Analysis",
|
| 799 |
+
lines=20,
|
| 800 |
+
interactive=False
|
| 801 |
+
)
|
| 802 |
+
transcript_data = gr.State()
|
| 803 |
+
|
| 804 |
+
upload_btn.click(
|
| 805 |
+
fn=parse_transcript,
|
| 806 |
+
inputs=transcript_file,
|
| 807 |
+
outputs=[transcript_output, transcript_data]
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
+
# ===== TAB 2: Learning Style Quiz =====
|
| 811 |
+
with gr.Tab("Learning Style Quiz", id=1) as tab2:
|
| 812 |
+
with gr.Row():
|
| 813 |
+
with gr.Column(scale=1):
|
| 814 |
+
gr.Markdown("### Step 2: Discover Your Learning Style")
|
| 815 |
+
gr.Markdown("Complete this 20-question quiz to identify whether you're a visual, auditory, reading/writing, or kinesthetic learner.")
|
| 816 |
+
|
| 817 |
+
progress = gr.HTML("<div class='progress-bar' style='width: 0%'></div>")
|
| 818 |
+
quiz_submit = gr.Button("Submit Quiz", variant="primary")
|
| 819 |
+
|
| 820 |
+
with gr.Column(scale=2):
|
| 821 |
+
quiz_components = []
|
| 822 |
+
with gr.Accordion("Quiz Questions", open=True):
|
| 823 |
+
for i, (question, options) in enumerate(zip(learning_style_quiz.questions, learning_style_quiz.options)):
|
| 824 |
+
with gr.Group(elem_classes="quiz-question"):
|
| 825 |
+
q = gr.Radio(
|
| 826 |
+
options,
|
| 827 |
+
label=f"{i+1}. {question}",
|
| 828 |
+
show_label=True
|
| 829 |
+
)
|
| 830 |
+
quiz_components.append(q)
|
| 831 |
+
|
| 832 |
+
learning_output = gr.Markdown(
|
| 833 |
+
label="Your Learning Style Results",
|
| 834 |
+
visible=False
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
# Update progress bar as questions are answered
|
| 838 |
+
for component in quiz_components:
|
| 839 |
+
component.change(
|
| 840 |
+
fn=lambda *answers: {
|
| 841 |
+
progress: gr.HTML(
|
| 842 |
+
f"<div class='progress-bar' style='width: {sum(1 for a in answers if a)/len(answers)*100}%'></div>"
|
| 843 |
+
)
|
| 844 |
+
},
|
| 845 |
+
inputs=quiz_components,
|
| 846 |
+
outputs=progress
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
quiz_submit.click(
|
| 850 |
+
fn=learning_style_quiz.evaluate_quiz,
|
| 851 |
+
inputs=quiz_components,
|
| 852 |
+
outputs=learning_output
|
| 853 |
+
).then(
|
| 854 |
+
fn=lambda: gr.update(visible=True),
|
| 855 |
+
outputs=learning_output
|
| 856 |
+
)
|
| 857 |
+
|
| 858 |
+
# ===== TAB 3: Personal Questions =====
|
| 859 |
+
with gr.Tab("Personal Profile", id=2) as tab3:
|
| 860 |
+
with gr.Row():
|
| 861 |
+
with gr.Column(scale=1):
|
| 862 |
+
gr.Markdown("### Step 3: Tell Us About Yourself")
|
| 863 |
+
gr.Markdown("This information helps us provide personalized recommendations.")
|
| 864 |
+
|
| 865 |
+
with gr.Group():
|
| 866 |
+
name = gr.Textbox(label="Full Name", placeholder="Your name")
|
| 867 |
+
age = gr.Number(label="Age", minimum=MIN_AGE, maximum=MAX_AGE, precision=0)
|
| 868 |
+
interests = gr.Textbox(
|
| 869 |
+
label="Your Interests/Hobbies",
|
| 870 |
+
placeholder="e.g., Science, Music, Sports, Art..."
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
gr.Markdown("### Favorites")
|
| 874 |
+
with gr.Group():
|
| 875 |
+
movie = gr.Textbox(label="Favorite Movie")
|
| 876 |
+
movie_reason = gr.Textbox(label="Why do you like it?", lines=2)
|
| 877 |
+
show = gr.Textbox(label="Favorite TV Show")
|
| 878 |
+
show_reason = gr.Textbox(label="Why do you like it?", lines=2)
|
| 879 |
+
book = gr.Textbox(label="Favorite Book")
|
| 880 |
+
book_reason = gr.Textbox(label="Why do you like it?", lines=2)
|
| 881 |
+
character = gr.Textbox(label="Favorite Character (from any story)")
|
| 882 |
+
character_reason = gr.Textbox(label="Why do you like them?", lines=2)
|
| 883 |
+
|
| 884 |
+
with gr.Column(scale=1):
|
| 885 |
+
gr.Markdown("### Additional Information")
|
| 886 |
+
|
| 887 |
+
blog_checkbox = gr.Checkbox(
|
| 888 |
+
label="Would you like to write a short blog about your learning experiences?",
|
| 889 |
+
value=False
|
| 890 |
+
)
|
| 891 |
+
blog_text = gr.Textbox(
|
| 892 |
+
label="Your Learning Blog",
|
| 893 |
+
placeholder="Write about your learning journey, challenges, goals...",
|
| 894 |
+
lines=8,
|
| 895 |
+
visible=False
|
| 896 |
+
)
|
| 897 |
+
blog_checkbox.change(
|
| 898 |
+
lambda x: gr.update(visible=x),
|
| 899 |
+
inputs=blog_checkbox,
|
| 900 |
+
outputs=blog_text
|
| 901 |
+
)
|
| 902 |
+
|
| 903 |
+
# ===== TAB 4: Save & Review =====
|
| 904 |
+
with gr.Tab("Save Profile", id=3) as tab4:
|
| 905 |
+
with gr.Row():
|
| 906 |
+
with gr.Column(scale=1):
|
| 907 |
+
gr.Markdown("### Step 4: Review & Save Your Profile")
|
| 908 |
+
gr.Markdown("Verify your information before saving. You can return to previous steps to make changes.")
|
| 909 |
+
|
| 910 |
+
save_btn = gr.Button("Save Profile", variant="primary")
|
| 911 |
+
load_profile_dropdown = gr.Dropdown(
|
| 912 |
+
label="Or load existing profile",
|
| 913 |
+
choices=profile_manager.list_profiles(),
|
| 914 |
+
visible=bool(profile_manager.list_profiles())
|
| 915 |
+
)
|
| 916 |
+
load_btn = gr.Button("Load Profile", visible=bool(profile_manager.list_profiles()))
|
| 917 |
+
|
| 918 |
+
with gr.Column(scale=2):
|
| 919 |
+
output_summary = gr.Markdown(
|
| 920 |
+
"Your profile summary will appear here after saving.",
|
| 921 |
+
label="Profile Summary"
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
save_btn.click(
|
| 925 |
+
fn=profile_manager.save_profile,
|
| 926 |
+
inputs=[
|
| 927 |
+
name, age, interests, transcript_data, learning_output,
|
| 928 |
+
movie, movie_reason, show, show_reason,
|
| 929 |
+
book, book_reason, character, character_reason, blog_text
|
| 930 |
+
],
|
| 931 |
+
outputs=output_summary
|
| 932 |
+
)
|
| 933 |
+
|
| 934 |
+
load_btn.click(
|
| 935 |
+
fn=lambda name: profile_manager.load_profile(name),
|
| 936 |
+
inputs=load_profile_dropdown,
|
| 937 |
+
outputs=output_summary
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
# ===== TAB 5: AI Teaching Assistant =====
|
| 941 |
+
with gr.Tab("AI Assistant", id=4) as tab5:
|
| 942 |
+
gr.Markdown("## Your Personalized Learning Assistant")
|
| 943 |
+
gr.Markdown("Ask me anything about studying, your courses, grades, or learning strategies.")
|
| 944 |
+
|
| 945 |
+
chatbot = gr.ChatInterface(
|
| 946 |
+
fn=teaching_assistant.generate_response,
|
| 947 |
+
examples=[
|
| 948 |
+
"How should I study for my next math test?",
|
| 949 |
+
"What's my current GPA?",
|
| 950 |
+
"Show me my course history",
|
| 951 |
+
"How can I improve my grades in science?",
|
| 952 |
+
"What study methods match my learning style?"
|
| 953 |
+
],
|
| 954 |
+
title="",
|
| 955 |
+
retry_btn=None,
|
| 956 |
+
undo_btn=None
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
# Tab navigation buttons
|
| 960 |
+
step1.click(
|
| 961 |
+
fn=lambda: navigate_to_tab(0),
|
| 962 |
+
outputs={tab: tab for tab in tabs}
|
| 963 |
)
|
| 964 |
+
step2.click(
|
| 965 |
+
fn=lambda: navigate_to_tab(1),
|
| 966 |
+
outputs={tab: tab for tab in tabs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 967 |
)
|
| 968 |
+
step3.click(
|
| 969 |
+
fn=lambda: navigate_to_tab(2),
|
| 970 |
+
outputs={tab: tab for tab in tabs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 971 |
)
|
| 972 |
+
step4.click(
|
| 973 |
+
fn=lambda: navigate_to_tab(3),
|
| 974 |
+
outputs={tab: tab for tab in tabs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 975 |
)
|
| 976 |
+
step5.click(
|
| 977 |
+
fn=lambda: navigate_to_tab(4),
|
| 978 |
+
outputs={tab: tab for tab in tabs}
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
return app
|
| 982 |
+
|
| 983 |
+
# Create and launch the interface
|
| 984 |
+
app = create_interface()
|
| 985 |
|
| 986 |
+
# For Hugging Face Spaces, we need to call launch() in the script
|
| 987 |
+
if __name__ == "__main__":
|
| 988 |
+
app.launch()
|
| 989 |
+
|