SUMANTH-CH commited on
Commit
bc1ce79
Β·
verified Β·
1 Parent(s): 62592ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -129
app.py CHANGED
@@ -1,18 +1,12 @@
1
- # EDUTUTOR AI with Google Authentication
2
- # Note: This collects user data - ensure you have proper privacy policy and user consent
3
 
4
  import gradio as gr
5
  import torch
6
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
7
  import warnings
8
- import datetime
9
- import json
10
  warnings.filterwarnings("ignore")
11
 
12
- # User session storage (in-memory for demo - use database in production)
13
- user_sessions = {}
14
- usage_analytics = []
15
-
16
  class EduTutorAI:
17
  def __init__(self):
18
  self.model_name = "ibm-granite/granite-3.3-2b-instruct"
@@ -26,11 +20,13 @@ class EduTutorAI:
26
  try:
27
  print("Loading EDUTUTOR AI model...")
28
 
 
29
  self.tokenizer = AutoTokenizer.from_pretrained(
30
  self.model_name,
31
  trust_remote_code=True
32
  )
33
 
 
34
  self.model = AutoModelForCausalLM.from_pretrained(
35
  self.model_name,
36
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
@@ -39,6 +35,7 @@ class EduTutorAI:
39
  low_cpu_mem_usage=True
40
  )
41
 
 
42
  self.pipe = pipeline(
43
  "text-generation",
44
  model=self.model,
@@ -70,16 +67,12 @@ Please provide a comprehensive yet accessible explanation:"""
70
 
71
  return system_prompt
72
 
73
- def generate_response(self, question, subject, difficulty, max_length, user_info=None):
74
- """Generate educational response with user tracking"""
75
  if not self.pipe:
76
  return "❌ Model not loaded. Please wait for initialization."
77
 
78
  try:
79
- # Log user interaction
80
- if user_info:
81
- self.log_user_interaction(user_info, question, subject, difficulty)
82
-
83
  # Create educational prompt
84
  prompt = self.create_educational_prompt(question, subject, difficulty)
85
 
@@ -96,16 +89,16 @@ Please provide a comprehensive yet accessible explanation:"""
96
 
97
  # Extract the generated text
98
  full_response = response[0]['generated_text']
 
 
99
  ai_response = full_response.replace(prompt, "").strip()
100
 
101
  # Store in conversation history
102
  self.conversation_history.append({
103
- "user": user_info.get("name", "Anonymous") if user_info else "Anonymous",
104
  "question": question,
105
  "subject": subject,
106
  "difficulty": difficulty,
107
- "response": ai_response,
108
- "timestamp": datetime.datetime.now().isoformat()
109
  })
110
 
111
  return ai_response
@@ -113,36 +106,29 @@ Please provide a comprehensive yet accessible explanation:"""
113
  except Exception as e:
114
  return f"❌ Error generating response: {str(e)}"
115
 
116
- def log_user_interaction(self, user_info, question, subject, difficulty):
117
- """Log user interaction for analytics"""
118
- interaction = {
119
- "timestamp": datetime.datetime.now().isoformat(),
120
- "user_name": user_info.get("name", "Unknown"),
121
- "user_email": user_info.get("email", "Unknown"),
122
- "question": question,
123
- "subject": subject,
124
- "difficulty": difficulty
125
- }
126
- usage_analytics.append(interaction)
127
- print(f"πŸ“Š Logged interaction: {user_info.get('name', 'Anonymous')} asked about {subject}")
 
 
 
 
 
 
128
 
129
  # Initialize the EduTutor AI
130
  edututor = EduTutorAI()
131
 
132
- # Authentication functions
133
- def authenticate_user(username, password):
134
- """Simple authentication (replace with Google OAuth in production)"""
135
- # This is a demo - in production, use proper Google OAuth
136
- if username and password:
137
- user_info = {
138
- "name": username,
139
- "email": f"{username}@example.com",
140
- "login_time": datetime.datetime.now().isoformat()
141
- }
142
- user_sessions[username] = user_info
143
- return True, f"βœ… Welcome {username}! You are now logged in.", user_info
144
- return False, "❌ Please enter valid credentials.", None
145
-
146
  def initialize_model():
147
  """Initialize the model and return status"""
148
  success = edututor.load_model()
@@ -151,54 +137,18 @@ def initialize_model():
151
  else:
152
  return "❌ Failed to load model. Please try again."
153
 
154
- def chat_with_edututor(question, subject, difficulty, max_length, user_info):
155
- """Main chat interface function with user tracking"""
 
156
  if not question.strip():
157
  return "Please enter a question to get started!"
158
 
159
- # Parse user_info if it's a string
160
- if isinstance(user_info, str) and user_info.startswith("{"):
161
- try:
162
- user_info = json.loads(user_info)
163
- except:
164
- user_info = None
165
-
166
- response = edututor.generate_response(question, subject, difficulty, max_length, user_info)
167
  return response
168
 
169
- def get_user_analytics():
170
- """Get analytics dashboard"""
171
- if not usage_analytics:
172
- return "No user interactions logged yet."
173
-
174
- total_users = len(set([interaction["user_email"] for interaction in usage_analytics]))
175
- total_questions = len(usage_analytics)
176
-
177
- subjects = {}
178
- for interaction in usage_analytics:
179
- subject = interaction["subject"]
180
- subjects[subject] = subjects.get(subject, 0) + 1
181
-
182
- analytics = f"""
183
- πŸ“Š **EDUTUTOR AI Analytics Dashboard**
184
-
185
- πŸ‘₯ **Total Unique Users**: {total_users}
186
- ❓ **Total Questions Asked**: {total_questions}
187
-
188
- πŸ“š **Popular Subjects**:
189
- """
190
- for subject, count in sorted(subjects.items(), key=lambda x: x[1], reverse=True):
191
- analytics += f"β€’ {subject}: {count} questions\n"
192
-
193
- analytics += f"\nπŸ• **Recent Activity** (Last 5):\n"
194
- for interaction in usage_analytics[-5:]:
195
- analytics += f"β€’ {interaction['user_name']} asked about {interaction['subject']} ({interaction['timestamp'][:19]})\n"
196
-
197
- return analytics
198
-
199
- # Create Gradio interface with authentication
200
  def create_interface():
201
- """Create the EDUTUTOR AI Gradio interface with authentication"""
202
 
203
  with gr.Blocks(
204
  title="πŸŽ“ EDUTUTOR AI - Your Personal Learning Assistant",
@@ -215,13 +165,6 @@ def create_interface():
215
  border-radius: 10px;
216
  margin-bottom: 20px;
217
  }
218
- .privacy-notice {
219
- background: #f0f0f0;
220
- padding: 15px;
221
- border-radius: 5px;
222
- margin: 10px 0;
223
- border-left: 4px solid #ff6b6b;
224
- }
225
  """
226
  ) as interface:
