Yoans commited on
Commit
3204807
·
verified ·
1 Parent(s): 1133937

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -99
app.py CHANGED
@@ -1,115 +1,126 @@
1
  import gradio as gr
2
  import json
3
  import os
4
-
5
- DATA_FILE = "student_profiles.json"
6
-
7
- # ---------- Data Storage ----------
8
- def load_student_data():
9
- if not os.path.exists(DATA_FILE):
 
 
 
 
 
 
 
10
  return {}
11
- with open(DATA_FILE, "r", encoding="utf-8") as f:
12
  return json.load(f)
13
 
14
- def save_student_data(data):
15
- with open(DATA_FILE, "w", encoding="utf-8") as f:
16
- json.dump(data, f, indent=4, ensure_ascii=False)
17
-
18
- def generate_new_student_id():
19
- data = load_student_data()
20
- if not data:
21
- return "student_1"
22
- numbers = [int(k.split("_")[1]) for k in data if k.startswith("student_")]
23
- return f"student_{max(numbers) + 1}"
24
-
25
- def add_student_data(new_data):
26
- data = load_student_data()
27
- new_id = generate_new_student_id()
28
- data[new_id] = new_data
29
- save_student_data(data)
30
- return new_id, new_data
31
-
32
- # ---------- Chat & Roadmap Simulation ----------
33
- def get_gemini_response(prompt, student_data):
34
- # Replace with real LLM call later
35
- return f"(Simulated AI Response based on {student_data['personality']} profile: {prompt})"
 
 
 
 
36
 
37
  def generate_ai_insights(student_data):
38
- return f"(Insights: Your learning style is {student_data['learning_style']}, motivation is {student_data['motivation_level']})"
39
-
40
- # ---------- Gradio Interface ----------
41
- def create_profile(learning_style, academic_progress, personality, interests, goals,
42
- level, preferred_methods, iq_level, eq_level, decision_style,
43
- motivation_level, study_environment, community_groups):
44
- new_data = {
45
- "learning_style": learning_style,
46
- "academic_progress": academic_progress,
47
- "personality": personality,
48
- "interests": interests,
49
- "goals": goals,
50
- "level": level,
51
- "preferred_methods": [m.strip() for m in preferred_methods.split(",") if m.strip()],
52
- "iq_level": iq_level,
53
- "eq_level": eq_level,
54
- "decision_making_style": decision_style,
55
- "motivation_level": motivation_level,
56
- "preferred_study_environment": study_environment,
57
- "community_groups": [g.strip() for g in community_groups.split(",") if g.strip()]
58
- }
59
- new_id, saved_data = add_student_data(new_data)
60
- return f"✅ New student created with ID: {new_id}", json.dumps(saved_data, indent=2, ensure_ascii=False), list(load_student_data().keys())
61
-
62
- def chat(student_id, message):
63
- data = load_student_data()
64
- student_data = data.get(student_id)
 
65
  if not student_data:
66
- return "❌ Student not found."
67
 
68
- if message.lower() == "roadmap":
69
- return get_gemini_response("roadmap", student_data)
70
- elif message.lower() == "insights":
71
- return generate_ai_insights(student_data)
72
  else:
73
- return get_gemini_response(message, student_data)
 
74
 
75
- with gr.Blocks() as demo:
76
- gr.Markdown("# 🎓 ThinkPal – Personalized Learning Assistant")
77
 
78
- with gr.Tab("➕ Add Student"):
79
- with gr.Row():
80
- learning_style = gr.Textbox(label="Learning Style")
81
- academic_progress = gr.Textbox(label="Academic Progress")
82
- personality = gr.Textbox(label="Personality")
83
- interests = gr.Textbox(label="Interests")
84
- goals = gr.Textbox(label="Goals")
85
- level = gr.Textbox(label="Level")
86
- preferred_methods = gr.Textbox(label="Preferred Methods (comma-separated)")
87
- iq_level = gr.Textbox(label="IQ Level")
88
- eq_level = gr.Textbox(label="EQ Level")
89
- decision_style = gr.Textbox(label="Decision Style")
90
- motivation_level = gr.Textbox(label="Motivation Level")
91
- study_environment = gr.Textbox(label="Study Environment")
92
- community_groups = gr.Textbox(label="Community Groups (comma-separated)")
93
-
94
- create_btn = gr.Button("Save Profile")
95
- status = gr.Textbox(label="Status")
96
- preview = gr.Textbox(label="Profile Preview", lines=8)
97
- student_list = gr.Dropdown(label="Student IDs", choices=list(load_student_data().keys()), value=None)
98
-
99
- create_btn.click(
100
- fn=create_profile,
101
- inputs=[learning_style, academic_progress, personality, interests, goals,
102
- level, preferred_methods, iq_level, eq_level, decision_style,
103
- motivation_level, study_environment, community_groups],
104
- outputs=[status, preview, student_list]
105
- )
106
 
107
- with gr.Tab("💬 Chat"):
108
- student_select = gr.Dropdown(label="Choose Student", choices=list(load_student_data().keys()))
109
- chat_in = gr.Textbox(label="Message (type 'roadmap' or 'insights')")
110
- chat_out = gr.Textbox(label="Chatbot Response", lines=6)
111
- chat_btn = gr.Button("Send")
112
 
113
- chat_btn.click(fn=chat, inputs=[student_select, chat_in], outputs=chat_out)
 
 
 
 
114
 
115
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import json
3
  import os
