Final_project / app.py
Dannyar608's picture
Update app.py
8ed0244 verified
raw
history blame
7.87 kB
import gradio as gr
import pandas as pd
import PyPDF2
import json
import re
# Parse uploaded transcript file
def parse_transcript(file):
if file.name.endswith('.csv'):
df = pd.read_csv(file.name)
elif file.name.endswith(('.xls', '.xlsx')):
df = pd.read_excel(file.name)
elif file.name.endswith('.pdf'):
reader = PyPDF2.PdfReader(file)
text = ""
for page in reader.pages:
text += page.extract_text() or ""
df = pd.DataFrame({'Transcript_Text': [text]})
else:
raise ValueError("Unsupported file format. Use .csv, .xlsx, or .pdf")
return df
# Extract student info
def extract_transcript_info(df):
transcript_text = df['Transcript_Text'].iloc[0] if 'Transcript_Text' in df.columns else ''
info = {}
gpa_match = re.search(r'(GPA|Grade Point Average)[^\d]*(\d+\.\d+)', transcript_text, re.IGNORECASE)
if gpa_match:
info['GPA'] = gpa_match.group(2)
grade_match = re.search(r'Grade:?[\s]*(\d{1,2})', transcript_text, re.IGNORECASE)
if grade_match:
info['Grade_Level'] = grade_match.group(1)
courses = re.findall(r'(?i)\b([A-Z][a-zA-Z\s&/]+)\s+(\d{1,3})\b', transcript_text)
if courses:
info['Courses'] = list(set([c[0].strip() for c in courses]))
return info
# Learning style questions - from educationplanner.org
learning_style_questions = [
"When you are learning something new, you prefer to:",
"When you are at home, you like to:",
"When you spell a word, you remember it by:",
"When you read, you:",
"When you write, you:",
"When you listen to music, you:",
"When you work at solving a problem, you:",
"When you give someone directions, you:",
"When you are concentrating, you:",
"When you meet someone new, you remember them by:"
]
learning_style_answers = [
["Watch someone do it", "Listen to someone explain it", "Read about it"],
["Watch TV or play video games", "Listen to music or talk to people", "Read books or write stories"],
["Seeing the word in your mind", "Saying the word out loud", "Writing the word down"],
["See the action in your mind", "Hear the characters talk", "Focus on the written words"],
["Use diagrams or doodles", "Talk about ideas", "Write detailed notes"],
["Appreciate the rhythm and melodies", "Easily remember lyrics", "Analyze the lyrics"],
["Visualize the solution", "Discuss the problem", "Write out the steps"],
["Draw a map", "Give spoken directions", "Write directions"],
["Picture things", "Say things out loud", "Write or read quietly"],
["Remember faces", "Remember names or voices", "Remember what you wrote about them"]
]
style_count_map = {0: "visual", 1: "auditory", 2: "reading/writing"}
def learning_style_quiz(*answers):
scores = {'visual': 0, 'auditory': 0, 'reading/writing': 0}
for i, ans in enumerate(answers):
if i < len(learning_style_answers):
options = learning_style_answers[i]
if ans in options:
index = options.index(ans)
style = style_count_map[index]
scores[style] += 1
max_score = max(scores.values())
best_styles = [style.capitalize() for style, score in scores.items() if score == max_score]
return ", ".join(best_styles)
# PanoramaEd categories and multiple choice questions
get_to_know_categories = {
"All About Me": [
("What’s your favorite way to spend a day off?", []),
("If you could only eat one food for the rest of your life, what would it be?", []),
("Do you have any pets? If so, what are their names?", []),
("If you could travel anywhere in the world, where would you go?", []),
("What’s your favorite holiday or tradition?", []),
("What are some of your favorite movies or shows?", []),
("Do you have a favorite book or book series? Why?", []),
("Who is a character from a show, book, or movie that you relate to? Why?", []),
("If you could be any fictional character, who would you be and why?", [])
],
"Hopes and Dreams": [
("What do you want to be when you grow up?", []),
("What’s something you hope to achieve this year?", []),
("If you could change the world in one way, what would you do?", []),
("What are you most proud of?", []),
("What’s a big dream you have for your future?", [])
],
"School Life": [
("What’s your favorite subject in school?", []),
("What’s something that makes learning easier for you?", []),
("Do you prefer working alone or in groups?", []),
("What helps you feel confident in class?", []),
("What’s something you’re good at in school?", [])
],
"Relationships": [
("Who do you look up to and why?", []),
("Who is someone that makes you feel safe and supported?", []),
("Do you have a best friend? What do you like to do together?", []),
("What’s one thing you wish people knew about you?", []),
("What’s something kind you’ve done for someone else?", [])
]
}
def display_saved_profile():
try:
with open("student_profile.json", "r") as f:
profile = json.load(f)
except FileNotFoundError:
return "⚠️ No profile data found."
transcript_info = profile.get("transcript_info", {})
gpa = transcript_info.get("GPA", "N/A")
grade = transcript_info.get("Grade_Level", "N/A")
courses = transcript_info.get("Courses", [])
past_classes = [{'Course': course, 'Grade': 'A'} for course in courses[:max(len(courses)-2, 0)]]
current_classes = [{'Course': course, 'Grade': 'IP'} for course in courses[-2:]]
all_classes_df = pd.DataFrame(past_classes + current_classes)
learning_type = profile.get("learning_style", "N/A")
responses = profile.get("get_to_know_answers", {})
blog = profile.get("blog", "[User skipped this section]")
comments = [f"⭐ I love how you spend your free time: {responses.get('What’s your favorite way to spend a day off?', 'N/A')}.",
f"🍕 {responses.get('If you could only eat one food for the rest of your life, what would it be?', 'N/A')} sounds delicious!",
f"🎬 You mentioned {responses.get('What are some of your favorite movies or shows?', 'N/A')}. Great picks!"]
blog_comment = ""
if blog and blog != "[User chose to skip this section]":
blog_comment = f"📝 Your blog was very thoughtful! You wrote: \"{blog[:150]}...\""
summary_text = f"""
👤 **Student Overview**
- Name: Extracted from transcript (if available)
- GPA: {gpa}
- Grade Level: {grade}
📚 **Courses**
{all_classes_df.to_markdown(index=False)}
🧠 **Learning Type**
Based on your answers, your learning style is: **{learning_type}**
💬 **Personal Reflections**
{chr(10).join(comments)}
{blog_comment}
❓ Is all this information correct?
"""
return summary_text
# Gradio confirmation block
with gr.Blocks() as review_block:
gr.Markdown("## ✅ Profile Review & Confirmation")
summary_output = gr.Markdown()
confirm_btn = gr.Button("Yes, everything is correct")
correct_btn = gr.Button("No, I need to make changes")
final_status = gr.Textbox(label="Final Status")
def confirm_review():
return display_saved_profile()
def finalize():
return "🎉 All set! You're ready to move forward."
def ask_to_correct():
return "🔁 Okay! Please update the necessary information and save again."
confirm_btn.click(fn=finalize, outputs=[final_status])
correct_btn.click(fn=ask_to_correct, outputs=[final_status])
review_block.load(fn=confirm_review, outputs=[summary_output]) # Automatically load profile on page reload
if __name__ == '__main__':
review_block.launch()