Shirpi commited on
Commit
03027d7
·
verified ·
1 Parent(s): 5d97563

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -444
app.py CHANGED
@@ -9,16 +9,11 @@ from PIL import Image
9
  from flask import Flask, request, jsonify, render_template_string, Response
10
  import google.generativeai as genai
11
 
12
- # --- FIX: IGNORE DEPRECATION WARNINGS ---
13
  warnings.filterwarnings("ignore")
14
 
15
- # ==========================================
16
- # 👇 API KEYS SETUP 👇
17
- # ==========================================
18
  keys_string = os.environ.get("API_KEYS", "")
19
  API_KEYS = [k.strip() for k in keys_string.replace(',', ' ').replace('\n', ' ').split() if k.strip()]
20
 
21
- # --- 💾 DATABASE ---
22
  DB_FILE = "chat_db.json"
23
  def load_db():
24
  try:
@@ -35,7 +30,6 @@ user_db = load_db()
35
  current_key_index = 0
36
  app = Flask(__name__)
37
 
38
- # --- 🧠 SYSTEM INSTRUCTION ---
39
  SYSTEM_INSTRUCTION = """
40
  ROLE: You are "Student's AI", a professional academic tutor.
41
  RULES:
@@ -46,7 +40,6 @@ RULES:
46
  5. **CODE:** Use Python/Java/C++ blocks. Explain logic briefly.
47
  """
48
 
49
- # --- 🧬 MODEL & FILE HANDLING ---
50
  def get_working_model(key):
51
  try:
52
  genai.configure(api_key=key)
@@ -70,7 +63,7 @@ def process_image(image_data):
70
 
71
  def generate_with_retry(prompt, image_data=None, file_text=None, history_messages=[]):
72
  global current_key_index
73
- if not API_KEYS: return "🚨 API Keys Missing."
74
 
75
  formatted_history = []
76
  for m in history_messages[-6:]:
@@ -87,15 +80,12 @@ def generate_with_retry(prompt, image_data=None, file_text=None, history_message
87
  for i in range(len(API_KEYS)):
88
  key = API_KEYS[current_key_index]
89
  model_name = get_working_model(key)
90
-
91
  if not model_name:
92
  current_key_index = (current_key_index + 1) % len(API_KEYS)
93
  continue
94
-
95
  try:
96
  genai.configure(api_key=key)
97
  model = genai.GenerativeModel(model_name=model_name, system_instruction=SYSTEM_INSTRUCTION)
98
-
99
  if image_data or file_text:
100
  response = model.generate_content(current_parts)
101
  else:
@@ -105,25 +95,21 @@ def generate_with_retry(prompt, image_data=None, file_text=None, history_message
105
  except Exception as e:
106
  current_key_index = (current_key_index + 1) % len(API_KEYS)
107
  time.sleep(1)
 
108
 
109
- return "⚠️ System Busy. Please try again."
110
-
111
- # --- UI TEMPLATE START ---
112
  HTML_TEMPLATE = """
113
  <!DOCTYPE html>
114
  <html lang="en">
115
  <head>
116
  <meta charset="UTF-8">
117
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, interactive-widget=resizes-content">
118
  <meta name="mobile-web-app-capable" content="yes">
119
  <meta name="apple-mobile-web-app-capable" content="yes">
120
  <meta name="theme-color" content="#09090b">
121
  <link rel="manifest" href="/manifest.json">
122
  <title>Student's AI</title>
123
-
124
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
125
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
126
-
127
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
128
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
129
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
@@ -134,153 +120,67 @@ HTML_TEMPLATE = """
134
  mermaid.initialize({ startOnLoad: false, theme: 'dark', securityLevel: 'loose' });
135
  window.mermaid = mermaid;
136
  </script>
137
-
138
  <style>
139
- :root {
140
- --bg: #09090b; --card: #18181b; --user-msg: #27272a; --text: #e4e4e7;
141
- --accent: #fff; --border: #27272a; --dim: #71717a;
142
- }
143
  * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
144
-
145
- body, html {
146
- margin: 0; padding: 0; height: 100dvh; width: 100%; max-width: 100%;
147
- background: var(--bg); color: var(--text); font-family: 'Outfit', sans-serif;
148
- overflow: hidden; font-size: 17px;
149
- -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;
150
- }
151
-
152
- textarea, input { -webkit-user-select: text !important; user-select: text !important; }
153
- .user-content, .ai-content, code, pre { -webkit-user-select: none !important; user-select: none !important; }
154
-
155
  #app-container { display: flex; flex-direction: column; height: 100dvh; width: 100%; position: relative; overflow-x: hidden; }
156
-
157
- header {
158
- height: 70px; padding: 0 20px; background: rgba(9,9,11, 0.98);
159
- border-bottom: 1px solid var(--border-color);
160
- display: flex; align-items: center; justify-content: space-between; flex-shrink: 0; z-index: 50;
161
- padding-top: env(safe-area-inset-top);
162
- }
163
- .menu-btn {
164
- width: 40px; height: 40px; border-radius: 50%; border: 1px solid #333;
165
- display: flex; align-items: center; justify-content: center; cursor: pointer;
166
- transition: 0.2s; color: #fff;
167
- }
168
- .menu-btn:active { transform: scale(0.95); background: #222; }
169
- .app-title { font-size: 24px; font-weight: 800; letter-spacing: -0.5px; color: #fff; }
170
-
171
- /* --- UNIFIED SIDEBAR (Always Top-to-Bottom) --- */
172
- #sidebar {
173
- position: fixed; top: 0; left: 0; width: 100%; height: 100%;
174
- background: var(--bg); z-index: 100;
175
- display: flex; flex-direction: column; padding: 25px;
176
- padding-top: calc(70px + env(safe-area-inset-top));
177
- transform: translateY(-100%);
178
- transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1);
179
- overflow-y: auto;
180
- }
181
  #sidebar.open { transform: translateY(0); }
 
182
 
183
- @media (min-width: 768px) {
184
- #sidebar { width: 350px; border-right: 1px solid var(--border); }
185
- .input-container { max-width: 800px; }
186
- #chat-box { padding: 20px 15%; }
187
- }
188
-
189
  .user-info { margin-bottom: 30px; font-size: 20px; font-weight: 700; color: #fff; display: flex; align-items: center; gap: 15px; flex-shrink: 0; }
190
- .new-chat-btn {
191
- width: 100%; padding: 15px; background: #fff; color: #000; border: none;
192
- border-radius: 12px; font-weight: 700; font-size: 16px; cursor: pointer; margin-bottom: 25px; flex-shrink: 0;
193
- }
194
-
195
- .history-label { color: var(--dim); font-size: 13px; font-weight: 600; margin-bottom: 10px; letter-spacing: 1px; text-transform: uppercase; flex-shrink: 0; }
196
  #history-list { flex: 1; overflow-y: auto; padding: 10px 0; min-height: 100px; }
197
-
198
- .history-item {
199
- display: flex; justify-content: space-between; align-items: center;
200
- padding: 15px; margin-bottom: 12px; background: var(--card); border: 1px solid var(--border); border-radius: 12px;
201
- cursor: pointer; color: #a1a1aa; font-size: 15px; transition: 0.2s;
202
- }
203
- .history-item:active { background: #222; color: #fff; border-color: #444; }
204
  .h-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; flex: 1; margin-right: 10px; }
205
  .h-actions { display: none; gap: 15px; }
206
  .history-item.active-mode .h-actions { display: flex; }
207
- .h-icon { font-size: 16px; color: #fff; padding: 5px; }
208
-
209
- .rename-input {
210
- background: transparent; border: none; border-bottom: 1px solid #fff;
211
- color: #fff; font-family: 'Outfit', sans-serif; font-size: 15px;
212
- width: 100%; outline: none; padding: 0;
213
- }
214
-
215
  .brand-section { text-align: center; margin-top: 20px; padding-bottom: env(safe-area-inset-bottom); flex-shrink: 0; }
216
- .brand-name { font-family: 'Outfit', sans-serif; font-weight: 600; font-size: 12px; color: var(--dim); letter-spacing: 2px; margin-bottom: 10px; opacity: 0.6; }
217
  .logout-btn { color: #ef4444; cursor: pointer; font-size: 15px; font-weight: 600; padding: 10px; }
218
 
219
- #chat-box {
220
- flex: 1; overflow-y: auto; padding: 20px 5%; padding-bottom: 80px;
221
- display: flex; flex-direction: column; gap: 25px;
222
- -webkit-overflow-scrolling: touch; overscroll-behavior-y: contain; min-height: 0;
223
- }
224
-
225
  .msg { width: 100%; line-height: 1.7; font-size: 17px; opacity: 0; animation: fadeInstant 0.3s forwards; display: flex; flex-direction: column; }
226
  @keyframes fadeInstant { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
227
-
228
  .user-msg { align-items: flex-end; }
229
  .user-content { display: inline-block; width: fit-content; max-width: 85%; background: var(--user-msg); padding: 10px 16px; border-radius: 18px 18px 4px 18px; text-align: left; color: #fff; word-wrap: break-word; }
230
-
231
  .ai-msg { align-items: flex-start; }
232
  .ai-content { width: 100%; color: #d4d4d8; word-wrap: break-word; }
233
- .ai-content strong { color: #fff; font-weight: 700; }
234
- .ai-content h1, .ai-content h2 { margin-top: 20px; color: #fff; font-weight: 700; }
235
- .ai-content img, .user-content img { cursor: pointer; transition: 0.2s; }
236
- .ai-content img:active, .user-content img:active { transform: scale(0.98); }
237
-
238
- pre { background: #1e1e1e !important; border-radius: 12px; padding: 15px; overflow-x: auto; margin: 15px 0; border: 1px solid #333; max-width: 100%; }
239
- code { font-family: 'JetBrains Mono', monospace; font-size: 14px; }
240
- .mjx-chtml { background: #18181b; padding: 10px; border-radius: 8px; border: 1px solid #333; overflow-x: auto; margin: 10px 0; text-align: center; max-width: 100%; }
241
- .mermaid { background: #111; padding: 15px; border-radius: 10px; text-align: center; margin: 15px 0; overflow-x: auto; }
242
-
243
- .msg-actions { margin-top: 10px; opacity: 0; transition: opacity 0.2s; display: flex; gap: 20px; align-items: center; }
244
- .user-msg .msg-actions { justify-content: flex-end; }
245
  .msg:hover .msg-actions { opacity: 1; }
246
- .action-icon { cursor: pointer; color: var(--dim); font-size: 18px; transition: 0.2s; }
247
- .action-icon:hover { color: #fff; transform: scale(1.1); }
248
 
249
  .input-wrapper { background: var(--bg); padding: 15px; border-top: 1px solid var(--border); flex-shrink: 0; z-index: 60; padding-bottom: max(15px, env(safe-area-inset-bottom)); }
250
  .input-container { max-width: 900px; margin: 0 auto; background: var(--card); border: 1px solid var(--border); border-radius: 24px; padding: 8px 12px; display: flex; align-items: flex-end; gap: 12px; }
251
  textarea { flex: 1; background: transparent; border: none; color: #fff; font-size: 17px; max-height: 120px; padding: 10px 5px; resize: none; outline: none; font-family: 'Outfit', sans-serif; }
252
- .icon-btn { width: 38px; height: 38px; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: none; background: transparent; color: #a1a1aa; cursor: pointer; font-size: 18px; }
253
- .send-btn { background: #fff; color: #000; width: 38px; height: 38px; border-radius: 50%; border: none; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 18px; }
254
-
255
  #preview-area { position: absolute; bottom: 85px; left: 20px; display: none; z-index: 70; }
256
- .preview-box { width: 60px; height: 60px; border-radius: 12px; border: 2px solid #fff; background: #222; overflow: hidden; position: relative; box-shadow: 0 4px 12px rgba(0,0,0,0.5); }
257
  .preview-img { width: 100%; height: 100%; object-fit: cover; }
258
- .remove-preview { position: absolute; top: -8px; right: -8px; background: red; color: white; border-radius: 50%; width: 20px; height: 20px; font-size: 12px; cursor: pointer; border: none; display: flex; align-items: center; justify-content: center; }
259
 
260
- /* --- LOGIN PAGE STABILITY (FIXED) --- */
261
- #login-overlay {
262
- position: fixed; inset: 0; background: #000; z-index: 2000;
263
- display: flex;
264
- /* Push Box Up so Keyboard doesn't cover/jump */
265
- align-items: flex-start; justify-content: center;
266
- padding-top: 25vh;
267
- transition: opacity 0.8s ease; opacity: 1; pointer-events: auto;
268
- }
269
  #login-overlay.hidden { opacity: 0; pointer-events: none; }
270
-
271
- .login-box {
272
- width: 90%; max-width: 350px; text-align: center;
273
- padding: 40px; border: 1px solid var(--border); border-radius: 20px; background: #0a0a0a;
274
- /* No margins that auto-adjust */
275
- }
276
-
277
  #image-modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 3000; display: none; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s; }
278
- #image-modal img { max-width: 95%; max-height: 90%; border-radius: 8px; box-shadow: 0 0 20px rgba(0,0,0,0.8); }
279
  #image-modal.active { opacity: 1; }
280
  </style>
281
  </head>
282
  <body>
283
-
284
  <div id="login-overlay">
285
  <div class="login-box">
286
  <h1 class="app-title" style="margin-bottom:10px;">Student's AI</h1>
@@ -288,11 +188,7 @@ HTML_TEMPLATE = """
288
  <button onclick="handleLogin()" style="width:100%; padding:15px; border-radius:12px; border:none; background:#fff; font-weight:800; cursor:pointer; font-size: 16px;">Start Learning</button>
289
  </div>
290
  </div>
291
-
292
- <div id="image-modal" onclick="closeImagePreview()">
293
- <img id="modal-img" src="" alt="Preview">
294
- </div>
295
-
296
  <div id="sidebar">
297
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-shrink:0;">
298
  <div class="user-info"><span id="display-name">User</span></div>
@@ -306,332 +202,62 @@ HTML_TEMPLATE = """
306
  <div class="logout-btn" onclick="handleLogout()">Log Out</div>
307
  </div>
308
  </div>
309
-
310
  <div id="app-container">
311
  <header>
312
  <div class="menu-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
313
  <span class="app-title">Student's AI</span>
314
  <div style="width:40px;"></div>
315
  </header>
316
-
317
  <div id="chat-box"></div>
318
-
319
  <div class="input-wrapper">
320
  <div id="preview-area">
321
  <div class="preview-box"><div id="preview-visual"></div></div>
322
- <button class="remove-preview" onclick="clearAttachment()">×</button>
323
  </div>
324
-
325
  <div class="input-container">
326
  <button class="icon-btn" onclick="document.getElementById('file-input').click()"><i class="fas fa-paperclip"></i></button>
327
  <input type="file" id="file-input" accept="image/*,.txt,.py,.js,.html,.css,.md,.csv,.json" hidden onchange="handleFileSelect(this)">
328
-
329
  <button class="icon-btn" onclick="document.getElementById('camera-input').click()"><i class="fas fa-camera"></i></button>
330
  <input type="file" id="camera-input" accept="image/*" capture="environment" hidden onchange="handleFileSelect(this)">
331
-
332
  <textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
333
-
334
  <button class="send-btn" onclick="send()"><i class="fas fa-arrow-up"></i></button>
335
  </div>
336
  </div>
337
  </div>
338
-
339
  <script>
340
- let currentUser = null;
341
- let currentChatId = null;
342
- let currentAttachment = { type: null, data: null, name: null };
343
- let longPressTimer;
344
-
345
- function getIntroHtml(name) {
346
- return `<div class="msg ai-msg"><div class="ai-content"><h1>Hi ${name},</h1><p>Ready to master your studies today?</p></div></div>`;
347
- }
348
-
349
- // --- AUTH LOGIC (SMOOTH TRANSITION) ---
350
- function checkLogin() {
351
- try {
352
- const stored = localStorage.getItem("student_ai_user");
353
- if (stored) {
354
- currentUser = stored;
355
- document.getElementById("login-overlay").classList.add('hidden');
356
- showApp();
357
- }
358
- } catch(e) { console.log("Storage access denied"); }
359
- }
360
-
361
- function handleLogin() {
362
- const input = document.getElementById("username-input");
363
- const name = input.value.trim();
364
- if(name) {
365
- try { localStorage.setItem("student_ai_user", name); } catch(e){}
366
- currentUser = name;
367
- document.getElementById("login-overlay").classList.add('hidden');
368
- showApp();
369
- } else {
370
- input.style.border = "1px solid red";
371
- setTimeout(() => input.style.border = "1px solid #333", 2000);
372
- }
373
- }
374
-
375
- function handleLogout() {
376
- try { localStorage.removeItem("student_ai_user"); } catch(e){}
377
- const overlay = document.getElementById("login-overlay");
378
- overlay.classList.remove('hidden'); // FADE IN LOGIN SCREEN
379
- document.getElementById('sidebar').classList.remove('open');
380
- setTimeout(() => {
381
- document.getElementById('chat-box').innerHTML = "";
382
- currentChatId = null;
383
- document.getElementById("username-input").value = "";
384
- }, 500);
385
- }
386
-
387
- function showApp() {
388
- document.getElementById("display-name").innerText = "Hi " + currentUser;
389
- loadHistory();
390
- if(!currentChatId) {
391
- const box = document.getElementById("chat-box");
392
- if(box.innerHTML === "") {
393
- box.innerHTML = getIntroHtml(currentUser);
394
- }
395
- }
396
- }
397
-
398
- function resizeInput(el) {
399
- el.style.height = 'auto';
400
- el.style.height = Math.min(el.scrollHeight, 150) + 'px';
401
- }
402
-
403
- function handleFileSelect(input) {
404
- if (input.files && input.files[0]) {
405
- const file = input.files[0];
406
- const reader = new FileReader();
407
- reader.onload = function(e) {
408
- const result = e.target.result;
409
- const isImage = file.type.startsWith('image/');
410
- currentAttachment = { type: isImage ? 'image' : 'file', data: isImage ? result : atob(result.split(',')[1]), name: file.name };
411
- const previewArea = document.getElementById('preview-area');
412
- const visual = document.getElementById('preview-visual');
413
- previewArea.style.display = 'block';
414
- visual.innerHTML = isImage ? `<img src="${result}" class="preview-img">` : `<div class="preview-file-icon"><i class="fas fa-file-alt"></i></div>`;
415
- }
416
- reader.readAsDataURL(file);
417
- }
418
- input.value = "";
419
- }
420
-
421
- function clearAttachment() {
422
- currentAttachment = { type: null, data: null, name: null };
423
- document.getElementById('preview-area').style.display = 'none';
424
- }
425
-
426
- function scrollToBottom() {
427
- const box = document.getElementById('chat-box');
428
- setTimeout(() => {
429
- box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });
430
- }, 100);
431
- }
432
-
433
- async function send() {
434
- const input = document.getElementById('input');
435
- const text = input.value.trim();
436
- if (!text && !currentAttachment.data) return;
437
-
438
- const chatBox = document.getElementById('chat-box');
439
- let attachHtml = '';
440
- if (currentAttachment.type === 'image') attachHtml = `<br><img src="${currentAttachment.data}" style="max-height:100px; margin-top:10px; border-radius:8px;">`;
441
- if (currentAttachment.type === 'file') attachHtml = `<br><small>📄 ${currentAttachment.name}</small>`;
442
-
443
- const userHtml = `
444
- <div class="msg user-msg">
445
- <div class="user-content">${text.replace(/</g, "&lt;")}${attachHtml}</div>
446
- <div class="msg-actions">
447
- <i class="fas fa-copy action-icon" onclick="copyText('${text}')"></i>
448
- <i class="fas fa-pen action-icon" onclick="editMessage('${text}')"></i>
449
- </div>
450
- </div>`;
451
- chatBox.insertAdjacentHTML('beforeend', userHtml);
452
-
453
- const promptText = text;
454
- const imgData = currentAttachment.type === 'image' ? currentAttachment.data : null;
455
- const fileText = currentAttachment.type === 'file' ? currentAttachment.data : null;
456
-
457
- input.value = ''; input.style.height = 'auto';
458
- clearAttachment();
459
- scrollToBottom();
460
-
461
- const msgId = "ai-" + Date.now();
462
- chatBox.insertAdjacentHTML('beforeend', `<div id="${msgId}" class="msg ai-msg"><i class="fas fa-circle-notch fa-spin"></i></div>`);
463
- scrollToBottom();
464
-
465
- try {
466
- if (!currentChatId) {
467
- const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
468
- const d = await r.json(); currentChatId = d.chat_id;
469
- loadHistory();
470
- }
471
- const res = await fetch('/chat', {
472
- method: 'POST', headers: {'Content-Type': 'application/json'},
473
- body: JSON.stringify({ message: promptText, image: imgData, file_text: fileText, username: currentUser, chat_id: currentChatId })
474
- });
475
- const data = await res.json();
476
-
477
- const aiDiv = document.getElementById(msgId);
478
- aiDiv.innerHTML = "";
479
- const contentDiv = document.createElement('div');
480
- contentDiv.className = 'ai-content';
481
- aiDiv.appendChild(contentDiv);
482
-
483
- await typeWriter(contentDiv, data.response);
484
-
485
- aiDiv.insertAdjacentHTML('beforeend', `
486
- <div class="msg-actions">
487
- <i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i>
488
- <i class="fas fa-share-alt action-icon" onclick="shareResponse(this)"></i>
489
- <i class="fas fa-redo action-icon" onclick="regenerate('${promptText}')"></i>
490
- </div>`);
491
-
492
- scrollToBottom();
493
- if(data.new_title) loadHistory();
494
- } catch (e) { document.getElementById(msgId).innerHTML = "⚠️ Error: " + e.message; }
495
- }
496
-
497
  function copyText(text) { navigator.clipboard.writeText(text); }
498
- function copyAiResponse(btn) {
499
- const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
500
- navigator.clipboard.writeText(text);
501
- }
502
- function shareResponse(btn) {
503
- const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
504
- if (navigator.share) navigator.share({ title: 'Student AI', text: text });
505
- else navigator.clipboard.writeText(text);
506
- }
507
  function editMessage(oldText) { document.getElementById('input').value = oldText; document.getElementById('input').focus(); }
508
  function regenerate(text) { document.getElementById('input').value = text; send(); }
509
-
510
- document.getElementById('chat-box').addEventListener('click', function(e) {
511
- if(e.target.tagName === 'IMG') {
512
- const modal = document.getElementById('image-modal');
513
- const modalImg = document.getElementById('modal-img');
514
- modalImg.src = e.target.src;
515
- modal.style.display = 'flex';
516
- setTimeout(() => modal.classList.add('active'), 10);
517
- }
518
- });
519
- function closeImagePreview() {
520
- const modal = document.getElementById('image-modal');
521
- modal.classList.remove('active');
522
- setTimeout(() => modal.style.display = 'none', 300);
523
- }
524
-
525
- function handleHistoryTouchStart(e, cid) {
526
- longPressTimer = setTimeout(() => {
527
- e.target.closest('.history-item').classList.add('active-mode');
528
- }, 600);
529
- }
530
  function handleHistoryTouchEnd(e) { clearTimeout(longPressTimer); }
531
-
532
- function startRename(cid) {
533
- const item = document.getElementById('chat-' + cid);
534
- const titleSpan = item.querySelector('.h-title');
535
- const currentTitle = titleSpan.innerText;
536
- const input = document.createElement('input');
537
- input.type = 'text'; input.value = currentTitle; input.className = 'rename-input';
538
-
539
- async function save() {
540
- const newTitle = input.value.trim();
541
- if(newTitle && newTitle !== currentTitle) {
542
- await fetch('/rename_chat', {
543
- method:'POST', headers:{'Content-Type':'application/json'},
544
- body:JSON.stringify({username:currentUser, chat_id:cid, title:newTitle})
545
- });
546
- loadHistory();
547
- } else { loadHistory(); }
548
- }
549
- input.addEventListener('blur', save);
550
- input.addEventListener('keydown', (e) => { if(e.key === 'Enter') { input.blur(); } });
551
- titleSpan.replaceWith(input); input.focus();
552
- }
553
-
554
- async function deleteChat(cid) {
555
- const el = document.getElementById('chat-' + cid);
556
- if(el) el.remove();
557
- await fetch('/delete_chat', {
558
- method:'POST', headers:{'Content-Type':'application/json'},
559
- body:JSON.stringify({username:currentUser, chat_id:cid})
560
- });
561
- if(currentChatId === cid) newChat();
562
- loadHistory();
563
- }
564
-
565
- async function loadHistory() {
566
- try {
567
- const res = await fetch('/get_history', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
568
- const data = await res.json();
569
- const list = document.getElementById('history-list'); list.innerHTML = "";
570
- if (data.chats) {
571
- Object.keys(data.chats).reverse().forEach(cid => {
572
- const title = data.chats[cid].title || "New Chat";
573
- list.innerHTML += `
574
- <div class="history-item" id="chat-${cid}" onclick="loadChat('${cid}')" oncontextmenu="return false;"
575
- ontouchstart="handleHistoryTouchStart(event, '${cid}')" ontouchend="handleHistoryTouchEnd(event)">
576
- <span class="h-title">${title}</span>
577
- <div class="h-actions">
578
- <i class="fas fa-pen h-icon" onclick="event.stopPropagation(); startRename('${cid}')"></i>
579
- <i class="fas fa-trash h-icon" onclick="event.stopPropagation(); deleteChat('${cid}')"></i>
580
- </div>
581
- </div>`;
582
- });
583
- }
584
- } catch(e) {}
585
- }
586
-
587
- async function typeWriter(element, markdownText) {
588
- element.innerHTML = marked.parse(markdownText);
589
- hljs.highlightAll();
590
- if (window.MathJax) await MathJax.typesetPromise([element]);
591
- if (window.mermaid) {
592
- const m = element.querySelectorAll('code.language-mermaid');
593
- m.forEach(c => { const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d); });
594
- window.mermaid.init(undefined, element.querySelectorAll('.mermaid'));
595
- }
596
- element.style.opacity = 0; element.style.transition = 'opacity 0.4s';
597
- setTimeout(() => { element.style.opacity = 1; scrollToBottom(); }, 50);
598
- }
599
-
600
  function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }
601
- async function newChat() {
602
- currentChatId = null;
603
- document.getElementById('chat-box').innerHTML = getIntroHtml(currentUser);
604
- const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
605
- const d = await r.json(); currentChatId = d.chat_id; loadHistory();
606
- document.getElementById('sidebar').classList.remove('open');
607
- }
608
- async function loadChat(cid) {
609
- currentChatId = cid; const res = await fetch('/get_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid})});
610
- const data = await res.json(); const box = document.getElementById('chat-box'); box.innerHTML = "";
611
- data.messages.forEach(msg => {
612
- const isUser = msg.role === 'user';
613
- if(isUser) {
614
- box.insertAdjacentHTML('beforeend', `<div class="msg user-msg"><div class="user-content">${msg.content.replace(/</g, "&lt;")}</div></div>`);
615
- } else {
616
- const div = document.createElement('div'); div.className = 'msg ai-msg';
617
- div.innerHTML = `<div class="ai-content">${marked.parse(msg.content)}</div>`;
618
- box.appendChild(div);
619
- hljs.highlightAll();
620
- if(window.MathJax) MathJax.typesetPromise([div]);
621
- div.insertAdjacentHTML('beforeend', `<div class="msg-actions"><i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i></div>`);
622
- }
623
- });
624
- document.getElementById('sidebar').classList.remove('open');
625
- box.scrollTop = box.scrollHeight;
626
- }
627
-
628
  checkLogin();
629
  </script>
630
  </body>
631
  </html>
632
  """
633
 
634
- # --- BACKEND ROUTES START HERE ---
635
  @app.route("/", methods=["GET"])
636
  def home(): return render_template_string(HTML_TEMPLATE)
637
 
@@ -678,19 +304,15 @@ def chat():
678
  u, cid, msg = d.get("username"), d.get("chat_id"), d.get("message")
679
  img_data = d.get("image")
680
  file_text = d.get("file_text")
681
-
682
  if u not in user_db: user_db[u] = {}
683
  if cid not in user_db[u]: user_db[u][cid] = {"messages": []}
684
-
685
  user_db[u][cid]["messages"].append({"role": "user", "content": msg})
686
  reply = generate_with_retry(msg, img_data, file_text, user_db[u][cid]["messages"][:-1])
687
  user_db[u][cid]["messages"].append({"role": "model", "content": reply})
688
-
689
  new_title = False
690
  if len(user_db[u][cid]["messages"]) <= 2:
691
  user_db[u][cid]["title"] = " ".join(msg.split()[:4])
692
  new_title = True
693
-
694
  save_db(user_db)
695
  return jsonify({"response": reply, "new_title": new_title})
696
 
@@ -705,19 +327,11 @@ def manifest():
705
  "background_color": "#09090b",
706
  "theme_color": "#09090b",
707
  "icons": [
708
- {
709
- "src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
710
- "sizes": "192x192",
711
- "type": "image/png"
712
- },
713
- {
714
- "src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
715
- "sizes": "512x512",
716
- "type": "image/png"
717
- }
718
  ]
719
  }
720
  return Response(json.dumps(data), mimetype='application/json')
721
 
722
  if __name__ == '__main__':
723
- app.run(host='0.0.0.0', port=7860)
 
9
  from flask import Flask, request, jsonify, render_template_string, Response
10
  import google.generativeai as genai
11
 
 
12
  warnings.filterwarnings("ignore")
13
 
 
 
 
14
  keys_string = os.environ.get("API_KEYS", "")
15
  API_KEYS = [k.strip() for k in keys_string.replace(',', ' ').replace('\n', ' ').split() if k.strip()]
16
 
 
17
  DB_FILE = "chat_db.json"
18
  def load_db():
19
  try:
 
30
  current_key_index = 0
31
  app = Flask(__name__)
32
 
 
33
  SYSTEM_INSTRUCTION = """
34
  ROLE: You are "Student's AI", a professional academic tutor.
35
  RULES:
 
40
  5. **CODE:** Use Python/Java/C++ blocks. Explain logic briefly.
41
  """
42
 
 
43
  def get_working_model(key):
44
  try:
45
  genai.configure(api_key=key)
 
63
 
64
  def generate_with_retry(prompt, image_data=None, file_text=None, history_messages=[]):
65
  global current_key_index
66
+ if not API_KEYS: return "🚨 API Keys Missing."
67
 
68
  formatted_history = []
69
  for m in history_messages[-6:]:
 
80
  for i in range(len(API_KEYS)):
81
  key = API_KEYS[current_key_index]
82
  model_name = get_working_model(key)
 
83
  if not model_name:
84
  current_key_index = (current_key_index + 1) % len(API_KEYS)
85
  continue
 
86
  try:
87
  genai.configure(api_key=key)
88
  model = genai.GenerativeModel(model_name=model_name, system_instruction=SYSTEM_INSTRUCTION)
 
89
  if image_data or file_text:
90
  response = model.generate_content(current_parts)
91
  else:
 
95
  except Exception as e:
96
  current_key_index = (current_key_index + 1) % len(API_KEYS)
97
  time.sleep(1)
98
+ return "⚠️ System Busy. Please try again."
99
 
 
 
 
100
  HTML_TEMPLATE = """
101
  <!DOCTYPE html>
102
  <html lang="en">
103
  <head>
104
  <meta charset="UTF-8">
105
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
106
  <meta name="mobile-web-app-capable" content="yes">
107
  <meta name="apple-mobile-web-app-capable" content="yes">
108
  <meta name="theme-color" content="#09090b">
109
  <link rel="manifest" href="/manifest.json">
110
  <title>Student's AI</title>
 
111
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
112
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
 
113
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
114
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
115
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
 
120
  mermaid.initialize({ startOnLoad: false, theme: 'dark', securityLevel: 'loose' });
121
  window.mermaid = mermaid;
122
  </script>
 
123
  <style>
124
+ :root { --bg: #09090b; --card: #18181b; --user-msg: #27272a; --text: #e4e4e7; --accent: #fff; --border: #27272a; --dim: #71717a; }
 
 
 
125
  * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
126
+ body, html { margin: 0; padding: 0; height: 100dvh; width: 100%; background: var(--bg); color: var(--text); font-family: 'Outfit', sans-serif; overflow: hidden; font-size: 17px; user-select: none; -webkit-user-select: none; }
127
+ textarea, input { user-select: text !important; -webkit-user-select: text !important; }
 
 
 
 
 
 
 
 
 
128
  #app-container { display: flex; flex-direction: column; height: 100dvh; width: 100%; position: relative; overflow-x: hidden; }
129
+ header { height: 70px; padding: 0 20px; background: rgba(9,9,11, 0.98); border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; flex-shrink: 0; z-index: 50; padding-top: env(safe-area-inset-top); }
130
+ .menu-btn { width: 40px; height: 40px; border-radius: 50%; border: 1px solid #333; display: flex; align-items: center; justify-content: center; cursor: pointer; color: #fff; }
131
+ .app-title { font-size: 24px; font-weight: 800; color: #fff; }
132
+
133
+ #sidebar { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: var(--bg); z-index: 100; display: flex; flex-direction: column; padding: 25px; padding-top: calc(70px + env(safe-area-inset-top)); transform: translateY(-100%); transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1); overflow-y: auto; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  #sidebar.open { transform: translateY(0); }
135
+ @media (min-width: 768px) { #sidebar { width: 350px; border-right: 1px solid var(--border); } .input-container { max-width: 800px; } #chat-box { padding: 20px 15%; } }
136
 
 
 
 
 
 
 
137
  .user-info { margin-bottom: 30px; font-size: 20px; font-weight: 700; color: #fff; display: flex; align-items: center; gap: 15px; flex-shrink: 0; }
138
+ .new-chat-btn { width: 100%; padding: 15px; background: #fff; color: #000; border: none; border-radius: 12px; font-weight: 700; font-size: 16px; cursor: pointer; margin-bottom: 25px; flex-shrink: 0; }
139
+ .history-label { color: var(--dim); font-size: 13px; font-weight: 600; margin-bottom: 10px; text-transform: uppercase; flex-shrink: 0; }
 
 
 
 
140
  #history-list { flex: 1; overflow-y: auto; padding: 10px 0; min-height: 100px; }
141
+ .history-item { display: flex; justify-content: space-between; align-items: center; padding: 15px; margin-bottom: 12px; background: var(--card); border: 1px solid var(--border); border-radius: 12px; cursor: pointer; color: #a1a1aa; font-size: 15px; transition: 0.2s; }
142
+ .history-item:active { background: #222; color: #fff; }
 
 
 
 
 
143
  .h-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; flex: 1; margin-right: 10px; }
144
  .h-actions { display: none; gap: 15px; }
145
  .history-item.active-mode .h-actions { display: flex; }
146
+ .rename-input { background: transparent; border: none; border-bottom: 1px solid #fff; color: #fff; font-family: 'Outfit', sans-serif; font-size: 15px; width: 100%; outline: none; padding: 0; }
 
 
 
 
 
 
 
147
  .brand-section { text-align: center; margin-top: 20px; padding-bottom: env(safe-area-inset-bottom); flex-shrink: 0; }
148
+ .brand-name { font-weight: 600; font-size: 12px; color: var(--dim); letter-spacing: 2px; margin-bottom: 10px; }
149
  .logout-btn { color: #ef4444; cursor: pointer; font-size: 15px; font-weight: 600; padding: 10px; }
150
 
151
+ #chat-box { flex: 1; overflow-y: auto; padding: 20px 5%; padding-bottom: 80px; display: flex; flex-direction: column; gap: 25px; -webkit-overflow-scrolling: touch; }
 
 
 
 
 
152
  .msg { width: 100%; line-height: 1.7; font-size: 17px; opacity: 0; animation: fadeInstant 0.3s forwards; display: flex; flex-direction: column; }
153
  @keyframes fadeInstant { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
 
154
  .user-msg { align-items: flex-end; }
155
  .user-content { display: inline-block; width: fit-content; max-width: 85%; background: var(--user-msg); padding: 10px 16px; border-radius: 18px 18px 4px 18px; text-align: left; color: #fff; word-wrap: break-word; }
 
156
  .ai-msg { align-items: flex-start; }
157
  .ai-content { width: 100%; color: #d4d4d8; word-wrap: break-word; }
158
+ .ai-content strong { color: #fff; }
159
+ .ai-content h1, .ai-content h2 { margin-top: 20px; color: #fff; }
160
+ .msg-actions { margin-top: 10px; opacity: 0; transition: opacity 0.2s; display: flex; gap: 20px; }
 
 
 
 
 
 
 
 
 
161
  .msg:hover .msg-actions { opacity: 1; }
162
+ .action-icon { cursor: pointer; color: var(--dim); font-size: 18px; }
 
163
 
164
  .input-wrapper { background: var(--bg); padding: 15px; border-top: 1px solid var(--border); flex-shrink: 0; z-index: 60; padding-bottom: max(15px, env(safe-area-inset-bottom)); }
165
  .input-container { max-width: 900px; margin: 0 auto; background: var(--card); border: 1px solid var(--border); border-radius: 24px; padding: 8px 12px; display: flex; align-items: flex-end; gap: 12px; }
166
  textarea { flex: 1; background: transparent; border: none; color: #fff; font-size: 17px; max-height: 120px; padding: 10px 5px; resize: none; outline: none; font-family: 'Outfit', sans-serif; }
167
+ .icon-btn, .send-btn { width: 38px; height: 38px; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: none; cursor: pointer; font-size: 18px; }
168
+ .icon-btn { background: transparent; color: #a1a1aa; }
169
+ .send-btn { background: #fff; color: #000; }
170
  #preview-area { position: absolute; bottom: 85px; left: 20px; display: none; z-index: 70; }
171
+ .preview-box { width: 60px; height: 60px; border-radius: 12px; border: 2px solid #fff; background: #222; overflow: hidden; position: relative; }
172
  .preview-img { width: 100%; height: 100%; object-fit: cover; }
173
+ .remove-preview { position: absolute; top: -8px; right: -8px; background: red; color: white; border-radius: 50%; width: 20px; height: 20px; font-size: 12px; cursor: pointer; border: none; }
174
 
175
+ #login-overlay { position: fixed; inset: 0; background: #000; z-index: 2000; display: flex; align-items: flex-start; justify-content: center; padding-top: 25vh; transition: opacity 0.8s ease; opacity: 1; pointer-events: auto; }
 
 
 
 
 
 
 
 
176
  #login-overlay.hidden { opacity: 0; pointer-events: none; }
177
+ .login-box { width: 90%; max-width: 350px; text-align: center; padding: 40px; border: 1px solid var(--border); border-radius: 20px; background: #0a0a0a; margin: 0 auto; }
 
 
 
 
 
 
178
  #image-modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 3000; display: none; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s; }
179
+ #image-modal img { max-width: 95%; max-height: 90%; border-radius: 8px; }
180
  #image-modal.active { opacity: 1; }
181
  </style>
182
  </head>
183
  <body>
 
184
  <div id="login-overlay">
185
  <div class="login-box">
186
  <h1 class="app-title" style="margin-bottom:10px;">Student's AI</h1>
 
188
  <button onclick="handleLogin()" style="width:100%; padding:15px; border-radius:12px; border:none; background:#fff; font-weight:800; cursor:pointer; font-size: 16px;">Start Learning</button>
189
  </div>
190
  </div>
191
+ <div id="image-modal" onclick="closeImagePreview()"><img id="modal-img" src=""></div>
 
 
 
 
192
  <div id="sidebar">
193
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-shrink:0;">
194
  <div class="user-info"><span id="display-name">User</span></div>
 
202
  <div class="logout-btn" onclick="handleLogout()">Log Out</div>
203
  </div>
204
  </div>
 
205
  <div id="app-container">
206
  <header>
207
  <div class="menu-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
208
  <span class="app-title">Student's AI</span>
209
  <div style="width:40px;"></div>
210
  </header>
 
211
  <div id="chat-box"></div>
 
212
  <div class="input-wrapper">
213
  <div id="preview-area">
214
  <div class="preview-box"><div id="preview-visual"></div></div>
215
+ <button class="remove-preview" onclick="clearAttachment()">×</button>
216
  </div>
 
217
  <div class="input-container">
218
  <button class="icon-btn" onclick="document.getElementById('file-input').click()"><i class="fas fa-paperclip"></i></button>
219
  <input type="file" id="file-input" accept="image/*,.txt,.py,.js,.html,.css,.md,.csv,.json" hidden onchange="handleFileSelect(this)">
 
220
  <button class="icon-btn" onclick="document.getElementById('camera-input').click()"><i class="fas fa-camera"></i></button>
221
  <input type="file" id="camera-input" accept="image/*" capture="environment" hidden onchange="handleFileSelect(this)">
 
222
  <textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
 
223
  <button class="send-btn" onclick="send()"><i class="fas fa-arrow-up"></i></button>
224
  </div>
225
  </div>
226
  </div>
 
227
  <script>
228
+ let currentUser = null; let currentChatId = null; let currentAttachment = { type: null, data: null, name: null }; let longPressTimer;
229
+ function getIntroHtml(name) { return `<div class="msg ai-msg"><div class="ai-content"><h1>Hi ${name},</h1><p>Ready to master your studies today?</p></div></div>`; }
230
+ function checkLogin() { try { const stored = localStorage.getItem("student_ai_user"); if (stored) { currentUser = stored; document.getElementById("login-overlay").classList.add('hidden'); showApp(); } } catch(e) {} }
231
+ function handleLogin() { const input = document.getElementById("username-input"); const name = input.value.trim(); if(name) { try { localStorage.setItem("student_ai_user", name); } catch(e){} currentUser = name; document.getElementById("login-overlay").classList.add('hidden'); showApp(); } else { input.style.border = "1px solid red"; setTimeout(() => input.style.border = "1px solid #333", 2000); } }
232
+ function handleLogout() { try { localStorage.removeItem("student_ai_user"); } catch(e){} document.getElementById("login-overlay").classList.remove('hidden'); document.getElementById('sidebar').classList.remove('open'); setTimeout(() => { document.getElementById('chat-box').innerHTML = ""; currentChatId = null; document.getElementById("username-input").value = ""; }, 300); }
233
+ function showApp() { document.getElementById("display-name").innerText = "Hi " + currentUser; loadHistory(); if(!currentChatId) { const box = document.getElementById("chat-box"); if(box.innerHTML === "") { box.innerHTML = getIntroHtml(currentUser); } } }
234
+ function resizeInput(el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 150) + 'px'; }
235
+ function handleFileSelect(input) { if (input.files && input.files[0]) { const file = input.files[0]; const reader = new FileReader(); reader.onload = function(e) { const result = e.target.result; const isImage = file.type.startsWith('image/'); currentAttachment = { type: isImage ? 'image' : 'file', data: isImage ? result : atob(result.split(',')[1]), name: file.name }; document.getElementById('preview-area').style.display = 'block'; document.getElementById('preview-visual').innerHTML = isImage ? `<img src="${result}" class="preview-img">` : `<div style="display:flex;justify-content:center;align-items:center;height:100%;color:#fff;"><i class="fas fa-file"></i></div>`; }; reader.readAsDataURL(file); } input.value = ""; }
236
+ function clearAttachment() { currentAttachment = { type: null, data: null, name: null }; document.getElementById('preview-area').style.display = 'none'; }
237
+ function scrollToBottom() { const box = document.getElementById('chat-box'); setTimeout(() => { box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' }); }, 100); }
238
+ async function send() { const input = document.getElementById('input'); const text = input.value.trim(); if (!text && !currentAttachment.data) return; const chatBox = document.getElementById('chat-box'); let attachHtml = ''; if (currentAttachment.type === 'image') attachHtml = `<br><img src="${currentAttachment.data}" style="max-height:100px; margin-top:10px; border-radius:8px;">`; if (currentAttachment.type === 'file') attachHtml = `<br><small>📄 ${currentAttachment.name}</small>`; const userHtml = `<div class="msg user-msg"><div class="user-content">${text.replace(/</g, "&lt;")}${attachHtml}</div><div class="msg-actions"><i class="fas fa-copy action-icon" onclick="copyText('${text}')"></i><i class="fas fa-pen action-icon" onclick="editMessage('${text}')"></i></div></div>`; chatBox.insertAdjacentHTML('beforeend', userHtml); const promptText = text; const imgData = currentAttachment.type === 'image' ? currentAttachment.data : null; const fileText = currentAttachment.type === 'file' ? currentAttachment.data : null; input.value = ''; input.style.height = 'auto'; clearAttachment(); scrollToBottom(); const msgId = "ai-" + Date.now(); chatBox.insertAdjacentHTML('beforeend', `<div id="${msgId}" class="msg ai-msg"><i class="fas fa-circle-notch fa-spin"></i></div>`); scrollToBottom(); try { if (!currentChatId) { const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})}); const d = await r.json(); currentChatId = d.chat_id; loadHistory(); } const res = await fetch('/chat', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ message: promptText, image: imgData, file_text: fileText, username: currentUser, chat_id: currentChatId }) }); const data = await res.json(); const aiDiv = document.getElementById(msgId); aiDiv.innerHTML = ""; const contentDiv = document.createElement('div'); contentDiv.className = 'ai-content'; aiDiv.appendChild(contentDiv); await typeWriter(contentDiv, data.response); aiDiv.insertAdjacentHTML('beforeend', `<div class="msg-actions"><i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i><i class="fas fa-share-alt action-icon" onclick="shareResponse(this)"></i><i class="fas fa-redo action-icon" onclick="regenerate('${promptText}')"></i></div>`); scrollToBottom(); if(data.new_title) loadHistory(); } catch (e) { document.getElementById(msgId).innerHTML = "⚠️ Error: " + e.message; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  function copyText(text) { navigator.clipboard.writeText(text); }
240
+ function copyAiResponse(btn) { const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText; navigator.clipboard.writeText(text); }
241
+ function shareResponse(btn) { const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText; if (navigator.share) navigator.share({ title: 'Student AI', text: text }); else navigator.clipboard.writeText(text); }
 
 
 
 
 
 
 
242
  function editMessage(oldText) { document.getElementById('input').value = oldText; document.getElementById('input').focus(); }
243
  function regenerate(text) { document.getElementById('input').value = text; send(); }
244
+ document.getElementById('chat-box').addEventListener('click', function(e) { if(e.target.tagName === 'IMG') { const modal = document.getElementById('image-modal'); const modalImg = document.getElementById('modal-img'); modalImg.src = e.target.src; modal.style.display = 'flex'; setTimeout(() => modal.classList.add('active'), 10); } });
245
+ function closeImagePreview() { const modal = document.getElementById('image-modal'); modal.classList.remove('active'); setTimeout(() => modal.style.display = 'none', 300); }
246
+ function handleHistoryTouchStart(e, cid) { longPressTimer = setTimeout(() => { e.target.closest('.history-item').classList.add('active-mode'); }, 600); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  function handleHistoryTouchEnd(e) { clearTimeout(longPressTimer); }
248
+ function startRename(cid) { const item = document.getElementById('chat-' + cid); const titleSpan = item.querySelector('.h-title'); const currentTitle = titleSpan.innerText; const input = document.createElement('input'); input.type = 'text'; input.value = currentTitle; input.className = 'rename-input'; async function save() { const newTitle = input.value.trim(); if(newTitle && newTitle !== currentTitle) { await fetch('/rename_chat', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid, title:newTitle}) }); loadHistory(); } else { loadHistory(); } } input.addEventListener('blur', save); input.addEventListener('keydown', (e) => { if(e.key === 'Enter') { input.blur(); } }); titleSpan.replaceWith(input); input.focus(); }
249
+ async function deleteChat(cid) { const el = document.getElementById('chat-' + cid); if(el) el.remove(); await fetch('/delete_chat', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid}) }); if(currentChatId === cid) newChat(); loadHistory(); }
250
+ async function loadHistory() { try { const res = await fetch('/get_history', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})}); const data = await res.json(); const list = document.getElementById('history-list'); list.innerHTML = ""; if (data.chats) { Object.keys(data.chats).reverse().forEach(cid => { const title = data.chats[cid].title || "New Chat"; list.innerHTML += `<div class="history-item" id="chat-${cid}" onclick="loadChat('${cid}')" oncontextmenu="return false;" ontouchstart="handleHistoryTouchStart(event, '${cid}')" ontouchend="handleHistoryTouchEnd(event)"><span class="h-title">${title}</span><div class="h-actions"><i class="fas fa-pen h-icon" onclick="event.stopPropagation(); startRename('${cid}')"></i><i class="fas fa-trash h-icon" onclick="event.stopPropagation(); deleteChat('${cid}')"></i></div></div>`; }); } } catch(e) {} }
251
+ async function typeWriter(element, markdownText) { element.innerHTML = marked.parse(markdownText); hljs.highlightAll(); if (window.MathJax) await MathJax.typesetPromise([element]); if (window.mermaid) { const m = element.querySelectorAll('code.language-mermaid'); m.forEach(c => { const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d); }); window.mermaid.init(undefined, element.querySelectorAll('.mermaid')); } element.style.opacity = 0; element.style.transition = 'opacity 0.4s'; setTimeout(() => { element.style.opacity = 1; scrollToBottom(); }, 50); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }
253
+ async function newChat() { currentChatId = null; document.getElementById('chat-box').innerHTML = getIntroHtml(currentUser); const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})}); const d = await r.json(); currentChatId = d.chat_id; loadHistory(); document.getElementById('sidebar').classList.remove('open'); }
254
+ async function loadChat(cid) { currentChatId = cid; const res = await fetch('/get_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid})}); const data = await res.json(); const box = document.getElementById('chat-box'); box.innerHTML = ""; data.messages.forEach(msg => { const isUser = msg.role === 'user'; if(isUser) { box.insertAdjacentHTML('beforeend', `<div class="msg user-msg"><div class="user-content">${msg.content.replace(/</g, "&lt;")}</div></div>`); } else { const div = document.createElement('div'); div.className = 'msg ai-msg'; div.innerHTML = `<div class="ai-content">${marked.parse(msg.content)}</div>`; box.appendChild(div); hljs.highlightAll(); if(window.MathJax) MathJax.typesetPromise([div]); div.insertAdjacentHTML('beforeend', `<div class="msg-actions"><i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i></div>`); } }); document.getElementById('sidebar').classList.remove('open'); box.scrollTop = box.scrollHeight; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  checkLogin();
256
  </script>
257
  </body>
258
  </html>
259
  """
260
 
 
261
  @app.route("/", methods=["GET"])
262
  def home(): return render_template_string(HTML_TEMPLATE)
263
 
 
304
  u, cid, msg = d.get("username"), d.get("chat_id"), d.get("message")
305
  img_data = d.get("image")
306
  file_text = d.get("file_text")
 
307
  if u not in user_db: user_db[u] = {}
308
  if cid not in user_db[u]: user_db[u][cid] = {"messages": []}
 
309
  user_db[u][cid]["messages"].append({"role": "user", "content": msg})
310
  reply = generate_with_retry(msg, img_data, file_text, user_db[u][cid]["messages"][:-1])
311
  user_db[u][cid]["messages"].append({"role": "model", "content": reply})
 
312
  new_title = False
313
  if len(user_db[u][cid]["messages"]) <= 2:
314
  user_db[u][cid]["title"] = " ".join(msg.split()[:4])
315
  new_title = True
 
316
  save_db(user_db)
317
  return jsonify({"response": reply, "new_title": new_title})
318
 
 
327
  "background_color": "#09090b",
328
  "theme_color": "#09090b",
329
  "icons": [
330
+ {"src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png", "sizes": "192x192", "type": "image/png"},
331
+ {"src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png", "sizes": "512x512", "type": "image/png"}
 
 
 
 
 
 
 
 
332
  ]
333
  }
334
  return Response(json.dumps(data), mimetype='application/json')
335
 
336
  if __name__ == '__main__':
337
+ app.run(host='0.0.0.0', port=7860)