227
 
@@ -234,26 +177,6 @@ def create_interface():
234
  </div>
235
  """)
236
 
237
- # Privacy Notice
238
- gr.HTML("""
239
- <div class="privacy-notice">
240
- <h3>πŸ”’ Privacy Notice</h3>
241
- <p><strong>Data Collection:</strong> This app collects user names, questions, and usage analytics to improve the learning experience.</p>
242
- <p><strong>By using this app, you consent to this data collection.</strong></p>
243
- <p>πŸ“§ Contact: For privacy concerns, contact the administrator.</p>
244
- </div>
245
- """)
246
-
247
- # Authentication Section
248
- with gr.Row():
249
- with gr.Column(scale=1):
250
- gr.Markdown("### πŸ” Login to EDUTUTOR AI")
251
- username_input = gr.Textbox(label="Username", placeholder="Enter your username")
252
- password_input = gr.Textbox(label="Password", type="password", placeholder="Enter your password")
253
- login_button = gr.Button("πŸ”‘ Login", variant="primary")
254
- login_status = gr.Textbox(label="Login Status", value="Please login to continue", interactive=False)
255
- user_info_state = gr.State(value=None)
256
-
257
  # Model initialization section
258
  with gr.Row():
259
  with gr.Column():
@@ -307,14 +230,15 @@ def create_interface():
307
  # Quick actions
308
  with gr.Group():
309
  gr.Markdown("### ⚑ Quick Actions")
310
- analytics_button = gr.Button("πŸ“Š View Analytics")
 
311
 
312
  gr.Markdown("### πŸ’‘ Tips")
313
  gr.Markdown("""
