Spaces:
Running
Running
import gradio as gr | |
import pandas as pd | |
import json | |
import os | |
import re | |
from PyPDF2 import PdfReader | |
from collections import defaultdict | |
# ========== NER MODEL HANDLING FOR SPACES ========== | |
try: | |
from transformers import pipeline | |
ner_pipeline = pipeline("ner", model="dslim/bert-base-NER") | |
except ImportError: | |
ner_pipeline = None | |
print("NER model not available - continuing without it") | |
except Exception as e: | |
ner_pipeline = None | |
print(f"Could not load NER model: {e}") | |
# ========== TRANSCRIPT PARSING ========== | |
def extract_gpa(text, gpa_type): | |
pattern = rf'{gpa_type}\s*([\d\.]+)' | |
match = re.search(pattern, text) | |
return match.group(1) if match else "N/A" | |
def extract_courses_from_table(text): | |
course_pattern = re.compile( | |
r'(\d{4}-\d{4})\s*' # School year | |
r'\|?\s*(\d+)\s*' # Grade level | |
r'\|?\s*([A-Z0-9]+)\s*' # Course code | |
r'\|?\s*([^\|]+?)\s*' # Course name (captures until next pipe) | |
r'(?:\|\s*[^\|]*){2}' # Skip Term and DstNumber | |
r'\|\s*([A-FW]?)\s*' # Grade (FG column) | |
r'(?:\|\s*[^\|]*)' # Skip Incl column | |
r'\|\s*([\d\.]+|inProgress)' # Credits | |
) | |
courses_by_grade = defaultdict(list) | |
for match in re.finditer(course_pattern, text): | |
year_range, grade_level, course_code, course_name, grade, credits = match.groups() | |
course_name = course_name.strip() | |
if 'DE:' in course_name: | |
course_name = course_name.replace('DE:', 'Dual Enrollment:') | |
if 'AP' in course_name: | |
course_name = course_name.replace('AP', 'AP ') | |
course_info = { | |
'name': f"{course_code} {course_name}", | |
'year': year_range, | |
'credits': credits | |
} | |
if grade and grade.strip(): | |
course_info['grade'] = grade.strip() | |
courses_by_grade[grade_level].append(course_info) | |
return courses_by_grade | |
def parse_transcript(file): | |
if file.name.endswith('.pdf'): | |
text = '' | |
reader = PdfReader(file) | |
for page in reader.pages: | |
text += page.extract_text() + '\n' | |
gpa_data = { | |
'weighted': extract_gpa(text, 'Weighted GPA'), | |
'unweighted': extract_gpa(text, 'Un-weighted GPA') | |
} | |
grade_match = re.search(r'Current Grade:\s*(\d+)', text) | |
grade_level = grade_match.group(1) if grade_match else "Unknown" | |
courses_by_grade = extract_courses_from_table(text) | |
output_text = f"Student Transcript Summary\n{'='*40}\n" | |
output_text += f"Current Grade Level: {grade_level}\n" | |
output_text += f"Weighted GPA: {gpa_data['weighted']}\n" | |
output_text += f"Unweighted GPA: {gpa_data['unweighted']}\n\n" | |
output_text += "Course History:\n{'='*40}\n" | |
for grade in sorted(courses_by_grade.keys(), key=int): | |
output_text += f"\nGrade {grade}:\n{'-'*30}\n" | |
for course in courses_by_grade[grade]: | |
output_text += f"- {course['name']}" | |
if 'grade' in course and course['grade']: | |
output_text += f" (Grade: {course['grade']})" | |
if 'credits' in course: | |
output_text += f" | Credits: {course['credits']}" | |
output_text += f" | Year: {course['year']}\n" | |
return output_text, { | |
"gpa": gpa_data, | |
"grade_level": grade_level, | |
"courses": dict(courses_by_grade) | |
} | |
else: | |
return "Unsupported file format (PDF only for transcript parsing)", None | |
# ========== LEARNING STYLE QUIZ ========== | |
learning_style_questions = [ | |
"When you study for a test, you prefer to:", | |
"When you need directions to a new place, you prefer:", | |
"When you learn a new skill, you prefer to:", | |
"When you're trying to concentrate, you:", | |
"When you meet new people, you remember them by:", | |
"When you're assembling furniture or a gadget, you:", | |
"When choosing a restaurant, you rely most on:", | |
"When you're in a waiting room, you typically:", | |
"When giving someone instructions, you tend to:", | |
"When you're trying to recall information, you:", | |
"When you're at a museum or exhibit, you:", | |
"When you're learning a new language, you prefer:", | |
"When you're taking notes in class, you:", | |
"When you're explaining something complex, you:", | |
"When you're at a party, you enjoy:", | |
"When you're trying to remember a phone number, you:", | |
"When you're relaxing, you prefer to:", | |
"When you're learning to use new software, you:", | |
"When you're giving a presentation, you rely on:", | |
"When you're solving a difficult problem, you:" | |
] | |
learning_style_options = [ | |
["Read the textbook (Reading/Writing)", "Listen to lectures (Auditory)", "Use diagrams/charts (Visual)", "Practice problems (Kinesthetic)"], | |
["Look at a map (Visual)", "Have someone tell you (Auditory)", "Write down directions (Reading/Writing)", "Try walking/driving there (Kinesthetic)"], | |
["Read instructions (Reading/Writing)", "Have someone show you (Visual)", "Listen to explanations (Auditory)", "Try it yourself (Kinesthetic)"], | |
["Need quiet (Reading/Writing)", "Need background noise (Auditory)", "Need to move around (Kinesthetic)", "Need visual stimulation (Visual)"], | |
["Their face (Visual)", "Their name (Auditory)", "What you talked about (Reading/Writing)", "What you did together (Kinesthetic)"], | |
["Read the instructions carefully (Reading/Writing)", "Look at the diagrams (Visual)", "Ask someone to explain (Auditory)", "Start putting pieces together (Kinesthetic)"], | |
["Online photos of the food (Visual)", "Recommendations from friends (Auditory)", "Reading the menu online (Reading/Writing)", "Remembering how it felt to eat there (Kinesthetic)"], | |
["Read magazines (Reading/Writing)", "Listen to music (Auditory)", "Watch TV (Visual)", "Fidget or move around (Kinesthetic)"], | |
["Write them down (Reading/Writing)", "Explain verbally (Auditory)", "Demonstrate (Visual)", "Guide them physically (Kinesthetic)"], | |
["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)"], | |
["Read all the descriptions (Reading/Writing)", "Listen to audio guides (Auditory)", "Look at the displays (Visual)", "Touch interactive exhibits (Kinesthetic)"], | |
["Study grammar rules (Reading/Writing)", "Listen to native speakers (Auditory)", "Use flashcards with images (Visual)", "Practice conversations (Kinesthetic)"], | |
["Write detailed paragraphs (Reading/Writing)", "Record the lecture (Auditory)", "Draw diagrams and charts (Visual)", "Doodle while listening (Kinesthetic)"], | |
["Write detailed steps (Reading/Writing)", "Explain verbally with examples (Auditory)", "Draw diagrams (Visual)", "Use physical objects to demonstrate (Kinesthetic)"], | |
["Conversations with people (Auditory)", "Watching others or the environment (Visual)", "Writing notes or texting (Reading/Writing)", "Dancing or physical activities (Kinesthetic)"], | |
["See the numbers in your head (Visual)", "Say them aloud (Auditory)", "Write them down (Reading/Writing)", "Dial them on a keypad (Kinesthetic)"], | |
["Read a book (Reading/Writing)", "Listen to music (Auditory)", "Watch TV/movies (Visual)", "Do something physical (Kinesthetic)"], | |
["Read the manual (Reading/Writing)", "Ask someone to show you (Visual)", "Call tech support (Auditory)", "Experiment with the software (Kinesthetic)"], | |
["Detailed notes (Reading/Writing)", "Verbal explanations (Auditory)", "Visual slides (Visual)", "Physical demonstrations (Kinesthetic)"], | |
["Write out possible solutions (Reading/Writing)", "Talk through it with someone (Auditory)", "Draw diagrams (Visual)", "Build a model or prototype (Kinesthetic)"] | |
] | |
def learning_style_quiz(*answers): | |
scores = { | |
"Visual": 0, | |
"Auditory": 0, | |
"Reading/Writing": 0, | |
"Kinesthetic": 0 | |
} | |
for i, answer in enumerate(answers): | |
if answer == learning_style_options[i][0]: | |
scores["Reading/Writing"] += 1 | |
elif answer == learning_style_options[i][1]: | |
scores["Auditory"] += 1 | |
elif answer == learning_style_options[i][2]: | |
scores["Visual"] += 1 | |
elif answer == learning_style_options[i][3]: | |
scores["Kinesthetic"] += 1 | |
max_score = max(scores.values()) | |
total_questions = len(learning_style_questions) | |
percentages = {style: (score/total_questions)*100 for style, score in scores.items()} | |
sorted_styles = sorted(scores.items(), key=lambda x: x[1], reverse=True) | |
result = "Your Learning Style Results:\n\n" | |
for style, score in sorted_styles: | |
result += f"{style}: {score}/{total_questions} ({percentages[style]:.1f}%)\n" | |
result += "\n" | |
primary_styles = [style for style, score in scores.items() if score == max_score] | |
if len(primary_styles) == 1: | |
result += f"Your primary learning style is: {primary_styles[0]}\n\n" | |
if primary_styles[0] == "Visual": | |
result += "Tips for Visual Learners:\n" | |
result += "- Use color coding in your notes\n" | |
result += "- Create mind maps and diagrams\n" | |
result += "- Watch educational videos\n" | |
result += "- Use flashcards with images\n" | |
elif primary_styles[0] == "Auditory": | |
result += "Tips for Auditory Learners:\n" | |
result += "- Record lectures and listen to them\n" | |
result += "- Participate in study groups\n" | |
result += "- Explain concepts out loud to yourself\n" | |
result += "- Use rhymes or songs to remember information\n" | |
elif primary_styles[0] == "Reading/Writing": | |
result += "Tips for Reading/Writing Learners:\n" | |
result += "- Write detailed notes\n" | |
result += "- Create summaries in your own words\n" | |
result += "- Read textbooks and articles\n" | |
result += "- Make lists to organize information\n" | |
else: | |
result += "Tips for Kinesthetic Learners:\n" | |
result += "- Use hands-on activities\n" | |
result += "- Take frequent movement breaks\n" | |
result += "- Create physical models\n" | |
result += "- Associate information with physical actions\n" | |
else: | |
result += f"You have multiple strong learning styles: {', '.join(primary_styles)}\n\n" | |
result += "You may benefit from combining different learning approaches.\n" | |
return result | |
# ========== PROFILE MANAGEMENT ========== | |
def save_profile(name, age, interests, transcript, learning_style, | |
movie, movie_reason, show, show_reason, | |
book, book_reason, character, character_reason, blog): | |
age = int(age) if age else 0 | |
favorites = { | |
"movie": movie, | |
"movie_reason": movie_reason, | |
"show": show, | |
"show_reason": show_reason, | |
"book": book, | |
"book_reason": book_reason, | |
"character": character, | |
"character_reason": character_reason | |
} | |
data = { | |
"name": name, | |
"age": age, | |
"interests": interests, | |
"transcript": transcript, | |
"learning_style": learning_style, | |
"favorites": favorites, | |
"blog": blog | |
} | |
os.makedirs("student_profiles", exist_ok=True) | |
json_path = os.path.join("student_profiles", f"{name.replace(' ', '_')}_profile.json") | |
with open(json_path, "w") as f: | |
json.dump(data, f, indent=2) | |
markdown_summary = f"""### Student Profile: {name} | |
**Age:** {age} | |
**Interests:** {interests} | |
**Learning Style:** {learning_style} | |
#### Transcript: | |
{transcript_display(transcript)} | |
#### Favorites: | |
- Movie: {favorites['movie']} ({favorites['movie_reason']}) | |
- Show: {favorites['show']} ({favorites['show_reason']}) | |
- Book: {favorites['book']} ({favorites['book_reason']}) | |
- Character: {favorites['character']} ({favorites['character_reason']}) | |
#### Blog: | |
{blog if blog else "_No blog provided_"} | |
""" | |
return markdown_summary | |
def transcript_display(transcript_dict): | |
if not transcript_dict or "courses" not in transcript_dict: | |
return "No course information available" | |
display = "### Detailed Course History\n" | |
courses_by_grade = transcript_dict["courses"] | |
if isinstance(courses_by_grade, dict): | |
for grade in sorted(courses_by_grade.keys(), key=int): | |
display += f"\n**Grade {grade}**\n" | |
for course in courses_by_grade[grade]: | |
display += f"- {course['name']}" | |
if 'grade' in course and course['grade']: | |
display += f" (Grade: {course['grade']})" | |
if 'credits' in course: | |
display += f" | Credits: {course['credits']}" | |
display += f" | Year: {course['year']}\n" | |
if 'gpa' in transcript_dict: | |
gpa = transcript_dict['gpa'] | |
display += "\n**GPA Information**\n" | |
display += f"- Unweighted: {gpa.get('unweighted', 'N/A')}\n" | |
display += f"- Weighted: {gpa.get('weighted', 'N/A')}\n" | |
return display | |
def load_profile(): | |
if not os.path.exists("student_profiles"): | |
return {} | |
files = [f for f in os.listdir("student_profiles") if f.endswith('.json')] | |
if files: | |
with open(os.path.join("student_profiles", files[0]), "r") as f: | |
return json.load(f) | |
return {} | |
def generate_response(message, history): | |
profile = load_profile() | |
if not profile: | |
return "Please complete and save your profile first using the previous tabs." | |
learning_style = profile.get("learning_style", "") | |
grade_level = profile.get("transcript", {}).get("grade_level", "unknown") | |
gpa = profile.get("transcript", {}).get("gpa", {}) | |
interests = profile.get("interests", "") | |
courses = profile.get("transcript", {}).get("courses", {}) | |
greetings = ["hi", "hello", "hey"] | |
study_help = ["study", "learn", "prepare", "exam"] | |
grade_help = ["grade", "gpa", "score"] | |
interest_help = ["interest", "hobby", "passion"] | |
course_help = ["courses", "classes", "transcript", "schedule"] | |
if any(greet in message.lower() for greet in greetings): | |
return f"Hello {profile.get('name', 'there')}! How can I help you today?" | |
elif any(word in message.lower() for word in study_help): | |
if "Visual" in learning_style: | |
response = ("Based on your visual learning style, I recommend:\n" | |
"- Creating mind maps or diagrams\n" | |
"- Using color-coded notes\n" | |
"- Watching educational videos") | |
elif "Auditory" in learning_style: | |
response = ("Based on your auditory learning style, I recommend:\n" | |
"- Recording lectures and listening to them\n" | |
"- Participating in study groups\n" | |
"- Explaining concepts out loud") | |
elif "Reading/Writing" in learning_style: | |
response = ("Based on your reading/writing learning style, I recommend:\n" | |
"- Writing detailed notes\n" | |
"- Creating summaries in your own words\n" | |
"- Reading textbooks and articles") | |
elif "Kinesthetic" in learning_style: | |
response = ("Based on your kinesthetic learning style, I recommend:\n" | |
"- Hands-on practice\n" | |
"- Creating physical models\n" | |
"- Taking frequent movement breaks") | |
else: | |
response = ("Here are some general study tips:\n" | |
"- Break study sessions into 25-minute chunks\n" | |
"- Review material regularly\n" | |
"- Teach concepts to someone else") | |
return response | |
elif any(word in message.lower() for word in grade_help): | |
return (f"Your GPA information:\n" | |
f"- Unweighted: {gpa.get('unweighted', 'N/A')}\n" | |
f"- Weighted: {gpa.get('weighted', 'N/A')}\n\n" | |
"To improve your grades, try:\n" | |
"- Setting specific goals\n" | |
"- Meeting with teachers\n" | |
"- Developing a study schedule") | |
elif any(word in message.lower() for word in interest_help): | |
return (f"I see you're interested in: {interests}\n\n" | |
"You might want to:\n" | |
"- Find clubs or activities related to these interests\n" | |
"- Explore career paths that align with them") | |
elif any(word in message.lower() for word in course_help): | |
response = "Here's a summary of your courses:\n" | |
for grade in sorted(courses.keys(), key=int): | |
response += f"\nGrade {grade}:\n" | |
for course in courses[grade]: | |
response += f"- {course['name']}" | |
if 'grade' in course: | |
response += f" (Grade: {course['grade']})" | |
response += "\n" | |
return response | |
elif "help" in message.lower(): | |
return ("I can help with:\n" | |
"- Study tips based on your learning style\n" | |
"- GPA and grade information\n" | |
"- Course history and schedules\n" | |
"- General academic advice\n\n" | |
"Try asking about study strategies or your grades!") | |
else: | |
return ("I'm your personalized teaching assistant. " | |
"I can help with study tips, grade information, and academic advice. " | |
"Try asking about how to study for your classes!") | |
# ========== GRADIO INTERFACE ========== | |
with gr.Blocks() as app: | |
with gr.Tab("Step 1: Upload Transcript"): | |
gr.Markdown("### Upload your transcript (PDF recommended for best results)") | |
transcript_file = gr.File(label="Transcript file", file_types=[".pdf"]) | |
transcript_output = gr.Textbox(label="Transcript Results", lines=20) | |
transcript_data = gr.State() | |
transcript_file.change( | |
fn=parse_transcript, | |
inputs=transcript_file, | |
outputs=[transcript_output, transcript_data] | |
) | |
with gr.Tab("Step 2: Learning Style Quiz"): | |
gr.Markdown("### Learning Style Quiz (20 Questions)") | |
quiz_components = [] | |
for i, (question, options) in enumerate(zip(learning_style_questions, learning_style_options)): | |
quiz_components.append(gr.Radio(options, label=f"{i+1}. {question}")) | |
learning_output = gr.Textbox(label="Your Learning Style", lines=15) | |
gr.Button("Submit Quiz").click( | |
fn=learning_style_quiz, | |
inputs=quiz_components, | |
outputs=learning_output | |
) | |
with gr.Tab("Step 3: Personal Questions"): | |
name = gr.Textbox(label="What's your name?") | |
age = gr.Number(label="How old are you?", precision=0) | |
interests = gr.Textbox(label="What are your interests?") | |
movie = gr.Textbox(label="Favorite movie?") | |
movie_reason = gr.Textbox(label="Why do you like that movie?") | |
show = gr.Textbox(label="Favorite TV show?") | |
show_reason = gr.Textbox(label="Why do you like that show?") | |
book = gr.Textbox(label="Favorite book?") | |
book_reason = gr.Textbox(label="Why do you like that book?") | |
character = gr.Textbox(label="Favorite character?") | |
character_reason = gr.Textbox(label="Why do you like that character?") | |
blog_checkbox = gr.Checkbox(label="Do you want to write a blog?", value=False) | |
blog_text = gr.Textbox(label="Write your blog here", visible=False, lines=5) | |
blog_checkbox.change(lambda x: gr.update(visible=x), inputs=blog_checkbox, outputs=blog_text) | |
with gr.Tab("Step 4: Save & Review"): | |
output_summary = gr.Markdown() | |
save_btn = gr.Button("Save Profile") | |
save_btn.click( | |
fn=save_profile, | |
inputs=[name, age, interests, transcript_data, learning_output, | |
movie, movie_reason, show, show_reason, | |
book, book_reason, character, character_reason, blog_text], | |
outputs=output_summary | |
) | |
with gr.Tab("🤖 AI Teaching Assistant"): | |
gr.Markdown("## Your Personalized Learning Assistant") | |
chatbot = gr.ChatInterface( | |
fn=generate_response, | |
examples=[ | |
"How should I study for my next test?", | |
"What's my GPA information?", | |
"Show me my course history", | |
"How can I improve my grades?" | |
] | |
) | |
app.launch() | |