-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1534 lines (1292 loc) · 60.5 KB
/
server.py
File metadata and controls
1534 lines (1292 loc) · 60.5 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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""NeonAI: Flask server entrypoint (chat/voice/uploads)."""
from web import search_adapter, movie_adapter
from exam import indexer
from brain import waterfall, memory, confidence_gate
from voice.tts_engine import generate_tts
from voice.model_loader import load_models
from voice.reference_loader import set_reference
from voice.whisper_engine import transcribe
from voice.llm_command_executor import execute_smart_command
from brain.intent_score_router import route_intent_scored
from brain import router_state
from utils import auth_db, storage_paths
import os
import re
import secrets
import sys
import time
from dotenv import load_dotenv
load_dotenv()
from flask import Flask, request, jsonify, render_template, send_file, session, redirect, url_for, abort
from flask_cors import CORS
from pyngrok import ngrok
import logging
class No206Filter(logging.Filter):
def filter(self, record):
msg = record.getMessage()
if '" 206 -' in msg and '.mp4' in msg:
return False
return True
logging.getLogger("werkzeug").addFilter(No206Filter())
# SETUP
# -----------------------------
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, 'static')
LEGACY_WALLPAPER_DIR = storage_paths.legacy_wallpaper_dir()
sys.path.append(BASE_DIR)
app = Flask(__name__, template_folder='templates', static_folder='static')
# 1️⃣ Hardcoded Secret Key Protection
neon_secret = os.environ.get('NEON_SECRET', '').strip()
if not neon_secret:
# In production, we should raise RuntimeError. For local development, we warn.
print("⚠️ WARNING: NEON_SECRET not found in environment. Sessions will not be secure.")
# raise RuntimeError("Missing NEON_SECRET environment variable.")
# (Uncomment the raise line for strict production environments)
app.secret_key = secrets.token_hex(32)
else:
app.secret_key = neon_secret
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = 60 * 60 * 24 * 30 # 30 days
# 3️⃣ File Upload Size Limit
# Background videos can be large; allow up to 50MB overall.
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024
CORS(app, resources={r"/*": {"origins": ["http://localhost:5000", "http://127.0.0.1:5000"]}})
# 2️⃣ & 5️⃣ MEMORY ISOLATION with LRU Cache (Per User + Per Mode)
# Using OrderedDict to implement an LRU cache for history to prevent memory leaks.
from collections import OrderedDict
HISTORY = OrderedDict()
MAX_HISTORY = 10
MAX_HISTORY_USERS = 50 # Total user+mode combinations tracked
IMAGE_EXTS = ("png", "jpg", "jpeg", "webp", "gif")
VIDEO_EXTS = ("mp4", "webm", "mov", "mkv", "avi")
PROFILE_PIC_EXTS = ("png", "jpg", "jpeg", "webp", "gif")
def _get_history_key(mode):
"""Returns user-specific history key."""
user_id = session.get('user_id', 'anon')
return f"user_{user_id}_{mode}"
def _get_user_history(mode):
"""Returns conversation history for current user + mode with LRU eviction."""
key = _get_history_key(mode)
if key in HISTORY:
# Move to end (most recently used)
HISTORY.move_to_end(key)
else:
# Add new key
HISTORY[key] = []
# Evict oldest if we exceed limit
if len(HISTORY) > MAX_HISTORY_USERS:
HISTORY.popitem(last=False)
return HISTORY[key]
def get_current_user():
"""Returns current logged-in user dict or None."""
user_id = session.get('user_id')
if user_id:
return auth_db.get_user_by_id(user_id)
return None
def _current_user_id() -> str:
return storage_paths.sanitize_user_id(session.get('user_id', 'anon'))
def _user_media_url(filename: str) -> str:
return f"/user-media/{filename}"
def _user_media_file(prefix: str, extensions) -> str | None:
user_id = _current_user_id()
media_dir = storage_paths.user_media_dir(user_id)
prefix_tag = f"{prefix}_{user_id}."
for ext in extensions:
filename = storage_paths.user_media_filename(prefix, user_id, ext)
if os.path.exists(os.path.join(media_dir, filename)):
return filename
if any(name.startswith(prefix_tag) for name in os.listdir(media_dir)):
return None
for ext in extensions:
filename = storage_paths.user_media_filename(prefix, user_id, ext)
if os.path.exists(os.path.join(LEGACY_WALLPAPER_DIR, filename)):
return filename
return None
def _clear_user_media(prefix: str, extensions, user_id: str | None = None) -> None:
import uuid
safe_user_id = storage_paths.sanitize_user_id(user_id or _current_user_id())
media_dir = storage_paths.user_media_dir(safe_user_id)
for ext in extensions:
path = os.path.join(
media_dir,
storage_paths.user_media_filename(prefix, safe_user_id, ext)
)
if os.path.exists(path):
try:
os.remove(path)
except OSError as e:
print(f"[_clear_user_media] Locked file workaround triggered for {path}: {e}")
try:
os.rename(path, f"{path}.del.{uuid.uuid4().hex}")
except OSError:
pass
try:
if os.path.exists(media_dir):
for filename in os.listdir(media_dir):
if ".del." in filename:
del_path = os.path.join(media_dir, filename)
try:
os.remove(del_path)
except OSError:
pass
except OSError:
pass
ALLOWED_MODES = {"casual", "exam", "movie", "coding", "voice_assistant"}
# -----------------------------
# HELPERS
# -----------------------------
def sanitize_english(text: str) -> str:
"""
Cleans output while strictly preserving newlines and indentation.
"""
if not text:
return ""
# Remove Devanagari only
text = re.sub(r'[\u0900-\u097F]+', '', text)
# Remove Hindi fillers (line safe)
hindi_fillers = [
r"\bnamaste\b", r"\bhaan\b", r"\bnahi\b", r"\baccha\b"
]
for word in hindi_fillers:
text = re.sub(word, "", text, flags=re.IGNORECASE)
# 🔥 DO NOT collapse whitespace
lines = text.split("\n")
cleaned = [line.rstrip() for line in lines]
return "\n".join(cleaned).strip()
def sanitize_for_voice(text: str) -> str:
"""
Make responses sound natural in TTS:
- remove markdown/emojis/symbol clutter
- keep it short and assistant-like
"""
if not text:
return ""
# Remove markdown emphasis/code fences
text = re.sub(r"```[\s\S]*?```", "", text)
text = text.replace("**", "").replace("*", "")
# Remove common emoji ranges (best-effort)
text = re.sub(r"[\U0001F300-\U0001FAFF]", "", text)
text = re.sub(r"[\u2600-\u26FF\u2700-\u27BF]", "", text)
# Remove bullet/list formatting that sounds weird in TTS
text = re.sub(r"^\s*[\-\*\d]+\.\s+", "", text, flags=re.MULTILINE)
# Collapse excessive whitespace but preserve sentence breaks
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text).strip()
# A few "system-y" phrases -> natural voice
replacements = {
"Command not recognized.": "I couldn't do that command.",
"Command blocked.": "I can't do that.",
}
for k, v in replacements.items():
text = text.replace(k, v)
return text.strip()
def enforce_code_formatting(text: str, mode: str) -> str:
"""
Ensures coding mode responses are properly formatted.
"""
if mode != "coding":
return text
if "```" not in text:
text = f"```python\n{text}\n```"
return text
def _strip_system_commands(text: str) -> str:
"""
Remove any system_command JSON from LLM responses in chat mode.
Handles:
- Pure JSON: '{"type":"system_command",...}'
- Mixed: '{"type":"system_command",...}\nSome explanation text'
- Wrapped: '{"type":"assistant","response":"..."}'
"""
import json
if not text or not text.strip():
return text
stripped = text.strip()
# --- Case 1: Pure JSON response ---
if stripped.startswith("{") and stripped.endswith("}"):
try:
parsed = json.loads(stripped)
if isinstance(parsed, dict):
if parsed.get("type") == "system_command":
return ""
if "response" in parsed:
return parsed["response"]
if "content" in parsed:
return parsed["content"]
except (json.JSONDecodeError, ValueError):
pass
# --- Case 2: JSON embedded in text (JSON + trailing explanation) ---
json_pattern = r'\{[^{}]*"type"\s*:\s*"system_command"[^{}]*\}'
match = re.search(json_pattern, stripped)
if match:
remaining = stripped[:match.start()] + stripped[match.end():]
remaining = remaining.strip().strip("\n").strip()
return remaining if remaining else ""
# --- Case 3: JSON with "response"/"content" wrapper mixed in text ---
if "{" in stripped:
try:
start = stripped.index("{")
depth = 0
end = start
for i in range(start, len(stripped)):
if stripped[i] == "{":
depth += 1
elif stripped[i] == "}":
depth -= 1
if depth == 0:
end = i + 1
break
json_str = stripped[start:end]
parsed = json.loads(json_str)
if isinstance(parsed, dict):
if parsed.get("type") == "system_command":
remaining = stripped[:start] + stripped[end:]
return remaining.strip() if remaining.strip() else ""
if "response" in parsed and not parsed.get("type"):
return parsed["response"]
except (json.JSONDecodeError, ValueError, IndexError):
pass
return text
def detect_pure_math(text: str) -> bool:
"""
Detects simple mathematical expressions like 5 + 7.
"""
if not text:
return False
text = text.strip()
pattern = r"^\d+(\.\d+)?\s*[\+\-\*/]\s*\d+(\.\d+)?$"
return bool(re.fullmatch(pattern, text))
def detect_coding_intent(text: str) -> bool:
"""
Smart detection for coding-related queries.
"""
if not text:
return False
text_lower = text.lower()
languages = ["python", "java", "c++", "javascript", "html", "css", "sql", "c#", "go", "rust"]
if any(lang in text_lower for lang in languages):
return True
structure_patterns = [
r"\bdef\s+\w+\(", r"\bclass\s+\w+", r"\bfor\s+\w+\s+in\s+",
r"\bwhile\s+.*:", r"\bif\s+.*:", r"print\(", r"\w+\s*=\s*.+"
]
for pattern in structure_patterns:
if re.search(pattern, text):
return True
operator_pattern = r"\d+\s*[\+\-\*/]\s*\d+"
if re.search(operator_pattern, text):
return True
symbol_pattern = r"[{}();]"
if re.search(symbol_pattern, text):
return True
return False
def unwrap_response(raw) -> str:
"""
Safely extracts plain text from waterfall responses.
Handles:
- dict with "content" key → {"type": "text", "content": "Hello"}
- dict with "response" key → {"type": "assistant", "response": "Hello"}
- plain string → "Hello"
- anything else → str() fallback
"""
if isinstance(raw, dict):
# Prefer "content", fallback to "response", fallback to empty
return raw.get("content") or raw.get("response") or ""
if isinstance(raw, str):
return raw
return str(raw) if raw else ""
# -----------------------------
# ROUTES
# -----------------------------
@app.route('/login')
def login_page():
if session.get('user_id'):
return redirect(url_for('home'))
return render_template('login.html')
@app.route('/auth/signup', methods=['POST'])
def auth_signup():
try:
data = request.get_json(silent=True) or {}
name = data.get('name', '').strip()
email = data.get('email', '').strip()
password = data.get('password', '')
success, message, user_id = auth_db.create_user(email, password, name)
if success:
session.permanent = True
session['user_id'] = user_id
session['user_name'] = name
session['user_email'] = email
return jsonify({'success': True, 'message': message})
return jsonify({'success': False, 'message': message})
except Exception as e:
print(f'[AUTH ERROR] Signup: {e}')
return jsonify({'success': False, 'message': 'Signup failed.'}), 500
@app.route('/auth/login', methods=['POST'])
def auth_login():
try:
data = request.get_json(silent=True) or {}
email = data.get('email', '').strip()
password = data.get('password', '')
success, user = auth_db.verify_user(email, password)
if success and user:
# Regenerate session to prevent session fixation
session.clear()
session.permanent = True
session['user_id'] = user['id']
session['user_name'] = user['name']
session['user_email'] = user['email']
return jsonify({'success': True, 'message': f"Welcome back, {user['name']}!"})
return jsonify({'success': False, 'message': 'Invalid email or password.'})
except Exception as e:
print(f'[AUTH ERROR] Login: {e}')
return jsonify({'success': False, 'message': 'Login failed.'}), 500
@app.route('/auth/logout')
def auth_logout():
session.clear()
return redirect(url_for('login_page'))
@app.route('/auth/me')
def auth_me():
user = get_current_user()
if user:
result = {'logged_in': True, 'name': user['name'], 'email': user['email']}
pic_file = _user_media_file("profile_dp", PROFILE_PIC_EXTS)
if pic_file:
result['profile_pic'] = _user_media_url(pic_file)
voice_video_file = _user_media_file("voice_video", VIDEO_EXTS)
if voice_video_file:
result['voice_video'] = _user_media_url(voice_video_file)
bg_video_file = _user_media_file("current_bg", VIDEO_EXTS)
if bg_video_file:
result['bg_video'] = _user_media_url(bg_video_file)
bg_image_file = _user_media_file("current_bg", IMAGE_EXTS)
if bg_image_file:
result['bg_image'] = _user_media_url(bg_image_file)
return jsonify(result)
return jsonify({'logged_in': False})
@app.route('/favicon.ico')
def favicon():
return send_file(os.path.join(STATIC_DIR, 'favicon.png'), mimetype='image/png')
@app.route('/user-media/<path:filename>')
def user_media(filename):
safe_name = os.path.basename(filename)
if safe_name != filename:
abort(404)
user_id = _current_user_id()
stem, _ = os.path.splitext(safe_name)
if not stem.endswith(f"_{user_id}"):
abort(404)
media_path = os.path.join(storage_paths.user_media_dir(user_id), safe_name)
if os.path.exists(media_path):
return send_file(media_path)
legacy_path = os.path.join(LEGACY_WALLPAPER_DIR, safe_name)
if os.path.exists(legacy_path):
return send_file(legacy_path)
abort(404)
@app.route('/')
def home():
if not session.get('user_id'):
return redirect(url_for('login_page'))
# Pass user_name and user_email to the template
user_name = session.get('user_name', 'User')
user_email = session.get('user_email', '')
user_id = session.get('user_id', 'anon')
return render_template('index.html', user_name=user_name, user_email=user_email, user_id=user_id)
@app.route("/upload-bg", methods=["POST"])
def upload_bg():
if not session.get('user_id'):
return jsonify({"status": "error", "message": "Unauthorized"}), 401
# Enforce specific background limits (video up to 50MB, images smaller)
try:
content_len = request.content_length or 0
if content_len > 50 * 1024 * 1024:
return jsonify({"status": "error", "message": "Background upload too large (max 50MB)."}), 413
except Exception:
pass
if "file" not in request.files:
return jsonify({"status": "error", "message": "No file provided"}), 400
file = request.files["file"]
if not file.filename:
return jsonify({"status": "error", "message": "Empty filename"}), 400
try:
from werkzeug.utils import secure_filename
user_id = _current_user_id()
safe_filename = secure_filename(file.filename)
ext = safe_filename.rsplit('.', 1)[-1].lower() if '.' in safe_filename else ''
is_video = ext in VIDEO_EXTS
if is_video:
_clear_user_media("current_bg", IMAGE_EXTS + VIDEO_EXTS, user_id)
filepath = storage_paths.user_media_path("current_bg", user_id, ext)
file.save(filepath)
return jsonify({"status": "success", "type": "video", "url": _user_media_url(os.path.basename(filepath))})
if ext not in IMAGE_EXTS:
return jsonify({"status": "error", "message": "Unsupported background file type"}), 400
# Images: keep tighter to reduce slow loads (10MB)
try:
if (request.content_length or 0) > 10 * 1024 * 1024:
return jsonify({"status": "error", "message": "Image background too large (max 10MB)."}), 413
except Exception:
pass
_clear_user_media("current_bg", IMAGE_EXTS + VIDEO_EXTS, user_id)
filepath = storage_paths.user_media_path("current_bg", user_id, ext)
file.save(filepath)
return jsonify({"status": "success", "type": "image", "url": _user_media_url(os.path.basename(filepath))})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/clear-bg", methods=["POST"])
def clear_bg():
"""Remove custom background (image/video) for current user."""
if not session.get('user_id'):
return jsonify({"status": "error", "message": "Unauthorized"}), 401
try:
user_id = _current_user_id()
_clear_user_media("current_bg", IMAGE_EXTS + VIDEO_EXTS, user_id)
return jsonify({"status": "success"})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/upload-profile-pic", methods=["POST"])
def upload_profile_pic():
if not session.get('user_id'):
return jsonify({"status": "error", "message": "Unauthorized"}), 401
if "file" not in request.files:
return jsonify({"status": "error", "message": "No file provided"}), 400
file = request.files["file"]
if not file.filename:
return jsonify({"status": "error", "message": "Empty filename"}), 400
try:
from werkzeug.utils import secure_filename
user_id = _current_user_id()
safe_filename = secure_filename(file.filename)
ext = safe_filename.rsplit('.', 1)[-1].lower() if '.' in safe_filename else ''
if ext not in PROFILE_PIC_EXTS:
return jsonify({"status": "error", "message": "Unsupported profile image type"}), 400
_clear_user_media("profile_dp", PROFILE_PIC_EXTS, user_id)
filepath = storage_paths.user_media_path("profile_dp", user_id, ext)
file.save(filepath)
return jsonify({"status": "success", "url": _user_media_url(os.path.basename(filepath))})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/upload-voice-video", methods=["POST"])
def upload_voice_video():
if not session.get('user_id'):
return jsonify({"status": "error", "message": "Unauthorized"}), 401
if "file" not in request.files:
return jsonify({"status": "error", "message": "No file provided"}), 400
file = request.files["file"]
if not file.filename:
return jsonify({"status": "error", "message": "Empty filename"}), 400
try:
from werkzeug.utils import secure_filename
user_id = _current_user_id()
safe_filename = secure_filename(file.filename)
ext = safe_filename.rsplit('.', 1)[-1].lower() if '.' in safe_filename else ''
if ext not in VIDEO_EXTS:
return jsonify({"status": "error", "message": "Unsupported video file type"}), 400
_clear_user_media("voice_video", VIDEO_EXTS, user_id)
filepath = storage_paths.user_media_path("voice_video", user_id, ext)
file.save(filepath)
return jsonify({"status": "success", "url": _user_media_url(os.path.basename(filepath))})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/upload-pdf", methods=["POST"])
def upload_pdf():
if not session.get('user_id'):
return jsonify({"status": "error", "message": "Unauthorized"}), 401
if "file" not in request.files:
return jsonify({"status": "error", "message": "No file provided"}), 400
file = request.files["file"]
if not file.filename:
return jsonify({"status": "error", "message": "Empty filename"}), 400
try:
from werkzeug.utils import secure_filename
user_id = _current_user_id()
safe_filename = secure_filename(file.filename)
if not safe_filename.lower().endswith('.pdf'):
return jsonify({"status": "error", "message": "Only PDF files allowed."}), 400
upload_dir = storage_paths.exam_upload_dir()
filename = f"syllabus_{user_id}.pdf"
filepath = os.path.join(upload_dir, filename)
file.save(filepath)
collection_name = f"exam_{user_id}"
success, msg = indexer.process_pdf(filename, collection_name=collection_name)
return jsonify({"status": "success" if success else "error", "message": msg})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/reset-exam-db", methods=["POST"])
def reset_exam_db_endpoint():
if not session.get('user_id'):
return jsonify({"status": "error", "message": "Unauthorized"}), 401
try:
user_id = _current_user_id()
collection_name = f"exam_{user_id}"
filename = f"syllabus_{user_id}.pdf"
success, msg = indexer.clear_database(collection_name=collection_name, filename=filename)
return jsonify({"status": "success" if success else "error", "message": msg})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/set-api-key", methods=["POST"])
def set_api_key_endpoint():
try:
user_id = session.get('user_id')
if not user_id:
return jsonify({"status": "error", "message": "Please log in first."}), 401
data = request.get_json(silent=True) or {}
api_key = data.get("api_key", "").strip()
# Save to database
auth_db.update_api_keys(user_id, search_api_key=api_key)
message = "Search API key saved to your account." if api_key else "Personal search API key removed."
return jsonify({"status": "success", "message": message})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/set-tmdb-key", methods=["POST"])
def set_tmdb_key_endpoint():
try:
user_id = session.get('user_id')
if not user_id:
return jsonify({"status": "error", "message": "Please log in first."}), 401
data = request.get_json(silent=True) or {}
api_key = data.get("api_key", "").strip()
# Save to database
auth_db.update_api_keys(user_id, tmdb_key=api_key)
message = "Movie API key saved to your account." if api_key else "Personal Movie API key removed."
return jsonify({"status": "success", "message": message})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/set-llm-keys", methods=["POST"])
def set_llm_keys_endpoint():
"""Save or remove LLM provider API keys (OpenAI / Gemini / Claude)."""
try:
user_id = session.get('user_id')
if not user_id:
return jsonify({"status": "error", "message": "Please log in first."}), 401
data = request.get_json(silent=True) or {}
openai_key = data.get("openai_key")
gemini_key = data.get("gemini_key")
claude_key = data.get("claude_key")
provider = data.get("llm_provider")
auth_db.update_api_keys(
user_id,
openai_key=openai_key,
gemini_key=gemini_key,
claude_key=claude_key,
llm_provider=provider,
)
return jsonify({"status": "success", "message": "LLM settings updated."})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/api/analyze-image", methods=["POST"])
def analyze_image_endpoint():
"""Offline image/resume analysis via local Ollama vision model or PDF text extraction."""
if not session.get('user_id'):
return jsonify({"status": "error", "message": "Unauthorized"}), 401
try:
from tools.vision_offline import analyze_image, analyze_pdf_resume
data = request.get_json(silent=True) or {}
file_b64 = data.get("image", "")
query = data.get("query", "Analyze this resume and give ATS score")
file_type = data.get("file_type", "image") # "image" or "pdf"
if not file_b64:
return jsonify({"status": "error", "message": "No file provided."}), 400
# Detailed logging for image/PDF analysis requests
b64_size_kb = len(file_b64) * 3 / 4 / 1024
print(f"\n📷 [API] /api/analyze-image request received")
print(f" File type: {file_type} | Base64 size: ~{b64_size_kb:.1f}KB")
print(f" Query: {query[:100]}{'...' if len(query) > 100 else ''}")
if file_type == "pdf":
# PDF resume → text extraction + LLM ATS analysis
result = analyze_pdf_resume(pdf_base64=file_b64, query=query)
else:
# Image → vision model analysis
result = analyze_image(image_base64=file_b64, query=query)
print(f" Result: {'✅ success' if result['success'] else '❌ failed'} | Model: {result.get('model', 'N/A')}")
return jsonify({
"status": "success" if result["success"] else "error",
"response": result["response"],
"model": result.get("model"),
})
except Exception as e:
print(f"[Vision Error] ❌ {e}")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/chat", methods=["POST"])
def chat():
global HISTORY
start_time = time.time()
try:
data = request.get_json(silent=True) or {}
user_text = data.get("message", "").strip()
mode = data.get("mode", "casual").lower().strip()
if not user_text:
return jsonify({"error": "Empty message"}), 400
if mode not in ALLOWED_MODES:
return jsonify({"error": "Invalid mode"}), 400
clean_lower = user_text.lower()
# --- LEVEL 2 INTELLIGENCE ---
# 1. Pure Math (safe AST-based evaluation — no eval())
if mode == "casual" and detect_pure_math(user_text):
try:
from tools.calculator import safe_eval
result, _ = safe_eval(user_text)
if result is not None:
print(f"🧮 Pure Math: {user_text} = {result}")
response_time = round(time.time() - start_time, 3)
print(f"⚡ Route: math_direct | Time: {response_time}s")
return jsonify({
"response": str(result),
"mode_used": "math_direct",
"mode": mode,
"response_time": response_time
})
except Exception:
pass
voice_mode_decision = None
# 1.25 Cross-mode deterministic routing (fix "broken in other modes")
# In exam mode we stay strict (no tools/system).
# In casual mode this is handled below with clarification + tool_data.
if mode in {"coding", "movie", "voice_assistant"}:
try:
decision = route_intent_scored(
user_text,
mode=mode,
user_id=_current_user_id(),
allow_system=True,
allow_tools=True,
allow_web=True,
)
if mode == "voice_assistant":
voice_mode_decision = decision
# If clarification is needed, reuse the same 1/2 flow even outside casual.
pending = router_state.get_pending_clarification(_current_user_id())
if pending:
choice = (user_text or "").strip().lower()
picked = None
if choice in {"1", "one"}:
picked = pending.options[0]
elif choice in {"2", "two"} and len(pending.options) > 1:
picked = pending.options[1]
elif choice in {"cancel", "no", "nope", "nah"}:
router_state.clear_pending_clarification(_current_user_id())
response_time = round(time.time() - start_time, 3)
return jsonify({
"response": "Okay, cancelled.",
"mode_used": "clarification_cancel",
"mode": mode,
"response_time": response_time
})
if picked and picked.get("decision"):
router_state.clear_pending_clarification(_current_user_id())
decision = picked["decision"]
else:
response_time = round(time.time() - start_time, 3)
lines = ["Please choose:", "1) " + pending.options[0]["label"]]
if len(pending.options) > 1:
lines.append("2) " + pending.options[1]["label"])
return jsonify({
"response": "\n".join(lines),
"mode_used": "clarification_repeat",
"mode": mode,
"response_time": response_time
})
if getattr(decision, "needs_clarification", False) and decision.clarification_options:
router_state.set_pending_clarification(_current_user_id(), decision.clarification_options)
response_time = round(time.time() - start_time, 3)
opt1 = decision.clarification_options[0]["label"]
opt2 = decision.clarification_options[1]["label"] if len(decision.clarification_options) > 1 else ""
resp = "Do you want me to:\n1) " + opt1
if opt2:
resp += "\n2) " + opt2
return jsonify({
"response": resp,
"mode_used": "clarification_prompt",
"mode": mode,
"response_time": response_time
})
if decision.route == "system" and decision.action:
result = execute_smart_command(
decision.action,
decision.target,
authorized=True,
user_id=_current_user_id(),
)
response_time = round(time.time() - start_time, 3)
return jsonify({
"response": str(result),
"mode_used": f"system_command:{decision.action}",
"mode": mode,
"response_time": response_time
})
if decision.route == "tool" and decision.tool_payload:
response_time = round(time.time() - start_time, 3)
matched_tool = decision.tool_payload.get("tool", "unknown_tool")
return jsonify({
"response": decision.tool_payload.get("response", ""),
"tool_data": decision.tool_payload.get("data"),
"mode_used": matched_tool,
"mode": mode,
"response_time": response_time
})
except Exception as e:
print(f"[Chat Cross-Mode Router Error] {e}")
# 1.5 Intent Routing & Tool Routing
if mode == "casual":
# 1.6 Intent Score Router (system/tool/web/llm)
try:
pending = router_state.get_pending_clarification(_current_user_id())
if pending:
choice = (user_text or "").strip().lower()
picked = None
if choice in {"1", "one"}:
picked = pending.options[0]
elif choice in {"2", "two"} and len(pending.options) > 1:
picked = pending.options[1]
elif choice in {"cancel", "no", "nope", "nah"}:
router_state.clear_pending_clarification(_current_user_id())
response_time = round(time.time() - start_time, 3)
return jsonify({
"response": "Okay, cancelled.",
"mode_used": "clarification_cancel",
"mode": mode,
"response_time": response_time
})
if picked and picked.get("decision"):
router_state.clear_pending_clarification(_current_user_id())
decision = picked["decision"]
else:
# If user didn't pick clearly, ask again.
response_time = round(time.time() - start_time, 3)
lines = ["Please choose:", "1) " + pending.options[0]["label"]]
if len(pending.options) > 1:
lines.append("2) " + pending.options[1]["label"])
return jsonify({
"response": "\n".join(lines),
"mode_used": "clarification_repeat",
"mode": mode,
"response_time": response_time
})
else:
decision = route_intent_scored(
user_text,
mode=mode,
user_id=_current_user_id(),
allow_system=True,
allow_tools=True,
allow_web=True,
)
if getattr(decision, "needs_clarification", False) and decision.clarification_options:
router_state.set_pending_clarification(_current_user_id(), decision.clarification_options)
response_time = round(time.time() - start_time, 3)
opt1 = decision.clarification_options[0]["label"]
opt2 = decision.clarification_options[1]["label"] if len(decision.clarification_options) > 1 else ""
resp = "Do you want me to:\n1) " + opt1
if opt2:
resp += "\n2) " + opt2
return jsonify({
"response": resp,
"mode_used": "clarification_prompt",
"mode": mode,
"response_time": response_time
})
if decision.route == "system" and decision.action:
result = execute_smart_command(
decision.action,
decision.target,
authorized=True,
user_id=_current_user_id(),
)
# context memory for follow-ups like "pause"
if decision.action in {"play_youtube", "media_control", "stop_music"}:
router_state.set_last_context(_current_user_id(), "system_media", {"action": decision.action})
else:
router_state.set_last_context(_current_user_id(), "system", {"action": decision.action})
response_time = round(time.time() - start_time, 3)
print(f"⚡ Route: system_command({decision.action}) | Time: {response_time}s")
return jsonify({
"response": str(result),
"mode_used": f"system_command:{decision.action}",
"mode": mode,
"response_time": response_time
})
if decision.route == "tool" and decision.tool_payload:
response_time = round(time.time() - start_time, 3)
matched_tool = decision.tool_payload.get("tool", "unknown_tool")
# context memory: music tool implies media follow-ups
if matched_tool == "music":
router_state.set_last_context(_current_user_id(), "music", {"tool": matched_tool})
else:
router_state.set_last_context(_current_user_id(), "tool", {"tool": matched_tool})
print(f"⚡ Route: {matched_tool}_tool | Time: {response_time}s")
return jsonify({
"response": decision.tool_payload.get("response", ""),
"tool_data": decision.tool_payload.get("data"),
"mode_used": matched_tool,
"mode": mode,
"response_time": response_time
})
except Exception as e:
print(f"[Chat Router Error] {e}")
intent = waterfall._classify_intent(user_text, mode)
print(f"[Chat] Classified Intent: {intent}")
if intent == "tool":