314
- - Login to track your learning progress
315
  - Be specific with your questions
316
  - Select appropriate subject and difficulty
317
  - Use follow-up questions for deeper understanding
 
318
  """)
319
 
320
  # Response section
@@ -326,22 +250,16 @@ def create_interface():
326
  interactive=False
327
  )
328
 
329
- # Analytics section
330
  with gr.Row():
331
- analytics_output = gr.Textbox(
332
- label="πŸ“Š Usage Analytics",
333
  lines=10,
334
  interactive=False,
335
  visible=False
336
  )
337
 
338
  # Event handlers
339
- login_button.click(
340
- fn=authenticate_user,
341
- inputs=[username_input, password_input],
342
- outputs=[gr.State(), login_status, user_info_state]
343
- )
344
-
345
  init_button.click(
346
  fn=initialize_model,
347
  outputs=init_status
@@ -349,24 +267,38 @@ def create_interface():
349
 
350
  ask_button.click(
351
  fn=chat_with_edututor,
352
- inputs=[question_input, subject_dropdown, difficulty_dropdown, max_length_slider, user_info_state],
 
 
 
 
 
 
353
  outputs=response_output
354
  )
355
 
356
- analytics_button.click(
357
- fn=get_user_analytics,
358
- outputs=analytics_output
359
  ).then(
360
  fn=lambda: gr.update(visible=True),
361
- outputs=analytics_output
 
 
 
 
 
362
  )
363
 
364
  return interface
365
 
366
  # Launch the application
367
  if __name__ == "__main__":
368
- print("πŸŽ“ Starting EDUTUTOR AI with User Authentication...")
369
  print("=" * 50)
370
 
 
371
  demo = create_interface()
 
 
372
  demo.launch()
 
1
+ # EDUTUTOR AI - Complete app.py for Hugging Face Spaces
2
+ # An intelligent AI tutor powered by IBM Granite that provides personalized educational explanations across multiple subjects and difficulty levels.
3
 
4
  import gradio as gr
5
  import torch
6
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
7
  import warnings
 
 
8
  warnings.filterwarnings("ignore")
9
 
 
 
 
 
10
  class EduTutorAI:
11
  def __init__(self):
12
  self.model_name = "ibm-granite/granite-3.3-2b-instruct"
 
20
  try:
21
  print("Loading EDUTUTOR AI model...")
22
 
23
+ # Load tokenizer
24
  self.tokenizer = AutoTokenizer.from_pretrained(
25
  self.model_name,
26
  trust_remote_code=True
27
  )
28
 
29
+ # Load model with optimization for deployment
30
  self.model = AutoModelForCausalLM.from_pretrained(
31
  self.model_name,
32
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
 
35
  low_cpu_mem_usage=True
36
  )
37
 
38
+ # Create pipeline
39
  self.pipe = pipeline(
40
  "text-generation",
41
  model=self.model,
 
67
 
68
  return system_prompt
69
 
70
+ def generate_response(self, question, subject, difficulty, max_length=512):
71
+ """Generate educational response"""
72
  if not self.pipe:
73
  return "❌ Model not loaded. Please wait for initialization."
74
 
75
  try:
 
 
 
 
76
  # Create educational prompt
77
  prompt = self.create_educational_prompt(question, subject, difficulty)
78
 
 
89
 
90
  # Extract the generated text
91
  full_response = response[0]['generated_text']
92
+
93
+ # Remove the prompt to get only the AI response
94
  ai_response = full_response.replace(prompt, "").strip()
95
 
96
  # Store in conversation history
97
  self.conversation_history.append({
 
98
  "question": question,
99
  "subject": subject,
100
  "difficulty": difficulty,
101
+ "response": ai_response
 
102
  })
103
 
104
  return ai_response
 
106
  except Exception as e:
107
  return f"❌ Error generating response: {str(e)}"
108
 
109
+ def get_conversation_history(self):
110
+ """Get formatted conversation history"""
111
+ if not self.conversation_history:
112
+ return "No conversation history yet."
113
+
114
+ history = "πŸ“š **EDUTUTOR AI - Learning Session History**\n\n"
115
+ for i, conv in enumerate(self.conversation_history[-5:], 1): # Show last 5 conversations
116
+ history += f"**Session {i}:**\n"
117
+ history += f"🎯 Subject: {conv['subject']} | Level: {conv['difficulty']}\n"
118
+ history += f"❓ Question: {conv['question']}\n"
119
+ history += f"πŸ’‘ Response: {conv['response'][:200]}...\n\n"
120
+
121
+ return history
122
+
123
+ def clear_history(self):
124
+ """Clear conversation history"""
125
+ self.conversation_history = []
126
+ return "πŸ—‘οΈ Conversation history cleared!"
127
 
128
  # Initialize the EduTutor AI
129
  edututor = EduTutorAI()
130
 
131
+ # Load model function for Gradio
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def initialize_model():
133
  """Initialize the model and return status"""
134
  success = edututor.load_model()
 
137
  else:
138
  return "❌ Failed to load model. Please try again."
139
 
140
+ # Main chat function
141
+ def chat_with_edututor(question, subject, difficulty, max_length):
142
+ """Main chat interface function"""
143
  if not question.strip():
144
  return "Please enter a question to get started!"
145
 
146
+ response = edututor.generate_response(question, subject, difficulty, max_length)
 
 
 
 
 
 
 
147
  return response
148
 
149
+ # Create Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  def create_interface():
151
+ """Create the EDUTUTOR AI Gradio interface"""
152
 
153
  with gr.Blocks(
154
  title="πŸŽ“ EDUTUTOR AI - Your Personal Learning Assistant",
 
165
  border-radius: 10px;
166
  margin-bottom: 20px;
167
  }
 
 
 
 
 
 
 
168
  """