4
+ import uuid
5
+
6
+ # -----------------------------
7
+ # File for student profiles
8
+ # -----------------------------
9
+ STUDENTS_FILE = "student_profiles.json"
10
+
11
+ # -----------------------------
12
+ # Student data handling
13
+ # -----------------------------
14
+ def load_students():
15
+ """Load all student profiles from JSON file."""
16
+ if not os.path.exists(STUDENTS_FILE):
17
  return {}
18
+ with open(STUDENTS_FILE, "r", encoding="utf-8") as f:
19
  return json.load(f)
20
 
21
+ def save_students(data):
22
+ """Save all student profiles to JSON file."""
23
+ with open(STUDENTS_FILE, "w", encoding="utf-8") as f:
24
+ json.dump(data, f, indent=2, ensure_ascii=False)
25
+
26
+ def get_student_data(student_id):
27
+ """Retrieve a single student profile by ID."""
28
+ students = load_students()
29
+ return students.get(student_id)
30
+
31
+ def add_student_data(data):
32
+ """Add a new student with unique random ID."""
33
+ students = load_students()
34
+ student_id = "student_" + str(uuid.uuid4())[:8] # unique random ID
35
+ students[student_id] = data
36
+ save_students(students)
37
+ return student_id
38
+
39
+ # -----------------------------
40
+ # Simulated AI responses (replace with Gemini later)
41
+ # -----------------------------
42
+ def get_gemini_response(prompt, student_data=None):
43
+ """Simulated LLM response."""
44
+ if not student_data:
45
+ return f"(Simulated Response: {prompt})"
46
+ return f"(Simulated AI Response for {student_data.get('personality','N/A')} personality: {prompt})"
47
 
48
  def generate_ai_insights(student_data):
49
+ """Simulated AI insights."""
50
+ return f"(Insights: Learning style = {student_data.get('learning_style')}, Motivation = {student_data.get('motivation_level')})"
51
+
52
+ # -----------------------------
53
+ # FAQ system (Arabic + English)
54
+ # -----------------------------
55
+ faqs = {
56
+ "إيه هو ThinkPal؟": "ThinkPal منصة بتساعدك تعرف نفسك أكتر وتتعلم بالطريقة اللي تناسبك...",
57
+ "What is ThinkPal?": "ThinkPal is a platform that helps you know yourself better...",
58
+ "لو وقفت في نص الطريق؟": "مفيش مشكلة، تقدر ترجع في أي وقت وتكمل من نفس المكان.",
59
+ "What if I stop halfway?": "No problem! You can always continue later from where you left off."
60
+ }
61
+
62
+ def find_faq_answer(user_input):
63
+ """Check if user_input matches any FAQ question."""
64
+ for q, a in faqs.items():
65
+ if user_input.strip().lower() in q.lower():
66
+ return a
67
+ return None
68
+
69
+ # -----------------------------
70
+ # Chat interface logic
71
+ # -----------------------------
72
+ def thinkpal_interface(student_id, user_input):
73
+ """Main chat interface logic."""
74
+ student_data = get_student_data(student_id)
75
+ roadmap_text, insights_text, chatbot_response_text = "", "", ""
76
+
77
  if not student_data:
78
+ return ("❌ Student not found. Please add a profile first.", "", "")
79
 
80
+ if user_input.lower() == "roadmap":
81
+ roadmap_text = get_gemini_response("roadmap", student_data) or "Could not generate roadmap."
82
+ elif user_input.lower() == "insights":
83
+ insights_text = generate_ai_insights(student_data) or "Could not generate insights."
84
  else:
85
+ faq_answer = find_faq_answer(user_input)
86
+ chatbot_response_text = faq_answer if faq_answer else get_gemini_response(user_input, student_data) or "Sorry, could not process request."
87
 
88
+ return roadmap_text, insights_text, chatbot_response_text
 
89
 
90
+ def add_new_student(data_json):
91
+ """Add student from JSON string."""
92
+ try:
93
+ data = json.loads(data_json)
94
+ except json.JSONDecodeError:
95
+ return "❌ Invalid JSON. Please check your input."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ student_id = add_student_data(data)
98
+ return f" Student added with ID: {student_id}"
 
 
 
99
 
100
+ # -----------------------------
101
+ # Gradio UI
102
+ # -----------------------------
103
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
104
+ gr.Markdown("## 🎓 ThinkPal - Personalized Learning Assistant")
105
 
106
+ with gr.Tab("💬 Chat"):
107
+ with gr.Row():
108
+ student_id_input = gr.Textbox(label="Enter Student ID", placeholder="student_1")
109
+ user_input = gr.Textbox(label="Your Question", placeholder="Type roadmap, insights, or FAQ...")
110
+ submit_btn = gr.Button("Ask")
111
+ roadmap_output = gr.Textbox(label="Roadmap", lines=8)
112
+ insights_output = gr.Textbox(label="Insights", lines=6)
113
+ chatbot_output = gr.Textbox(label="Chatbot Response", lines=4)
114
+ submit_btn.click(thinkpal_interface, [student_id_input, user_input], [roadmap_output, insights_output, chatbot_output])
115
+
116
+ with gr.Tab("➕ Add Student"):
117
+ gr.Markdown("Paste student profile data as JSON to add a new student.")
118
+ new_student_data = gr.Textbox(label="Student Data (JSON)", lines=10,
119
+ placeholder='{"learning_style": "visual", "goals": "improve math"}')
120
+ add_btn = gr.Button("Add Student")
121
+ add_output = gr.Textbox(label="Result")
122
+ add_btn.click(add_new_student, inputs=[new_student_data], outputs=[add_output])
123
+
124
+ # For Hugging Face Spaces
125
+ if __name__ == "__main__":
126
+ demo.launch()