-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_mlx.py
More file actions
691 lines (580 loc) · 26.3 KB
/
app_mlx.py
File metadata and controls
691 lines (580 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
"""
Math Tutor Bot - MLX-Optimized Version for Apple Silicon
2-3x faster than PyTorch version!
MEMORY-OPTIMIZED: Reduced resource usage for stability
"""
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
from mlx_lm import load, generate
import mlx.core as mx
from kokoro import KPipeline
import soundfile as sf
from datetime import datetime
import os
import gc # Garbage collection for memory management
from werkzeug.utils import secure_filename
from emotion_analyzer import EmotionAnalyzer
from facial_emotion_analyzer import FacialEmotionAnalyzer
from rag_system import RAGSystem
from gemini_client import initialize_gemini
from diagram_generator import DiagramGenerator
from dotenv import load_dotenv
app = Flask(__name__)
CORS(app)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB max file size
app.config['UPLOAD_FOLDER'] = 'uploaded_docs'
# Load environment variables
load_dotenv()
def latex_to_speech(text):
"""
Convert LaTeX mathematical notation to spoken text for TTS
"""
import re
# Remove display math delimiters (both escaped and unescaped brackets)
text = re.sub(r'\\\[(.*?)\\\]', r'\1', text, flags=re.DOTALL) # \[ ... \]
text = re.sub(r'\[\s*([^\[\]]*(?:\\[a-zA-Z]+|=)[^\[\]]*)\s*\]', r'\1', text, flags=re.DOTALL) # [ ... ] with LaTeX
text = re.sub(r'\\\((.*?)\\\)', r'\1', text, flags=re.DOTALL) # \( ... \)
text = re.sub(r'\(\(\s*([^)]+?)\s*\)\)', r'\1', text) # (( ... ))
# Remove inline math delimiters $ ... $
text = re.sub(r'\$(.*?)\$', r'\1', text)
# Remove markdown formatting
text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text) # **bold**
text = re.sub(r'__([^_]+)__', r'\1', text) # __bold__
text = re.sub(r'\*([^*]+)\*', r'\1', text) # *italic*
text = re.sub(r'_([^_]+)_', r'\1', text) # _italic_
text = re.sub(r'~~([^~]+)~~', r'\1', text) # ~~strikethrough~~
text = re.sub(r'`([^`]+)`', r'\1', text) # `code`
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE) # # headers
# Convert common LaTeX commands to spoken form
replacements = {
# Fractions
r'\\frac\{([^}]+)\}\{([^}]+)\}': r'\1 divided by \2',
# Text commands
r'\\text\{([^}]+)\}': r'\1',
r'\\mathrm\{([^}]+)\}': r'\1',
r'\\mathbf\{([^}]+)\}': r'\1',
# Superscripts and subscripts
r'\^(\d+)': r' to the power of \1',
r'\^\{([^}]+)\}': r' to the power of \1',
r'_(\d+)': r' sub \1',
r'_\{([^}]+)\}': r' sub \1',
# Greek letters
r'\\alpha': 'alpha',
r'\\beta': 'beta',
r'\\gamma': 'gamma',
r'\\delta': 'delta',
r'\\epsilon': 'epsilon',
r'\\theta': 'theta',
r'\\lambda': 'lambda',
r'\\mu': 'mu',
r'\\pi': 'pi',
r'\\sigma': 'sigma',
r'\\tau': 'tau',
r'\\phi': 'phi',
r'\\omega': 'omega',
# Math symbols
r'\\sum': 'sum',
r'\\prod': 'product',
r'\\int': 'integral',
r'\\sqrt\{([^}]+)\}': r'square root of \1',
r'\\sqrt': 'square root',
# Operators
r'\\times': 'times',
r'\\cdot': 'times',
r'\\div': 'divided by',
r'\\pm': 'plus or minus',
r'\\leq': 'less than or equal to',
r'\\geq': 'greater than or equal to',
r'\\neq': 'not equal to',
r'\\approx': 'approximately equal to',
r'\\infty': 'infinity',
# Brackets and parentheses
r'\\left\(': '(',
r'\\right\)': ')',
r'\\left\[': '[',
r'\\right\]': ']',
r'\\left\\{': '{',
r'\\right\\}': '}',
r'\\{': '{',
r'\\}': '}',
# Remove remaining backslashes
r'\\': '',
}
# Apply all replacements
for pattern, replacement in replacements.items():
text = re.sub(pattern, replacement, text)
# Clean up extra spaces
text = re.sub(r'\s+', ' ', text).strip()
return text
# Global variables
model = None
tokenizer = None
tts = None
emotion_analyzer = None
facial_emotion_analyzer = None
rag_system = None
gemini_client = None
diagram_generator = None
conversation_history = []
emotion_history = [] # Track emotion over time
def load_model():
"""Load MLX-optimized model for Apple Silicon"""
global model, tokenizer, tts, emotion_analyzer, facial_emotion_analyzer, rag_system, gemini_client, diagram_generator
print("="*60)
print("Loading Gemini API + Phi-3 Mini (3.8B) + RAG + Image Generation")
print("="*60)
# Initialize Gemini API first
print("\nInitializing Gemini API (Google AI Studio)...")
gemini_client = initialize_gemini(os.getenv('GEMINI_API_KEY'))
if gemini_client.is_available():
print("✓ Gemini API ready! (Primary AI model)")
print("✓ Phi-3 Mini will serve as fallback\n")
else:
print("⚠ Gemini API not available - will use Phi-3 Mini only\n")
print("Optimized for Apple Silicon - 2-3x faster!")
print("Downloading Phi-3 Mini 4-bit quantized model (~2GB)...\n")
# Load Phi-3 Mini MLX model (optimized for Apple Silicon)
model, tokenizer = load("mlx-community/Phi-3-mini-4k-instruct-4bit")
print("✓ Phi-3 Mini loaded successfully!")
print(f"✓ Running on Apple Neural Engine\n")
print("Loading Kokoro TTS for voice generation...")
tts = KPipeline(lang_code='a')
print("✓ TTS loaded!\n")
print("Loading Emotion Analyzers for adaptive tutoring...")
emotion_analyzer = EmotionAnalyzer()
print("✓ Text Emotion Analyzer loaded!")
facial_emotion_analyzer = FacialEmotionAnalyzer()
print("✓ Facial Emotion Analyzer loaded!\n")
print("Initializing RAG System for document-based learning...")
rag_system = RAGSystem()
print("✓ RAG System ready!\n")
print("Initializing Local Diagram Generator for mathematical visualizations...")
diagram_generator = DiagramGenerator()
print("✓ Diagram Generator ready! (No API quota needed)\n")
@app.route('/')
def home():
"""Serve the main page"""
return render_template('index.html')
def get_dynamic_parameters(emotion, emotion_history):
"""
Get dynamic LLM parameters based on current emotion and history.
Returns:
dict: {
'max_tokens': int,
'temperature': float (not used in MLX but good for reference),
'response_style': str,
'additional_context': str
}
}
"""
# Check emotion trend
recent_emotions = emotion_history[-5:] if len(emotion_history) >= 5 else emotion_history
# Count consecutive frustrated/anxious states
negative_streak = 0
for e in reversed(recent_emotions):
if e in ['frustrated', 'anxious']:
negative_streak += 1
else:
break
# Base parameters by emotion (optimized for comprehensive responses)
params = {
'frustrated': {
'max_tokens': 2048, # Very high limit for complete detailed step-by-step explanations
'temperature': 0.2, # Very focused, step-by-step
'response_style': 'break down into very small, manageable steps with lots of encouragement',
'pacing': 'slow and steady'
},
'confused': {
'max_tokens': 2048, # Very high limit for multiple complete explanations and examples
'temperature': 0.3, # Deterministic and clear
'response_style': 'provide multiple explanations, use analogies and examples',
'pacing': 'thorough and methodical'
},
'anxious': {
'max_tokens': 1536, # High limit for reassuring complete responses
'temperature': 0.4, # Calm and reassuring
'response_style': 'be extra reassuring, celebrate progress, use simple language',
'pacing': 'gentle and supportive'
},
'confident': {
'max_tokens': 2048, # Very high limit for complete advanced concepts
'temperature': 0.6, # Allow some creativity
'response_style': 'be direct and challenging, introduce advanced concepts',
'pacing': 'brisk and engaging'
},
'neutral': {
'max_tokens': 2048, # Very high limit for complete comprehensive document explanations
'temperature': 0.5, # Balanced
'response_style': 'maintain standard tutoring approach',
'pacing': 'steady'
}
}
base_params = params.get(emotion, params['neutral'])
# Adjust for negative streaks
additional_context = ""
if negative_streak >= 3:
additional_context = "\n\nIMPORTANT: Student has been struggling for a while. Consider suggesting a break or switching to a simpler topic. Be extra encouraging."
base_params['max_tokens'] = min(base_params['max_tokens'], 300) # Keep it brief
elif negative_streak >= 5:
additional_context = "\n\nCRITICAL: Student is very frustrated. Strongly suggest taking a short break. Provide lots of positive reinforcement."
base_params['max_tokens'] = 200 # Very brief, supportive message
base_params['additional_context'] = additional_context
return base_params
@app.route('/api/detect_emotion', methods=['POST'])
def detect_emotion():
"""Real-time facial emotion detection endpoint"""
data = request.json
face_image = data.get('face_image', None)
if not face_image:
return jsonify({'emotion': 'neutral', 'confidence': 0.0})
try:
# Analyze facial emotion
facial_emotion_result = facial_emotion_analyzer.analyze_from_base64(face_image)
if facial_emotion_result['face_detected']:
return jsonify({
'emotion': facial_emotion_result['emotion'],
'confidence': facial_emotion_result['confidence']
})
else:
return jsonify({'emotion': 'neutral', 'confidence': 0.0})
except Exception as e:
print(f"Error in real-time emotion detection: {e}")
return jsonify({'emotion': 'neutral', 'confidence': 0.0})
@app.route('/api/upload_document', methods=['POST'])
def upload_document():
"""Upload and process a document for RAG"""
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
# Check file type
allowed_extensions = {'.pdf', '.txt'}
file_ext = os.path.splitext(file.filename)[1].lower()
if file_ext not in allowed_extensions:
return jsonify({'error': 'Only PDF and TXT files are supported'}), 400
try:
# Save file
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
file.save(filepath)
# Process with RAG system
success = rag_system.add_document(filepath, filename)
if success:
stats = rag_system.get_stats()
return jsonify({
'message': f'Document {filename} uploaded successfully!',
'stats': stats
})
else:
return jsonify({'error': 'Failed to process document'}), 500
except Exception as e:
print(f"Error uploading document: {e}")
import traceback
traceback.print_exc()
return jsonify({'error': str(e)}), 500
@app.route('/api/rag_stats', methods=['GET'])
def rag_stats():
"""Get RAG system statistics"""
stats = rag_system.get_stats()
return jsonify(stats)
@app.route('/api/clear_documents', methods=['POST'])
def clear_documents():
"""Clear all uploaded documents"""
try:
rag_system.clear_all()
return jsonify({'message': 'All documents cleared successfully'})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/chat', methods=['POST'])
def chat():
"""Handle chat requests with MLX + RAG - Always generates both text and voice"""
global conversation_history, emotion_history
data = request.json
user_message = data.get('message', '')
current_emotion = data.get('current_emotion', None)
if not user_message:
return jsonify({'error': 'No message provided'}), 400
# Add user message to history
conversation_history.append({
"role": "user",
"content": user_message
})
# Keep only last 6 messages (reduced from 10 for memory optimization)
if len(conversation_history) > 6:
conversation_history = conversation_history[-6:]
# Analyze text-based emotion
text_emotion_result = emotion_analyzer.analyze(user_message)
# Use real-time facial emotion if available
if current_emotion and current_emotion.get('confidence', 0) > 0:
# Use the real-time detected facial emotion
facial_emotion_data = {
'emotion': current_emotion['emotion'],
'confidence': current_emotion['confidence'],
'face_detected': True
}
print(f"\n[Real-time Facial Emotion] {facial_emotion_data['emotion'].upper()} "
f"(confidence: {facial_emotion_data['confidence']:.2f})")
# Combine facial and text emotions
combined_emotion = facial_emotion_analyzer.combine_with_text_emotion(
facial_emotion_data,
text_emotion_result
)
detected_emotion = combined_emotion['emotion']
emotion_confidence = combined_emotion['confidence']
emotion_source = combined_emotion['source']
print(f"[Text Emotion] {text_emotion_result['emotion'].upper()} "
f"(confidence: {text_emotion_result['confidence']:.2f})")
print(f"[Combined Emotion] {detected_emotion.upper()} "
f"(confidence: {emotion_confidence:.2f}, source: {emotion_source})")
else:
# Use only text emotion
detected_emotion = text_emotion_result['emotion']
emotion_confidence = text_emotion_result['confidence']
print(f"\n[Text Emotion] {detected_emotion.upper()} (confidence: {emotion_confidence:.2f})")
print(f"[Details] {text_emotion_result['details']}")
# Get dynamic parameters based on emotion and history
dynamic_params = get_dynamic_parameters(detected_emotion, emotion_history)
# Update emotion history
emotion_history.append(detected_emotion)
if len(emotion_history) > 20: # Keep last 20 emotions
emotion_history = emotion_history[-20:]
print(f"[Dynamic Params] max_tokens: {dynamic_params['max_tokens']}, "
f"style: {dynamic_params['response_style']}, pacing: {dynamic_params['pacing']}")
# Base system prompt
base_prompt = """You are a helpful, patient, and encouraging tutor. Your primary role is to help students learn and understand concepts.
**When answering questions:**
- If document context is provided below, use it as your PRIMARY source of information
- Explain concepts from the uploaded documents clearly and accurately
- For math questions, show step-by-step solutions and explain the 'why' behind each step
- Use simple language and encourage critical thinking
IMPORTANT: Use proper LaTeX formatting for all mathematical notation:
- Use \\( ... \\) for inline math (e.g., \\(x^2 + y^2\\))
- Use \\[ ... \\] for display math (e.g., \\[\\frac{a}{b}\\])
- Use \\begin{pmatrix} ... \\end{pmatrix} inside \\[ \\] for matrices
Example: A vector \\(\\mathbf{v}\\) can be written as \\[\\mathbf{v} = \\begin{pmatrix} v_1 \\\\ v_2 \\end{pmatrix}\\]"""
# Get adaptive system prompt based on emotion
adaptive_prompt = emotion_analyzer.get_adaptive_prompt(detected_emotion, base_prompt)
# Add dynamic context based on emotion history
adaptive_prompt += f"\n\nRESPONSE STYLE: {dynamic_params['response_style']} Use a {dynamic_params['pacing']} pace."
adaptive_prompt += dynamic_params['additional_context']
# **RAG: Retrieve relevant context from uploaded documents**
# Check if user is explicitly asking about the uploaded document
doc_keywords = ['document', 'paper', 'file', 'upload', 'pdf', 'txt']
asking_about_doc = any(keyword in user_message.lower() for keyword in doc_keywords)
if asking_about_doc:
# User explicitly mentioned the document - bypass relevance threshold
print(f"[RAG] User asking about uploaded document - bypassing relevance threshold")
rag_context = rag_system.get_context_for_query(user_message, top_k=3, relevance_threshold=999)
else:
# Regular query - use strict relevance threshold (1.5)
rag_context = rag_system.get_context_for_query(user_message, top_k=2, relevance_threshold=1.5)
if rag_context:
# Truncate RAG context to max 800 characters to prevent context overflow
if len(rag_context) > 800:
rag_context = rag_context[:800] + "\n[Context truncated for memory optimization]"
adaptive_prompt += f"\n\n{rag_context}"
print(f"[RAG] Retrieved context from documents (length: {len(rag_context)} chars)")
# DEBUG: Log the actual RAG context being added (both console and file)
debug_output = f"\n{'='*60}\n"
debug_output += f"[DEBUG] RAG CONTEXT BEING ADDED:\n"
debug_output += f"{'='*60}\n"
debug_output += rag_context + "\n"
debug_output += f"{'='*60}\n"
print(debug_output)
# Save to log file
os.makedirs('rag_logs', exist_ok=True)
log_filename = f"rag_logs/rag_debug_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
with open(log_filename, 'w', encoding='utf-8') as f:
f.write(f"RAG DEBUG LOG - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"User Message: {user_message}\n")
f.write(debug_output)
# Prepare conversation with adaptive system prompt
full_conversation = [
{"role": "system", "content": adaptive_prompt}
] + conversation_history
# DEBUG: Log the full system prompt
print(f"\n{'='*60}")
print(f"[DEBUG] FULL SYSTEM PROMPT (length: {len(adaptive_prompt)} chars):")
print(f"{'='*60}")
print(f"First 500 chars:\n{adaptive_prompt[:500]}")
print(f"\nLast 500 chars:\n{adaptive_prompt[-500:]}")
print(f"{'='*60}\n")
# Save full system prompt to log file (if RAG context exists)
if rag_context:
log_filename = f"rag_logs/rag_debug_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
with open(log_filename, 'a', encoding='utf-8') as f:
f.write(f"\n{'='*60}\n")
f.write(f"FULL SYSTEM PROMPT (length: {len(adaptive_prompt)} chars):\n")
f.write(f"{'='*60}\n")
f.write(adaptive_prompt)
f.write(f"\n{'='*60}\n")
try:
# Format prompt for MLX
prompt = tokenizer.apply_chat_template(
full_conversation,
tokenize=False,
add_generation_prompt=True
)
# DEBUG: Log the final formatted prompt
print(f"\n{'='*60}")
print(f"[DEBUG] FINAL FORMATTED PROMPT (length: {len(prompt)} chars):")
print(f"{'='*60}")
print(f"Last 800 chars (shows user message + context):\n{prompt[-800:]}")
print(f"{'='*60}\n")
# Save final formatted prompt to log file (if RAG context exists)
if rag_context:
with open(log_filename, 'a', encoding='utf-8') as f:
f.write(f"\nFINAL FORMATTED PROMPT (length: {len(prompt)} chars):\n")
f.write(f"{'='*60}\n")
f.write(prompt)
f.write(f"\n{'='*60}\n")
print(f"[LOG] Saved RAG debug info to: {log_filename}")
# Generate response: Try Gemini first, fallback to Phi-3 Mini
response_text = None
# Try Gemini API first
if gemini_client and gemini_client.is_available():
print("[Generation] Attempting Gemini API...", flush=True)
response_text = gemini_client.generate_response(
full_conversation,
max_tokens=dynamic_params['max_tokens'],
temperature=0.7
)
if response_text:
print("[Generation] ✓ Gemini API successful", flush=True)
else:
print("[Generation] ✗ Gemini API failed, falling back to Phi-3 Mini", flush=True)
# Fallback to Phi-3 Mini if Gemini failed or unavailable
if not response_text:
print("[Generation] Using Phi-3 Mini (MLX)...", flush=True)
response_text = generate(
model,
tokenizer,
prompt=prompt,
max_tokens=dynamic_params['max_tokens'],
verbose=False
)
# Clean up response (remove prompt echo if present)
if prompt in response_text:
response_text = response_text[len(prompt):].strip()
print("[Generation] ✓ Phi-3 Mini successful", flush=True)
conversation_history.append({
"role": "assistant",
"content": response_text
})
# Memory cleanup after generation
mx.metal.clear_cache() # Clear MLX memory cache
gc.collect() # Force garbage collection
print(f"[Memory] Cleaned up after generation")
# **VISUALIZATION: Automatically attempt to generate diagrams for mathematical concepts**
diagram_url = None
# Detect if the response contains mathematical concepts that could benefit from visualization
# We'll be proactive and try to visualize any mathematical function or concept mentioned
math_concepts = [
'function', 'equation', 'formula', 'curve', 'line', 'parabola', 'circle', 'triangle',
'sine', 'cosine', 'tangent', 'exponential', 'logarithm', 'sigmoid', 'softmax',
'relu', 'tanh', 'activation', 'derivative', 'integral', 'polynomial',
'vector', 'matrix', 'geometry', 'shape', 'angle', 'slope',
'distribution', 'probability', 'histogram', 'gaussian', 'normal',
'graph', 'plot', 'linear', 'quadratic', 'cubic'
]
# Check both user message and bot response for mathematical concepts
combined_text = (user_message + ' ' + response_text).lower()
has_math_concept = any(concept in combined_text for concept in math_concepts)
# Image generation enabled - generates visualizations for mathematical concepts
# Always try to generate visualization if mathematical concepts are present
if has_math_concept: # Enabled to provide visual learning aids
print(f"\n[Diagram Generator] Visualization requested - generating local diagram...")
# Use combined text to detect which mathematical concept to visualize
concept_to_visualize = combined_text
# Generate diagram using local matplotlib generator (no API calls!)
image_base64 = diagram_generator.generate_direct(concept_to_visualize)
if image_base64:
# Save the image to a file
diagram_filename = f"diagram_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
diagram_path = os.path.join('static', diagram_filename)
# Decode base64 and save as PNG
import base64
image_data = base64.b64decode(image_base64)
with open(diagram_path, 'wb') as f:
f.write(image_data)
diagram_url = f'/static/{diagram_filename}'
print(f"[Diagram Generator] ✓ Diagram saved to {diagram_path}")
else:
print(f"[Diagram Generator] ✗ Failed to generate diagram")
# Always generate voice output
try:
# Convert LaTeX to spoken text for TTS
speech_text = latex_to_speech(response_text)
print(f"[TTS] Converting LaTeX to speech: {speech_text[:100]}...", flush=True)
# Generate audio using Kokoro
audio_generator = tts(speech_text, voice="af_heart")
# Kokoro returns (gs, ps, audio) tuples - concatenate all chunks
audio_filename = f"response_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
audio_path = os.path.join('static', audio_filename)
# Collect all audio chunks
import numpy as np
audio_chunks = []
for gs, ps, audio in audio_generator:
audio_chunks.append(audio)
# Concatenate all chunks into complete audio
if audio_chunks:
complete_audio = np.concatenate(audio_chunks)
sf.write(audio_path, complete_audio, 24000)
return jsonify({
'response': response_text,
'audio_url': f'/static/{audio_filename}',
'diagram_url': diagram_url,
'emotion': detected_emotion,
'emotion_confidence': emotion_confidence
})
except Exception as e:
print(f"Error generating audio: {e}")
import traceback
traceback.print_exc()
# Return text response even if audio fails
return jsonify({
'response': response_text,
'diagram_url': diagram_url,
'emotion': detected_emotion,
'emotion_confidence': emotion_confidence
})
except Exception as e:
print(f"Error generating response: {e}")
import traceback
traceback.print_exc()
return jsonify({'error': str(e)}), 500
@app.route('/api/clear', methods=['POST'])
def clear_history():
"""Clear conversation history"""
global conversation_history
conversation_history = []
return jsonify({'status': 'success', 'message': 'Conversation history cleared'})
@app.route('/api/history', methods=['GET'])
def get_history():
"""Get conversation history"""
return jsonify({'history': conversation_history})
@app.route('/health', methods=['GET'])
def health():
"""Health check"""
return jsonify({
'status': 'healthy',
'model_loaded': model is not None,
'framework': 'MLX (Apple Silicon Optimized)',
'performance': '2-3x faster than PyTorch'
})
if __name__ == '__main__':
# Load model
load_model()
print("="*60)
print("Math Tutor Bot - MLX Edition")
print("="*60)
print("Server starting on http://localhost:5001")
print("Optimized for Apple Silicon - 2-3x faster!")
print("Expected response time: 0.5-1 second")
print("\nOpen http://localhost:5001 in your browser")
print("Press Ctrl+C to stop")
print("="*60 + "\n")
# Run server
app.run(host='0.0.0.0', port=5001, debug=False)