169
  ) as interface:
170
 
 
177
  </div>
178
  """)
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  # Model initialization section
181
  with gr.Row():
182
  with gr.Column():
 
230
  # Quick actions
231
  with gr.Group():
232
  gr.Markdown("### ⚑ Quick Actions")
233
+ history_button = gr.Button("πŸ“š View Learning History")
234
+ clear_button = gr.Button("πŸ—‘οΈ Clear History")
235
 
236
  gr.Markdown("### πŸ’‘ Tips")
237
  gr.Markdown("""
 
238
  - Be specific with your questions
239
  - Select appropriate subject and difficulty
240
  - Use follow-up questions for deeper understanding
241
+ - Experiment with different difficulty levels
242
  """)
243
 
244
  # Response section
 
250
  interactive=False
251
  )
252
 
253
+ # History section
254
  with gr.Row():
255
+ history_output = gr.Textbox(
256
+ label="πŸ“š Learning Session History",
257
  lines=10,
258
  interactive=False,
259
  visible=False
260
  )
261
 
262
  # Event handlers
 
 
 
 
 
 
263
  init_button.click(
264
  fn=initialize_model,
265
  outputs=init_status
 
267
 
268
  ask_button.click(
269
  fn=chat_with_edututor,
270
+ inputs=[question_input, subject_dropdown, difficulty_dropdown, max_length_slider],
271
+ outputs=response_output
272
+ )
273
+
274
+ question_input.submit(
275
+ fn=chat_with_edututor,
276
+ inputs=[question_input, subject_dropdown, difficulty_dropdown, max_length_slider],
277
  outputs=response_output
278
  )
279
 
280
+ history_button.click(
281
+ fn=edututor.get_conversation_history,
282
+ outputs=history_output
283
  ).then(
284
  fn=lambda: gr.update(visible=True),
285
+ outputs=history_output
286
+ )
287
+
288
+ clear_button.click(
289
+ fn=edututor.clear_history,
290
+ outputs=init_status
291
  )
292
 
293
  return interface
294
 
295
  # Launch the application
296
  if __name__ == "__main__":
297
+ print("πŸŽ“ Starting EDUTUTOR AI...")
298
  print("=" * 50)
299
 
300
+ # Create and launch interface
301
  demo = create_interface()
302
+
303
+ # Launch for Hugging Face Spaces (simplified)
304
  demo.launch()