Mahdi Naser Moghadasi commited on
Commit
35cddd4
Β·
1 Parent(s): 385ad5e

Clone full BrightMind AI demo - Complete working app with all features

Browse files
Files changed (1) hide show
  1. app.py +1415 -4
app.py CHANGED
@@ -1,7 +1,1418 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
5
+ import smtplib
6
+ import sqlite3
7
+ from datetime import datetime
8
+ from email.mime.text import MIMEText
9
+ from email.mime.multipart import MIMEMultipart
10
 
11
+ # Get Hugging Face token from environment variable
12
+ HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
13
 
14
+ # Database configuration
15
+ DATABASE_FILE = "feedback.db"
16
+
17
+ # Email configuration (private)
18
+ FEEDBACK_EMAIL = "mahdi@brightmind-ai.com"
19
+ SMTP_SERVER = "smtp.gmail.com"
20
+ SMTP_PORT = 587
21
+ SMTP_USERNAME = os.getenv("SMTP_USERNAME", "")
22
+ SMTP_PASSWORD = os.getenv("SMTP_PASSWORD", "")
23
+
24
+ # Debug token detection
25
+ print(f"πŸ” Token detection debug:")
26
+ print(f" - HF_TOKEN exists: {HF_TOKEN is not None}")
27
+ print(f" - HF_TOKEN length: {len(HF_TOKEN) if HF_TOKEN else 0}")
28
+ print(f" - HF_TOKEN starts with hf_: {HF_TOKEN.startswith('hf_') if HF_TOKEN else False}")
29
+ print(f" - SMTP configured: {SMTP_USERNAME != '' and SMTP_PASSWORD != ''}")
30
+
31
+ def generate_lesson_plan_with_progress(topic, subject, grade_level, duration, difficulty="intermediate"):
32
+ """Generate a lesson plan with progress updates"""
33
+
34
+ # Show progress bar
35
+ progress_html = """
36
+ <div class="progress-container">
37
+ <div class="generation-status">πŸ€– Generating your lesson plan...</div>
38
+ <div class="progress-bar">
39
+ <div class="progress-fill"></div>
40
+ </div>
41
+ <div class="generation-status">Analyzing requirements and creating content...</div>
42
+ </div>
43
+ """
44
+
45
+ yield progress_html, ""
46
+
47
+ print(f"πŸš€ Starting lesson plan generation for: {topic}")
48
+ print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Duration: {duration}min")
49
+
50
+ # Try Hugging Face API first if token is available
51
+ if HF_TOKEN:
52
+ print("πŸ€– Token found! Attempting Hugging Face API call...")
53
+ try:
54
+ result = generate_with_hugging_face(topic, subject, grade_level, duration, difficulty)
55
+ print("βœ… Successfully generated with Hugging Face API")
56
+
57
+ # Show completion and return result
58
+ completion_html = """
59
+ <div class="progress-container">
60
+ <div class="generation-status">βœ… Lesson Plan Generated Successfully!</div>
61
+ </div>
62
+ """
63
+ yield completion_html, result
64
+
65
+ except Exception as e:
66
+ print(f"❌ Hugging Face API failed: {e}")
67
+ print("πŸ”„ Falling back to educational algorithms...")
68
+
69
+ # Show fallback progress
70
+ fallback_html = """
71
+ <div class="progress-container">
72
+ <div class="generation-status">πŸ”„ Using educational algorithms...</div>
73
+ <div class="progress-bar">
74
+ <div class="progress-fill"></div>
75
+ </div>
76
+ </div>
77
+ """
78
+ yield fallback_html, ""
79
+
80
+ result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
81
+ print("βœ… Generated with educational algorithms")
82
+
83
+ # Show completion
84
+ completion_html = """
85
+ <div class="progress-container">
86
+ <div class="generation-status">βœ… Lesson Plan Generated with Educational Algorithms!</div>
87
+ </div>
88
+ """
89
+ yield completion_html, result
90
+ else:
91
+ print("⚠️ No Hugging Face token found, using educational algorithms...")
92
+
93
+ # Show progress for algorithms
94
+ algo_html = """
95
+ <div class="progress-container">
96
+ <div class="generation-status">πŸ“š Using educational algorithms...</div>
97
+ <div class="progress-bar">
98
+ <div class="progress-fill"></div>
99
+ </div>
100
+ </div>
101
+ """
102
+ yield algo_html, ""
103
+
104
+ result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
105
+ print("βœ… Generated with educational algorithms")
106
+
107
+ # Show completion
108
+ completion_html = """
109
+ <div class="progress-container">
110
+ <div class="generation-status">βœ… Lesson Plan Generated Successfully!</div>
111
+ </div>
112
+ """
113
+ yield completion_html, result
114
+
115
+ def generate_lesson_plan(topic, subject, grade_level, duration, difficulty="intermediate"):
116
+ """Generate a lesson plan using Hugging Face API or fallback algorithms"""
117
+
118
+ print(f"πŸš€ Starting lesson plan generation for: {topic}")
119
+ print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Duration: {duration}min")
120
+
121
+ # Try Hugging Face API first if token is available
122
+ if HF_TOKEN:
123
+ print("πŸ€– Token found! Attempting Hugging Face API call...")
124
+ try:
125
+ result = generate_with_hugging_face(topic, subject, grade_level, duration, difficulty)
126
+ print("βœ… Successfully generated with Hugging Face API")
127
+ return result
128
+ except Exception as e:
129
+ print(f"❌ Hugging Face API failed: {e}")
130
+ print("πŸ”„ Falling back to educational algorithms...")
131
+ else:
132
+ print("⚠️ No Hugging Face token found, using educational algorithms...")
133
+
134
+ # Fallback to educational algorithms
135
+ result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
136
+ print("βœ… Generated with educational algorithms")
137
+ return result
138
+
139
+ def typewriter_effect(text, status_message):
140
+ """Create typewriter effect for displaying content"""
141
+ import time
142
+
143
+ # Show typewriter container
144
+ typewriter_html = f"""
145
+ <div class="typewriter-container">
146
+ <div class="typewriter-header">
147
+ <span class="book-icon">πŸ“–</span>
148
+ <span class="generation-status">{status_message}</span>
149
+ </div>
150
+ <div class="typewriter-text" id="typewriter-content">
151
+ </div>
152
+ </div>
153
+ """
154
+
155
+ yield typewriter_html, ""
156
+
157
+ # Typewriter effect
158
+ displayed_text = ""
159
+ for i, char in enumerate(text):
160
+ displayed_text += char
161
+ if char == '\n':
162
+ displayed_text += " " # Add indentation for new lines
163
+
164
+ # Update the content
165
+ updated_html = f"""
166
+ <div class="typewriter-container">
167
+ <div class="typewriter-header">
168
+ <span class="book-icon">πŸ“–</span>
169
+ <span class="generation-status">{status_message}</span>
170
+ </div>
171
+ <div class="typewriter-text">
172
+ {displayed_text}<span class="cursor">|</span>
173
+ </div>
174
+ </div>
175
+ """
176
+
177
+ yield updated_html, ""
178
+ time.sleep(0.02) # Adjust speed here
179
+
180
+ # Final result without cursor - just return the text content
181
+ yield "", text
182
+
183
+ def generate_quiz_with_progress(topic, subject, grade_level, question_count, question_types):
184
+ """Generate a quiz with progress updates"""
185
+
186
+ # Show progress bar
187
+ progress_html = """
188
+ <div class="progress-container">
189
+ <div class="generation-status">🎯 Generating your quiz...</div>
190
+ <div class="progress-bar">
191
+ <div class="progress-fill"></div>
192
+ </div>
193
+ <div class="generation-status">Creating questions and answers...</div>
194
+ </div>
195
+ """
196
+
197
+ yield progress_html, ""
198
+
199
+ print(f"🎯 Starting quiz generation for: {topic}")
200
+ print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Questions: {question_count}")
201
+ print(f"πŸ“ Question types: {', '.join(question_types)}")
202
+
203
+ # Try Hugging Face API first if token is available
204
+ if HF_TOKEN:
205
+ print("πŸ€– Token found! Attempting Hugging Face API call for quiz...")
206
+ try:
207
+ result = generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types)
208
+ print("βœ… Successfully generated quiz with Hugging Face API")
209
+
210
+ # Show completion and return result
211
+ completion_html = """
212
+ <div class="progress-container">
213
+ <div class="generation-status">βœ… Quiz Generated Successfully!</div>
214
+ </div>
215
+ """
216
+ yield completion_html, result
217
+
218
+ except Exception as e:
219
+ print(f"❌ Hugging Face API failed: {e}")
220
+ print("πŸ”„ Falling back to educational algorithms...")
221
+
222
+ # Show fallback progress
223
+ fallback_html = """
224
+ <div class="progress-container">
225
+ <div class="generation-status">πŸ”„ Using educational algorithms...</div>
226
+ <div class="progress-bar">
227
+ <div class="progress-fill"></div>
228
+ </div>
229
+ </div>
230
+ """
231
+ yield fallback_html, ""
232
+
233
+ result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
234
+ print("βœ… Generated quiz with educational algorithms")
235
+
236
+ # Show completion
237
+ completion_html = """
238
+ <div class="progress-container">
239
+ <div class="generation-status">βœ… Quiz Generated with Educational Algorithms!</div>
240
+ </div>
241
+ """
242
+ yield completion_html, result
243
+ else:
244
+ print("⚠️ No Hugging Face token found, using educational algorithms...")
245
+
246
+ # Show progress for algorithms
247
+ algo_html = """
248
+ <div class="progress-container">
249
+ <div class="generation-status">🎯 Using educational algorithms...</div>
250
+ <div class="progress-bar">
251
+ <div class="progress-fill"></div>
252
+ </div>
253
+ </div>
254
+ """
255
+ yield algo_html, ""
256
+
257
+ result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
258
+ print("βœ… Generated quiz with educational algorithms")
259
+
260
+ # Show completion
261
+ completion_html = """
262
+ <div class="progress-container">
263
+ <div class="generation-status">βœ… Quiz Generated Successfully!</div>
264
+ </div>
265
+ """
266
+ yield completion_html, result
267
+
268
+ def generate_quiz(topic, subject, grade_level, question_count, question_types):
269
+ """Generate a quiz using Hugging Face API or fallback algorithms"""
270
+
271
+ print(f"🎯 Starting quiz generation for: {topic}")
272
+ print(f"πŸ“š Subject: {subject}, Grade: {grade_level}, Questions: {question_count}")
273
+ print(f"πŸ“ Question types: {', '.join(question_types)}")
274
+
275
+ # Try Hugging Face API first if token is available
276
+ if HF_TOKEN:
277
+ print("πŸ€– Token found! Attempting Hugging Face API call for quiz...")
278
+ try:
279
+ result = generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types)
280
+ print("βœ… Successfully generated quiz with Hugging Face API")
281
+ return result
282
+ except Exception as e:
283
+ print(f"❌ Hugging Face API failed: {e}")
284
+ print("πŸ”„ Falling back to educational algorithms...")
285
+ else:
286
+ print("⚠️ No Hugging Face token found, using educational algorithms...")
287
+
288
+ # Fallback to educational algorithms
289
+ result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
290
+ print("βœ… Generated quiz with educational algorithms")
291
+ return result
292
+
293
+ def generate_with_hugging_face(topic, subject, grade_level, duration, difficulty):
294
+ """Generate lesson plan using Hugging Face Inference Providers API"""
295
+
296
+ print(f"🌐 Making API call to Hugging Face Inference Providers...")
297
+ print(f"πŸ”— Endpoint: https://router.huggingface.co/v1/chat/completions")
298
+ print(f"πŸ”‘ Token available: {HF_TOKEN is not None}")
299
+
300
+ prompt = f"""Create a comprehensive lesson plan for:
301
+ Topic: {topic}
302
+ Subject: {subject}
303
+ Grade Level: {grade_level}
304
+ Duration: {duration} minutes
305
+ Difficulty: {difficulty}
306
+
307
+ Include:
308
+ 1. Learning objectives
309
+ 2. Activities with time allocations
310
+ 3. Materials needed
311
+ 4. Assessment methods
312
+ 5. Differentiation strategies
313
+ 6. Educational standards
314
+
315
+ Format as a structured lesson plan."""
316
+
317
+ print(f"πŸ“ Prompt length: {len(prompt)}")
318
+
319
+ headers = {
320
+ "Authorization": f"Bearer {HF_TOKEN}",
321
+ "Content-Type": "application/json"
322
+ }
323
+
324
+ data = {
325
+ "model": "deepseek-ai/DeepSeek-V3-0324",
326
+ "messages": [
327
+ {
328
+ "role": "user",
329
+ "content": prompt
330
+ }
331
+ ],
332
+ "max_tokens": 1000,
333
+ "temperature": 0.7
334
+ }
335
+
336
+ print(f"πŸ“‘ Sending API request...")
337
+ try:
338
+ response = requests.post(
339
+ "https://router.huggingface.co/v1/chat/completions",
340
+ headers=headers,
341
+ json=data,
342
+ timeout=30
343
+ )
344
+
345
+ print(f"πŸ“‘ API Response Status: {response.status_code}")
346
+
347
+ if response.status_code == 200:
348
+ result = response.json()
349
+ print(f"βœ… API Response received: {type(result)}")
350
+ print(f"πŸ“„ Response content length: {len(str(result))}")
351
+
352
+ if "choices" in result and len(result["choices"]) > 0:
353
+ content = result["choices"][0]["message"]["content"]
354
+ else:
355
+ content = ""
356
+
357
+ print(f"πŸ“ Generated content length: {len(content)}")
358
+
359
+ if content and len(content) > 50: # Ensure we got meaningful content
360
+ return format_lesson_plan(content, topic, subject, grade_level, duration, True)
361
+ else:
362
+ print("⚠️ API returned empty or too short content, falling back to algorithms")
363
+ raise Exception("Empty or insufficient content from API")
364
+ else:
365
+ error_text = response.text
366
+ print(f"❌ API Error: {response.status_code} - {error_text}")
367
+ raise Exception(f"API request failed: {response.status_code} - {error_text}")
368
+
369
+ except requests.exceptions.Timeout:
370
+ print("⏰ API request timed out, falling back to algorithms")
371
+ raise Exception("API request timeout")
372
+ except requests.exceptions.RequestException as e:
373
+ print(f"🌐 Network error: {e}, falling back to algorithms")
374
+ raise Exception(f"Network error: {e}")
375
+ except Exception as e:
376
+ print(f"❌ Unexpected error: {e}, falling back to algorithms")
377
+ raise Exception(f"Unexpected error: {e}")
378
+
379
+ def generate_with_algorithms(topic, subject, grade_level, duration, difficulty):
380
+ """Generate lesson plan using educational algorithms"""
381
+
382
+ grade = int(grade_level.split('-')[0]) if '-' in grade_level else int(grade_level)
383
+
384
+ # Generate objectives based on Bloom's Taxonomy
385
+ objectives = generate_objectives(topic, grade)
386
+
387
+ # Generate activities
388
+ activities = generate_activities(topic, int(duration), grade)
389
+
390
+ # Generate materials
391
+ materials = generate_materials(subject, grade)
392
+
393
+ # Generate assessment
394
+ assessment = generate_assessment(grade)
395
+
396
+ # Generate differentiation
397
+ differentiation = generate_differentiation()
398
+
399
+ lesson_plan = {
400
+ "topic": topic,
401
+ "subject": subject,
402
+ "grade_level": grade_level,
403
+ "duration": duration,
404
+ "difficulty": difficulty,
405
+ "objectives": objectives,
406
+ "activities": activities,
407
+ "materials": materials,
408
+ "assessment": assessment,
409
+ "differentiation": differentiation,
410
+ "ai_generated": False,
411
+ "generated_at": datetime.now().strftime("%Y-%m-%d")
412
+ }
413
+
414
+ return format_lesson_plan_from_dict(lesson_plan)
415
+
416
+ def generate_objectives(topic, grade):
417
+ """Generate learning objectives based on grade level"""
418
+ if grade <= 2:
419
+ return [
420
+ f"Students will identify key concepts about {topic}",
421
+ f"Students will demonstrate understanding through hands-on activities"
422
+ ]
423
+ elif grade <= 5:
424
+ return [
425
+ f"Students will explain the main concepts of {topic}",
426
+ f"Students will apply knowledge through practical exercises",
427
+ f"Students will analyze information about {topic}"
428
+ ]
429
+ elif grade <= 8:
430
+ return [
431
+ f"Students will analyze and evaluate information about {topic}",
432
+ f"Students will synthesize knowledge through creative projects",
433
+ f"Students will demonstrate critical thinking skills"
434
+ ]
435
+ else:
436
+ return [
437
+ f"Students will critically analyze complex concepts in {topic}",
438
+ f"Students will synthesize information from multiple sources",
439
+ f"Students will create original work demonstrating mastery"
440
+ ]
441
+
442
+ def generate_activities(topic, duration, grade):
443
+ """Generate activities with time allocations"""
444
+ activities = []
445
+
446
+ # Introduction (15% of time)
447
+ intro_time = max(5, int(duration * 0.15))
448
+ activities.append({
449
+ "name": f"Introduction to {topic}",
450
+ "duration": f"{intro_time} minutes",
451
+ "description": f"Engage students with a hook activity related to {topic}"
452
+ })
453
+
454
+ # Main activities (60% of time)
455
+ main_time = int(duration * 0.6)
456
+ if grade <= 2:
457
+ activities.append({
458
+ "name": "Hands-on Exploration",
459
+ "duration": f"{main_time} minutes",
460
+ "description": f"Interactive exploration of {topic} through manipulatives and visual aids"
461
+ })
462
+ elif grade <= 5:
463
+ activities.append({
464
+ "name": "Guided Discovery",
465
+ "duration": f"{int(main_time * 0.6)} minutes",
466
+ "description": f"Structured exploration of {topic} with teacher guidance"
467
+ })
468
+ activities.append({
469
+ "name": "Collaborative Learning",
470
+ "duration": f"{int(main_time * 0.4)} minutes",
471
+ "description": f"Group work to deepen understanding of {topic}"
472
+ })
473
+ else:
474
+ activities.append({
475
+ "name": "Independent Research",
476
+ "duration": f"{int(main_time * 0.4)} minutes",
477
+ "description": f"Students research aspects of {topic} independently"
478
+ })
479
+ activities.append({
480
+ "name": "Discussion and Analysis",
481
+ "duration": f"{int(main_time * 0.6)} minutes",
482
+ "description": f"Class discussion analyzing different perspectives on {topic}"
483
+ })
484
+
485
+ # Practice (20% of time)
486
+ practice_time = int(duration * 0.2)
487
+ activities.append({
488
+ "name": "Practice and Application",
489
+ "duration": f"{practice_time} minutes",
490
+ "description": f"Students apply their knowledge through exercises related to {topic}"
491
+ })
492
+
493
+ return activities
494
+
495
+ def generate_materials(subject, grade):
496
+ """Generate materials based on subject and grade"""
497
+ materials = ["Whiteboard or chart paper", "Markers or chalk"]
498
+
499
+ if grade <= 2:
500
+ materials.extend(["Visual aids and pictures", "Manipulatives or hands-on objects", "Colored pencils and paper"])
501
+ elif grade <= 5:
502
+ materials.extend(["Textbooks or reference materials", "Worksheets or activity sheets", "Art supplies for projects"])
503
+ elif grade <= 8:
504
+ materials.extend(["Research materials (books, articles)", "Technology devices (if available)", "Presentation materials"])
505
+ else:
506
+ materials.extend(["Advanced reference materials", "Technology for research and presentation", "Writing materials for essays or reports"])
507
+
508
+ # Subject-specific materials
509
+ if subject.lower() == "science":
510
+ materials.extend(["Science equipment or models", "Safety materials (if needed)"])
511
+ elif subject.lower() == "math":
512
+ materials.extend(["Calculators (if appropriate)", "Graph paper or rulers"])
513
+ elif subject.lower() == "history":
514
+ materials.extend(["Historical documents or primary sources", "Maps or timelines"])
515
+
516
+ return materials
517
+
518
+ def generate_assessment(grade):
519
+ """Generate assessment methods based on grade level"""
520
+ if grade <= 2:
521
+ return ["Observation of student participation", "Simple oral questions and answers", "Drawing or visual representation of learning"]
522
+ elif grade <= 5:
523
+ return ["Quick quiz or exit ticket", "Student presentations or demonstrations", "Portfolio of completed work"]
524
+ elif grade <= 8:
525
+ return ["Written reflection or journal entry", "Group project evaluation", "Peer assessment activities"]
526
+ else:
527
+ return ["Essay or written analysis", "Research project presentation", "Peer review and self-assessment"]
528
+
529
+ def generate_differentiation():
530
+ """Generate differentiation strategies"""
531
+ return {
532
+ "struggling": [
533
+ "Provide additional visual aids and examples",
534
+ "Break down complex concepts into smaller parts",
535
+ "Offer one-on-one support during activities",
536
+ "Use simplified language and vocabulary"
537
+ ],
538
+ "advanced": [
539
+ "Provide extension activities and challenges",
540
+ "Encourage independent research and exploration",
541
+ "Assign leadership roles in group activities",
542
+ "Offer opportunities for creative expression"
543
+ ],
544
+ "ell": [
545
+ "Use visual supports and gestures",
546
+ "Provide vocabulary lists and definitions",
547
+ "Pair with native speakers for support",
548
+ "Use multimedia resources when available"
549
+ ]
550
+ }
551
+
552
+ def format_lesson_plan(content, topic, subject, grade_level, duration, ai_generated):
553
+ """Format lesson plan from AI response"""
554
+ return f"""
555
+ # Lesson Plan: {topic}
556
+
557
+ **Subject:** {subject}
558
+ **Grade Level:** {grade_level}
559
+ **Duration:** {duration} minutes
560
+ **Generated:** {datetime.now().strftime("%Y-%m-%d")}
561
+ **AI Generated:** {'Yes' if ai_generated else 'No'}
562
+
563
+ ---
564
+
565
+ ## Content
566
+
567
+ {content}
568
+
569
+ ---
570
+
571
+ *Generated by BrightMind AI - Educational Technology Platform*
572
+ """
573
+
574
+ def format_lesson_plan_from_dict(lesson_plan):
575
+ """Format lesson plan from dictionary"""
576
+ content = f"""
577
+ # Lesson Plan: {lesson_plan['topic']}
578
+
579
+ **Subject:** {lesson_plan['subject']}
580
+ **Grade Level:** {lesson_plan['grade_level']}
581
+ **Duration:** {lesson_plan['duration']} minutes
582
+ **Difficulty:** {lesson_plan['difficulty']}
583
+ **Generated:** {lesson_plan['generated_at']}
584
+ **AI Generated:** {'Yes' if lesson_plan['ai_generated'] else 'No'}
585
+
586
+ ---
587
+
588
+ ## Learning Objectives
589
+
590
+ """
591
+
592
+ for i, objective in enumerate(lesson_plan['objectives'], 1):
593
+ content += f"{i}. {objective}\n"
594
+
595
+ content += "\n## Activities\n\n"
596
+ for activity in lesson_plan['activities']:
597
+ content += f"**{activity['name']}** ({activity['duration']})\n"
598
+ content += f"{activity['description']}\n\n"
599
+
600
+ content += "## Materials Needed\n\n"
601
+ for material in lesson_plan['materials']:
602
+ content += f"β€’ {material}\n"
603
+
604
+ content += "\n## Assessment Methods\n\n"
605
+ for i, assessment in enumerate(lesson_plan['assessment'], 1):
606
+ content += f"{i}. {assessment}\n"
607
+
608
+ content += "\n## Differentiation Strategies\n\n"
609
+ for category, strategies in lesson_plan['differentiation'].items():
610
+ content += f"**{category.title()} Learners:**\n"
611
+ for strategy in strategies:
612
+ content += f"β€’ {strategy}\n"
613
+ content += "\n"
614
+
615
+ content += "\n---\n*Generated by BrightMind AI - Educational Technology Platform*"
616
+
617
+ return content
618
+
619
+ def generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types):
620
+ """Generate quiz using Hugging Face Inference Providers API"""
621
+
622
+ print(f"🌐 Making API call to Hugging Face Inference Providers for quiz...")
623
+ print(f"πŸ”— Endpoint: https://router.huggingface.co/v1/chat/completions")
624
+ print(f"πŸ”‘ Token available: {HF_TOKEN is not None}")
625
+
626
+ prompt = f"""Create a quiz about "{topic}" for {grade_level} students studying {subject}.
627
+
628
+ Requirements:
629
+ - Generate exactly {question_count} questions
630
+ - Include these question types: {', '.join(question_types)}
631
+ - Make questions appropriate for {grade_level} grade level
632
+ - Ensure questions are specific to "{topic}"
633
+ - Include correct answers and explanations
634
+
635
+ Format the response as a structured quiz with clear questions, options, and explanations."""
636
+
637
+ print(f"πŸ“ Prompt length: {len(prompt)}")
638
+
639
+ headers = {
640
+ "Authorization": f"Bearer {HF_TOKEN}",
641
+ "Content-Type": "application/json"
642
+ }
643
+
644
+ data = {
645
+ "model": "deepseek-ai/DeepSeek-V3-0324",
646
+ "messages": [
647
+ {
648
+ "role": "user",
649
+ "content": prompt
650
+ }
651
+ ],
652
+ "max_tokens": 1000,
653
+ "temperature": 0.7
654
+ }
655
+
656
+ print(f"πŸ“‘ Sending API request...")
657
+ try:
658
+ response = requests.post(
659
+ "https://router.huggingface.co/v1/chat/completions",
660
+ headers=headers,
661
+ json=data,
662
+ timeout=30
663
+ )
664
+
665
+ print(f"πŸ“‘ API Response Status: {response.status_code}")
666
+
667
+ if response.status_code == 200:
668
+ result = response.json()
669
+ print(f"βœ… API Response received: {type(result)}")
670
+ print(f"πŸ“„ Response content length: {len(str(result))}")
671
+
672
+ if "choices" in result and len(result["choices"]) > 0:
673
+ content = result["choices"][0]["message"]["content"]
674
+ else:
675
+ content = ""
676
+
677
+ print(f"πŸ“ Generated content length: {len(content)}")
678
+
679
+ if content and len(content) > 50: # Ensure we got meaningful content
680
+ return format_quiz(content, topic, subject, grade_level, question_count, True)
681
+ else:
682
+ print("⚠️ API returned empty or too short content, falling back to algorithms")
683
+ raise Exception("Empty or insufficient content from API")
684
+ else:
685
+ error_text = response.text
686
+ print(f"❌ API Error: {response.status_code} - {error_text}")
687
+ raise Exception(f"API request failed: {response.status_code} - {error_text}")
688
+
689
+ except requests.exceptions.Timeout:
690
+ print("⏰ API request timed out, falling back to algorithms")
691
+ raise Exception("API request timeout")
692
+ except requests.exceptions.RequestException as e:
693
+ print(f"🌐 Network error: {e}, falling back to algorithms")
694
+ raise Exception(f"Network error: {e}")
695
+ except Exception as e:
696
+ print(f"❌ Unexpected error: {e}, falling back to algorithms")
697
+ raise Exception(f"Unexpected error: {e}")
698
+
699
+ def generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types):
700
+ """Generate quiz using educational algorithms"""
701
+
702
+ questions = []
703
+ grade = int(grade_level.split('-')[0]) if '-' in grade_level else int(grade_level)
704
+
705
+ for i in range(int(question_count)):
706
+ question_type = question_types[i % len(question_types)]
707
+ question = generate_question_by_type(question_type, topic, subject, grade, i + 1)
708
+ questions.append(question)
709
+
710
+ quiz = {
711
+ "topic": topic,
712
+ "subject": subject,
713
+ "grade_level": grade_level,
714
+ "question_count": int(question_count),
715
+ "questions": questions,
716
+ "generated_at": datetime.now().strftime("%Y-%m-%d"),
717
+ "ai_generated": False
718
+ }
719
+
720
+ return format_quiz_from_dict(quiz)
721
+
722
+ def generate_question_by_type(question_type, topic, subject, grade, question_number):
723
+ """Generate a specific type of question"""
724
+
725
+ if question_type == "Multiple Choice":
726
+ return generate_multiple_choice_question(topic, subject, grade, question_number)
727
+ elif question_type == "True/False":
728
+ return generate_true_false_question(topic, subject, grade, question_number)
729
+ elif question_type == "Short Answer":
730
+ return generate_short_answer_question(topic, subject, grade, question_number)
731
+ elif question_type == "Fill in the Blank":
732
+ return generate_fill_in_blank_question(topic, subject, grade, question_number)
733
+ else:
734
+ return generate_multiple_choice_question(topic, subject, grade, question_number)
735
+
736
+ def generate_multiple_choice_question(topic, subject, grade, question_number):
737
+ """Generate a multiple choice question"""
738
+
739
+ templates = [
740
+ {
741
+ "question": f"What is the main concept of {topic}?",
742
+ "options": [
743
+ f"A fundamental principle in {subject}",
744
+ "A type of animal",
745
+ "A mathematical formula",
746
+ "A historical event"
747
+ ],
748
+ "correct": "A",
749
+ "explanation": f"This question tests basic understanding of {topic} in the context of {subject}."
750
+ },
751
+ {
752
+ "question": f"Which of the following best describes {topic}?",
753
+ "options": [
754
+ "A complex system with multiple components",
755
+ "A simple process with one step",
756
+ "A type of building material",
757
+ "A musical instrument"
758
+ ],
759
+ "correct": "A",
760
+ "explanation": f"{topic} involves multiple interconnected elements that work together."
761
+ },
762
+ {
763
+ "question": f"How does {topic} relate to {subject}?",
764
+ "options": [
765
+ f"It provides a foundation for understanding {subject} concepts",
766
+ "It is unrelated to the subject",
767
+ "It only applies to advanced students",
768
+ "It is only theoretical"
769
+ ],
770
+ "correct": "A",
771
+ "explanation": f"{topic} helps students understand broader concepts in {subject}."
772
+ }
773
+ ]
774
+
775
+ template = templates[question_number % len(templates)]
776
+ return {
777
+ "type": "Multiple Choice",
778
+ "question": template["question"],
779
+ "options": template["options"],
780
+ "correct_answer": template["correct"],
781
+ "explanation": template["explanation"]
782
+ }
783
+
784
+ def generate_true_false_question(topic, subject, grade, question_number):
785
+ """Generate a true/false question"""
786
+
787
+ templates = [
788
+ {
789
+ "question": f"{topic} is an important concept in {subject}.",
790
+ "correct": "True",
791
+ "explanation": f"{topic} is indeed a fundamental concept in {subject} that students need to understand."
792
+ },
793
+ {
794
+ "question": f"{topic} can only be learned through memorization.",
795
+ "correct": "False",
796
+ "explanation": f"{topic} is best learned through understanding, practice, and application, not just memorization."
797
+ },
798
+ {
799
+ "question": f"Understanding {topic} helps students in other areas of {subject}.",
800
+ "correct": "True",
801
+ "explanation": f"Knowledge of {topic} provides a foundation for understanding related concepts in {subject}."
802
+ }
803
+ ]
804
+
805
+ template = templates[question_number % len(templates)]
806
+ return {
807
+ "type": "True/False",
808
+ "question": template["question"],
809
+ "correct_answer": template["correct"],
810
+ "explanation": template["explanation"]
811
+ }
812
+
813
+ def generate_short_answer_question(topic, subject, grade, question_number):
814
+ """Generate a short answer question"""
815
+
816
+ templates = [
817
+ {
818
+ "question": f"Explain what {topic} means in your own words.",
819
+ "correct_answer": f"Student should demonstrate understanding of {topic} concepts",
820
+ "explanation": f"This question allows students to express their understanding of {topic} in their own words."
821
+ },
822
+ {
823
+ "question": f"How does {topic} relate to {subject}?",
824
+ "correct_answer": f"Student should explain the connection between {topic} and {subject}",
825
+ "explanation": f"This question tests students' ability to make connections between concepts."
826
+ },
827
+ {
828
+ "question": f"What are the key components of {topic}?",
829
+ "correct_answer": f"Student should identify the main elements of {topic}",
830
+ "explanation": f"This question tests students' ability to break down complex concepts."
831
+ }
832
+ ]
833
+
834
+ template = templates[question_number % len(templates)]
835
+ return {
836
+ "type": "Short Answer",
837
+ "question": template["question"],
838
+ "correct_answer": template["correct_answer"],
839
+ "explanation": template["explanation"]
840
+ }
841
+
842
+ def generate_fill_in_blank_question(topic, subject, grade, question_number):
843
+ """Generate a fill in the blank question"""
844
+
845
+ templates = [
846
+ {
847
+ "question": f"{topic} is important because it helps us understand ______.",
848
+ "correct_answer": f"{subject} concepts",
849
+ "explanation": f"{topic} provides a foundation for understanding broader {subject} concepts."
850
+ },
851
+ {
852
+ "question": f"The main purpose of {topic} is to ______.",
853
+ "correct_answer": f"enhance learning in {subject}",
854
+ "explanation": f"{topic} serves to improve students' understanding of {subject}."
855
+ },
856
+ {
857
+ "question": f"Students learn {topic} to better understand ______.",
858
+ "correct_answer": f"complex {subject} concepts",
859
+ "explanation": f"{topic} helps students grasp more advanced {subject} topics."
860
+ }
861
+ ]
862
+
863
+ template = templates[question_number % len(templates)]
864
+ return {
865
+ "type": "Fill in the Blank",
866
+ "question": template["question"],
867
+ "correct_answer": template["correct_answer"],
868
+ "explanation": template["explanation"]
869
+ }
870
+
871
+ def format_quiz(content, topic, subject, grade_level, question_count, ai_generated):
872
+ """Format quiz from AI response"""
873
+ return f"""
874
+ # Quiz: {topic}
875
+
876
+ **Subject:** {subject}
877
+ **Grade Level:** {grade_level}
878
+ **Questions:** {question_count}
879
+ **Generated:** {datetime.now().strftime("%Y-%m-%d")}
880
+ **AI Generated:** {'Yes' if ai_generated else 'No'}
881
+
882
+ ---
883
+
884
+ ## Quiz Content
885
+
886
+ {content}
887
+
888
+ ---
889
+
890
+ *Generated by BrightMind AI - Educational Technology Platform*
891
+ """
892
+
893
+ def format_quiz_from_dict(quiz):
894
+ """Format quiz from dictionary"""
895
+ content = f"""
896
+ # Quiz: {quiz['topic']}
897
+
898
+ **Subject:** {quiz['subject']}
899
+ **Grade Level:** {quiz['grade_level']}
900
+ **Questions:** {quiz['question_count']}
901
+ **Generated:** {quiz['generated_at']}
902
+ **AI Generated:** {'Yes' if quiz['ai_generated'] else 'No'}
903
+
904
+ ---
905
+
906
+ ## Questions
907
+
908
+ """
909
+
910
+ for i, question in enumerate(quiz['questions'], 1):
911
+ content += f"### Question {i}: {question['type']}\n\n"
912
+ content += f"**{question['question']}**\n\n"
913
+
914
+ if question['type'] == 'Multiple Choice':
915
+ for j, option in enumerate(question['options']):
916
+ content += f"{chr(65 + j)}. {option}\n"
917
+ content += f"\n**Correct Answer:** {question['correct_answer']}\n\n"
918
+ elif question['type'] == 'True/False':
919
+ content += f"**Answer:** {question['correct_answer']}\n\n"
920
+ elif question['type'] == 'Short Answer':
921
+ content += f"**Expected Answer:** {question['correct_answer']}\n\n"
922
+ elif question['type'] == 'Fill in the Blank':
923
+ content += f"**Answer:** {question['correct_answer']}\n\n"
924
+
925
+ content += f"**Explanation:** {question['explanation']}\n\n"
926
+ content += "---\n\n"
927
+
928
+ content += "\n*Generated by BrightMind AI - Educational Technology Platform*"
929
+
930
+ return content
931
+
932
+ def send_feedback_email(feedback_type, rating, comments, user_email=""):
933
+ """Send feedback email to admin"""
934
+
935
+ if not SMTP_USERNAME or not SMTP_PASSWORD:
936
+ print("⚠️ SMTP credentials not configured, storing feedback locally")
937
+ # Store feedback locally if no email configured
938
+ feedback_data = {
939
+ "timestamp": datetime.now().isoformat(),
940
+ "feedback_type": feedback_type,
941
+ "rating": rating,
942
+ "comments": comments,
943
+ "user_email": user_email
944
+ }
945
+
946
+ # Save to local file
947
+ try:
948
+ with open("feedback_log.json", "a") as f:
949
+ f.write(json.dumps(feedback_data) + "\n")
950
+ return "βœ… Feedback saved successfully! (Email not configured)"
951
+ except Exception as e:
952
+ return f"❌ Error saving feedback: {str(e)}"
953
+
954
+ try:
955
+ # Create message
956
+ msg = MIMEMultipart()
957
+ msg['From'] = SMTP_USERNAME
958
+ msg['To'] = FEEDBACK_EMAIL
959
+ msg['Subject'] = f"BrightMind AI Feedback - {feedback_type}"
960
+
961
+ # Create email body
962
+ body = f"""
963
+ New Feedback Received from BrightMind AI Platform
964
+
965
+ Feedback Type: {', '.join(feedback_type) if isinstance(feedback_type, list) else feedback_type}
966
+ Rating: {rating}/5
967
+ User Email: {user_email if user_email else 'Not provided'}
968
+ Comments: {comments}
969
+
970
+ Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
971
+
972
+ ---
973
+ This feedback was automatically sent from the BrightMind AI platform.
974
+ """
975
+
976
+ msg.attach(MIMEText(body, 'plain'))
977
+
978
+ # Send email
979
+ server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
980
+ server.starttls()
981
+ server.login(SMTP_USERNAME, SMTP_PASSWORD)
982
+ text = msg.as_string()
983
+ server.sendmail(SMTP_USERNAME, FEEDBACK_EMAIL, text)
984
+ server.quit()
985
+
986
+ print(f"βœ… Feedback email sent successfully to {FEEDBACK_EMAIL}")
987
+ return "βœ… Thank you! Your feedback has been sent successfully."
988
+
989
+ except Exception as e:
990
+ print(f"❌ Error sending feedback email: {str(e)}")
991
+ return f"❌ Error sending feedback: {str(e)}"
992
+
993
+ def submit_feedback(feedback_type, rating, comments, user_email):
994
+ """Handle feedback submission"""
995
+
996
+ if not feedback_type:
997
+ return "❌ Please select at least one feedback type."
998
+
999
+ if not rating:
1000
+ return "❌ Please provide a rating."
1001
+
1002
+ if not comments.strip():
1003
+ return "❌ Please provide your comments."
1004
+
1005
+ # Save to database first
1006
+ db_success = save_feedback_to_db(feedback_type, rating, comments, user_email)
1007
+
1008
+ if not db_success:
1009
+ return "❌ Error saving feedback to database. Please try again."
1010
+
1011
+ # Try to send email (optional)
1012
+ email_result = send_feedback_email(feedback_type, rating, comments, user_email)
1013
+
1014
+ if "βœ…" in email_result:
1015
+ return "βœ… Thank you! Your feedback has been saved and sent successfully."
1016
+ else:
1017
+ return "βœ… Thank you! Your feedback has been saved successfully. (Email notification not available)"
1018
+
1019
+ def init_database():
1020
+ """Initialize the SQLite database"""
1021
+ try:
1022
+ conn = sqlite3.connect(DATABASE_FILE)
1023
+ cursor = conn.cursor()
1024
+
1025
+ # Create feedback table
1026
+ cursor.execute('''
1027
+ CREATE TABLE IF NOT EXISTS feedback (
1028
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1029
+ timestamp TEXT NOT NULL,
1030
+ feedback_type TEXT NOT NULL,
1031
+ rating INTEGER NOT NULL,
1032
+ comments TEXT NOT NULL,
1033
+ user_email TEXT,
1034
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
1035
+ )
1036
+ ''')
1037
+
1038
+ conn.commit()
1039
+ conn.close()
1040
+ print("βœ… Database initialized successfully")
1041
+ return True
1042
+ except Exception as e:
1043
+ print(f"❌ Database initialization error: {e}")
1044
+ return False
1045
+
1046
+ def save_feedback_to_db(feedback_type, rating, comments, user_email=""):
1047
+ """Save feedback to SQLite database"""
1048
+ try:
1049
+ conn = sqlite3.connect(DATABASE_FILE)
1050
+ cursor = conn.cursor()
1051
+
1052
+ # Convert feedback_type list to string
1053
+ feedback_type_str = ', '.join(feedback_type) if isinstance(feedback_type, list) else str(feedback_type)
1054
+
1055
+ cursor.execute('''
1056
+ INSERT INTO feedback (timestamp, feedback_type, rating, comments, user_email)
1057
+ VALUES (?, ?, ?, ?, ?)
1058
+ ''', (
1059
+ datetime.now().isoformat(),
1060
+ feedback_type_str,
1061
+ rating,
1062
+ comments,
1063
+ user_email
1064
+ ))
1065
+
1066
+ conn.commit()
1067
+ conn.close()
1068
+ print("βœ… Feedback saved to database successfully")
1069
+ return True
1070
+ except Exception as e:
1071
+ print(f"❌ Database save error: {e}")
1072
+ return False
1073
+
1074
+ def get_feedback_stats():
1075
+ """Get feedback statistics for admin"""
1076
+ try:
1077
+ conn = sqlite3.connect(DATABASE_FILE)
1078
+ cursor = conn.cursor()
1079
+
1080
+ # Get total feedback count
1081
+ cursor.execute('SELECT COUNT(*) FROM feedback')
1082
+ total_feedback = cursor.fetchone()[0]
1083
+
1084
+ # Get average rating
1085
+ cursor.execute('SELECT AVG(rating) FROM feedback')
1086
+ avg_rating = cursor.fetchone()[0]
1087
+ avg_rating = round(avg_rating, 2) if avg_rating else 0
1088
+
1089
+ # Get recent feedback (last 5)
1090
+ cursor.execute('''
1091
+ SELECT timestamp, feedback_type, rating, comments, user_email
1092
+ FROM feedback
1093
+ ORDER BY created_at DESC
1094
+ LIMIT 5
1095
+ ''')
1096
+ recent_feedback = cursor.fetchall()
1097
+
1098
+ conn.close()
1099
+
1100
+ return {
1101
+ 'total_feedback': total_feedback,
1102
+ 'avg_rating': avg_rating,
1103
+ 'recent_feedback': recent_feedback
1104
+ }
1105
+ except Exception as e:
1106
+ print(f"❌ Database stats error: {e}")
1107
+ return {
1108
+ 'total_feedback': 0,
1109
+ 'avg_rating': 0,
1110
+ 'recent_feedback': []
1111
+ }
1112
+
1113
+ def view_feedback_admin():
1114
+ """Admin function to view all feedback"""
1115
+ try:
1116
+ conn = sqlite3.connect(DATABASE_FILE)
1117
+ cursor = conn.cursor()
1118
+
1119
+ cursor.execute('''
1120
+ SELECT id, timestamp, feedback_type, rating, comments, user_email, created_at
1121
+ FROM feedback
1122
+ ORDER BY created_at DESC
1123
+ ''')
1124
+
1125
+ feedback_data = cursor.fetchall()
1126
+ conn.close()
1127
+
1128
+ if not feedback_data:
1129
+ return "No feedback found in database."
1130
+
1131
+ # Format feedback data
1132
+ result = "# πŸ“Š Feedback Database\n\n"
1133
+ result += f"**Total Feedback Entries:** {len(feedback_data)}\n\n"
1134
+
1135
+ for entry in feedback_data:
1136
+ id_val, timestamp, feedback_type, rating, comments, user_email, created_at = entry
1137
+ result += f"## Entry #{id_val}\n"
1138
+ result += f"**Date:** {timestamp}\n"
1139
+ result += f"**Type:** {feedback_type}\n"
1140
+ result += f"**Rating:** {rating}/5 ⭐\n"
1141
+ result += f"**Comments:** {comments}\n"
1142
+ result += f"**Email:** {user_email if user_email else 'Not provided'}\n"
1143
+ result += f"**Created:** {created_at}\n"
1144
+ result += "---\n\n"
1145
+
1146
+ return result
1147
+ except Exception as e:
1148
+ return f"❌ Error accessing database: {str(e)}"
1149
+
1150
+ # Initialize database on startup
1151
+ init_database()
1152
+
1153
+ # Create Gradio interface with custom CSS
1154
+ with gr.Blocks(
1155
+ title="BrightMind AI - Educational Content Generator",
1156
+ theme=gr.themes.Soft(),
1157
+ css="""
1158
+ .progress-container {
1159
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1160
+ border-radius: 15px;
1161
+ padding: 20px;
1162
+ margin: 20px 0;
1163
+ box-shadow: 0 8px 32px rgba(0,0,0,0.1);
1164
+ }
1165
+ .progress-bar {
1166
+ width: 100%;
1167
+ height: 8px;
1168
+ background: rgba(255,255,255,0.2);
1169
+ border-radius: 4px;
1170
+ overflow: hidden;
1171
+ margin: 10px 0;
1172
+ }
1173
+ .progress-fill {
1174
+ height: 100%;
1175
+ background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
1176
+ border-radius: 4px;
1177
+ animation: progress-animation 2s ease-in-out infinite;
1178
+ }
1179
+ @keyframes progress-animation {
1180
+ 0% { width: 0%; }
1181
+ 50% { width: 70%; }
1182
+ 100% { width: 100%; }
1183
+ }
1184
+ .typewriter-container {
1185
+ background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
1186
+ border-radius: 15px;
1187
+ padding: 25px;
1188
+ margin: 20px 0;
1189
+ box-shadow: 0 10px 40px rgba(0,0,0,0.1);
1190
+ border-left: 5px solid #667eea;
1191
+ }
1192
+ .typewriter-header {
1193
+ display: flex;
1194
+ align-items: center;
1195
+ margin-bottom: 15px;
1196
+ }
1197
+ .book-icon {
1198
+ font-size: 24px;
1199
+ margin-right: 10px;
1200
+ color: #8b4513;
1201
+ animation: book-flip 2s ease-in-out infinite;
1202
+ }
1203
+ @keyframes book-flip {
1204
+ 0%, 100% { transform: rotateY(0deg); }
1205
+ 50% { transform: rotateY(10deg); }
1206
+ }
1207
+ .typewriter-text {
1208
+ font-family: 'Courier New', monospace;
1209
+ font-size: 16px;
1210
+ line-height: 1.6;
1211
+ color: #2c3e50;
1212
+ white-space: pre-wrap;
1213
+ min-height: 200px;
1214
+ }
1215
+ .cursor {
1216
+ display: inline-block;
1217
+ width: 2px;
1218
+ height: 20px;
1219
+ background: #667eea;
1220
+ animation: blink 1s infinite;
1221
+ }
1222
+ @keyframes blink {
1223
+ 0%, 50% { opacity: 1; }
1224
+ 51%, 100% { opacity: 0; }
1225
+ }
1226
+ .generation-status {
1227
+ text-align: center;
1228
+ color: #667eea;
1229
+ font-weight: 600;
1230
+ margin: 10px 0;
1231
+ }
1232
+ .professional-header {
1233
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1234
+ color: white;
1235
+ padding: 30px;
1236
+ border-radius: 15px;
1237
+ text-align: center;
1238
+ margin-bottom: 30px;
1239
+ box-shadow: 0 10px 40px rgba(0,0,0,0.1);
1240
+ }
1241
+ .professional-header h1 {
1242
+ margin: 0;
1243
+ font-size: 2.5em;
1244
+ font-weight: 700;
1245
+ }
1246
+ .professional-header p {
1247
+ margin: 10px 0 0 0;
1248
+ font-size: 1.2em;
1249
+ opacity: 0.9;
1250
+ }
1251
+ """
1252
+ ) as demo:
1253
+
1254
+ # Professional Header
1255
+ with gr.Row():
1256
+ gr.HTML("""
1257
+ <div class="professional-header">
1258
+ <h1>🧠 BrightMind AI</h1>
1259
+ <p>Professional Educational Content Generator for Teachers</p>
1260
+ </div>
1261
+ """)
1262
+
1263
+ with gr.Tabs():
1264
+ with gr.TabItem("πŸ“š Lesson Plan Generator"):
1265
+ with gr.Row():
1266
+ with gr.Column():
1267
+ topic = gr.Textbox(label="Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
1268
+ subject = gr.Dropdown(
1269
+ choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
1270
+ label="Subject",
1271
+ value="Science"
1272
+ )
1273
+ grade_level = gr.Dropdown(
1274
+ choices=["K-2", "3-5", "6-8", "9-12"],
1275
+ label="Grade Level",
1276
+ value="6-8"
1277
+ )
1278
+ duration = gr.Slider(
1279
+ minimum=30,
1280
+ maximum=180,
1281
+ step=15,
1282
+ value=60,
1283
+ label="Duration (minutes)"
1284
+ )
1285
+ difficulty = gr.Dropdown(
1286
+ choices=["Beginner", "Intermediate", "Advanced"],
1287
+ label="Difficulty",
1288
+ value="Intermediate"
1289
+ )
1290
+
1291
+ generate_lesson_btn = gr.Button("Generate Lesson Plan", variant="primary")
1292
+
1293
+ with gr.Column():
1294
+ progress_display = gr.HTML(visible=False)
1295
+ lesson_output = gr.Markdown(label="Generated Lesson Plan")
1296
+
1297
+ # Event handlers
1298
+ generate_lesson_btn.click(
1299
+ fn=generate_lesson_plan_with_progress,
1300
+ inputs=[topic, subject, grade_level, duration, difficulty],
1301
+ outputs=[progress_display, lesson_output],
1302
+ show_progress=True
1303
+ )
1304
+
1305
+ # Examples
1306
+ gr.Examples(
1307
+ examples=[
1308
+ ["Photosynthesis", "Science", "6-8", 60, "Intermediate"],
1309
+ ["World War II", "History", "9-12", 90, "Advanced"],
1310
+ ["Basic Algebra", "Mathematics", "3-5", 45, "Beginner"]
1311
+ ],
1312
+ inputs=[topic, subject, grade_level, duration, difficulty]
1313
+ )
1314
+
1315
+ with gr.TabItem("🎯 Quiz Generator"):
1316
+ with gr.Row():
1317
+ with gr.Column():
1318
+ quiz_topic = gr.Textbox(label="Quiz Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
1319
+ quiz_subject = gr.Dropdown(
1320
+ choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
1321
+ label="Subject",
1322
+ value="Science"
1323
+ )
1324
+ quiz_grade_level = gr.Dropdown(
1325
+ choices=["K-2", "3-5", "6-8", "9-12"],
1326
+ label="Grade Level",
1327
+ value="6-8"
1328
+ )
1329
+ question_count = gr.Slider(
1330
+ minimum=3,
1331
+ maximum=20,
1332
+ step=1,
1333
+ value=5,
1334
+ label="Number of Questions"
1335
+ )
1336
+ question_types = gr.CheckboxGroup(
1337
+ choices=["Multiple Choice", "True/False", "Short Answer", "Fill in the Blank"],
1338
+ label="Question Types",
1339
+ value=["Multiple Choice", "True/False"]
1340
+ )
1341
+
1342
+ generate_quiz_btn = gr.Button("Generate Quiz", variant="primary")
1343
+
1344
+ with gr.Column():
1345
+ quiz_progress_display = gr.HTML(visible=False)
1346
+ quiz_output = gr.Markdown(label="Generated Quiz")
1347
+
1348
+ # Event handlers
1349
+ generate_quiz_btn.click(
1350
+ fn=generate_quiz_with_progress,
1351
+ inputs=[quiz_topic, quiz_subject, quiz_grade_level, question_count, question_types],
1352
+ outputs=[quiz_progress_display, quiz_output],
1353
+ show_progress=True
1354
+ )
1355
+
1356
+ # Examples
1357
+ gr.Examples(
1358
+ examples=[
1359
+ ["Photosynthesis", "Science", "6-8", 5, ["Multiple Choice", "True/False"]],
1360
+ ["World War II", "History", "9-12", 8, ["Multiple Choice", "Short Answer"]],
1361
+ ["Basic Algebra", "Mathematics", "3-5", 4, ["Multiple Choice", "Fill in the Blank"]]
1362
+ ],
1363
+ inputs=[quiz_topic, quiz_subject, quiz_grade_level, question_count, question_types]
1364
+ )
1365
+
1366
+ with gr.TabItem("πŸ”§ Admin Dashboard", visible=False): # Hidden by default
1367
+ with gr.Row():
1368
+ with gr.Column():
1369
+ gr.Markdown("""
1370
+ ## πŸ”§ Admin Dashboard
1371
+
1372
+ **Access Level**: Administrator Only
1373
+ **Database**: SQLite (feedback.db)
1374
+ **Last Updated**: Real-time
1375
+ """)
1376
+
1377
+ refresh_btn = gr.Button("πŸ”„ Refresh Data", variant="secondary")
1378
+ view_feedback_btn = gr.Button("πŸ“Š View All Feedback", variant="primary")
1379
+
1380
+ with gr.Column():
1381
+ admin_output = gr.Markdown(label="Admin Data")
1382
+
1383
+ # Event handlers for admin
1384
+ def format_stats():
1385
+ stats = get_feedback_stats()
1386
+ result = f"""
1387
+ # πŸ“Š Feedback Statistics
1388
+
1389
+ **Total Feedback Entries:** {stats['total_feedback']}
1390
+ **Average Rating:** {stats['avg_rating']}/5 ⭐
1391
+ **Database Status:** βœ… Active
1392
+
1393
+ ## Recent Feedback (Last 5)
1394
+ """
1395
+ for entry in stats['recent_feedback']:
1396
+ timestamp, feedback_type, rating, comments, user_email = entry
1397
+ result += f"""
1398
+ ### Entry from {timestamp}
1399
+ - **Type:** {feedback_type}
1400
+ - **Rating:** {rating}/5 ⭐
1401
+ - **Comments:** {comments[:100]}{'...' if len(comments) > 100 else ''}
1402
+ - **Email:** {user_email if user_email else 'Not provided'}
1403
+ ---
1404
+ """
1405
+ return result
1406
+
1407
+ refresh_btn.click(
1408
+ fn=format_stats,
1409
+ outputs=admin_output
1410
+ )
1411
+
1412
+ view_feedback_btn.click(
1413
+ fn=view_feedback_admin,
1414
+ outputs=admin_output
1415
+ )
1416
+
1417
+ if __name__ == "__main__":
1418
+ demo.launch()