Shirpi commited on
Commit
5ea3b18
·
verified ·
1 Parent(s): fee9d22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -450
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)
@@ -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 ---
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,152 +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; 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
- /* --- SIDEBAR ANIMATION (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
- /* --- FIXED: LOGIN PAGE STABILITY & KEYBOARD --- */
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; padding-top: 25vh;
266
- transition: opacity 0.8s ease; opacity: 1; pointer-events: auto;
267
- }
268
  #login-overlay.hidden { opacity: 0; pointer-events: none; }
269
-
270
- .login-box {
271
- width: 90%; max-width: 350px; text-align: center;
272
- padding: 40px; border: 1px solid var(--border); border-radius: 20px; background: #0a0a0a;
273
- margin: 0 auto;
274
- }
275
-
276
  #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; }
277
- #image-modal img { max-width: 95%; max-height: 90%; border-radius: 8px; box-shadow: 0 0 20px rgba(0,0,0,0.8); }
278
  #image-modal.active { opacity: 1; }
279
  </style>
280
  </head>
281
  <body>
282
-
283
  <div id="login-overlay">
284
  <div class="login-box">
285
  <h1 class="app-title" style="margin-bottom:10px;">Student's AI</h1>
@@ -287,11 +188,7 @@ HTML_TEMPLATE = """
287
  <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>
288
  </div>
289
  </div>
290
-
291
- <div id="image-modal" onclick="closeImagePreview()">
292
- <img id="modal-img" src="" alt="Preview">
293
- </div>
294
-
295
  <div id="sidebar">
296
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-shrink:0;">
297
  <div class="user-info"><span id="display-name">User</span></div>
@@ -305,349 +202,136 @@ HTML_TEMPLATE = """
305
  <div class="logout-btn" onclick="handleLogout()">Log Out</div>
306
  </div>
307
  </div>
308
-
309
  <div id="app-container">
310
  <header>
311
  <div class="menu-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
312
  <span class="app-title">Student's AI</span>
313
  <div style="width:40px;"></div>
314
  </header>
315
-
316
  <div id="chat-box"></div>
317
-
318
  <div class="input-wrapper">
319
  <div id="preview-area">
320
  <div class="preview-box"><div id="preview-visual"></div></div>
321
  <button class="remove-preview" onclick="clearAttachment()">×</button>
322
  </div>
323
-
324
  <div class="input-container">
325
  <button class="icon-btn" onclick="document.getElementById('file-input').click()"><i class="fas fa-paperclip"></i></button>
326
  <input type="file" id="file-input" accept="image/*,.txt,.py,.js,.html,.css,.md,.csv,.json" hidden onchange="handleFileSelect(this)">
327
-
328
  <button class="icon-btn" onclick="document.getElementById('camera-input').click()"><i class="fas fa-camera"></i></button>
329
  <input type="file" id="camera-input" accept="image/*" capture="environment" hidden onchange="handleFileSelect(this)">
330
-
331
  <textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
332
-
333
  <button class="send-btn" onclick="send()"><i class="fas fa-arrow-up"></i></button>
334
  </div>
335
  </div>
336
  </div>
337
-
338
  <script>
339
- let currentUser = null;
340
- let currentChatId = null;
341
- let currentAttachment = { type: null, data: null, name: null };
342
- let longPressTimer;
343
-
344
- function getIntroHtml(name) {
345
- return `<div class="msg ai-msg"><div class="ai-content"><h1>Hi ${name},</h1><p>Ready to master your studies today?</p></div></div>`;
346
- }
347
-
348
- // --- AUTH LOGIC (SMOOTH TRANSITION) ---
349
- function checkLogin() {
350
- try {
351
- const stored = localStorage.getItem("student_ai_user");
352
- if (stored) {
353
- currentUser = stored;
354
- document.getElementById("login-overlay").classList.add('hidden');
355
- showApp();
356
- }
357
- } catch(e) { console.log("Storage access denied"); }
358
- }
359
-
360
- function handleLogin() {
361
- const input = document.getElementById("username-input");
362
- const name = input.value.trim();
363
- if(name) {
364
- try { localStorage.setItem("student_ai_user", name); } catch(e){}
365
- currentUser = name;
366
- document.getElementById("login-overlay").classList.add('hidden');
367
- showApp();
368
- } else {
369
- input.style.border = "1px solid red";
370
- setTimeout(() => input.style.border = "1px solid #333", 2000);
371
- }
372
- }
373
-
374
- function handleLogout() {
375
- try { localStorage.removeItem("student_ai_user"); } catch(e){}
376
- const overlay = document.getElementById("login-overlay");
377
- overlay.classList.remove('hidden'); // FADE IN LOGIN SCREEN
378
- document.getElementById('sidebar').classList.remove('open');
379
- setTimeout(() => {
380
- document.getElementById('chat-box').innerHTML = "";
381
- currentChatId = null;
382
- document.getElementById("username-input").value = "";
383
- }, 300);
384
- }
385
-
386
- function showApp() {
387
- document.getElementById("display-name").innerText = "Hi " + currentUser;
388
- loadHistory();
389
- if(!currentChatId) {
390
- const box = document.getElementById("chat-box");
391
- if(box.innerHTML === "") {
392
- box.innerHTML = getIntroHtml(currentUser);
393
- }
394
- }
395
- }
396
-
397
- function resizeInput(el) {
398
- el.style.height = 'auto';
399
- el.style.height = Math.min(el.scrollHeight, 150) + 'px';
400
- }
401
-
402
- function handleFileSelect(input) {
403
- if (input.files && input.files[0]) {
404
- const file = input.files[0];
405
- const reader = new FileReader();
406
- reader.onload = function(e) {
407
- const result = e.target.result;
408
- const isImage = file.type.startsWith('image/');
409
- currentAttachment = { type: isImage ? 'image' : 'file', data: isImage ? result : atob(result.split(',')[1]), name: file.name };
410
- const previewArea = document.getElementById('preview-area');
411
- const visual = document.getElementById('preview-visual');
412
- previewArea.style.display = 'block';
413
- visual.innerHTML = isImage ? `<img src="${result}" class="preview-img">` : `<div class="preview-file-icon"><i class="fas fa-file-alt"></i></div>`;
414
- }
415
- reader.readAsDataURL(file);
416
- }
417
- input.value = "";
418
- }
419
-
420
- function clearAttachment() {
421
- currentAttachment = { type: null, data: null, name: null };
422
- document.getElementById('preview-area').style.display = 'none';
423
- }
424
-
425
- function scrollToBottom() {
426
- const box = document.getElementById('chat-box');
427
- setTimeout(() => {
428
- box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });
429
- }, 100);
430
- }
431
-
432
- async function send() {
433
- const input = document.getElementById('input');
434
- const text = input.value.trim();
435
- if (!text && !currentAttachment.data) return;
436
-
437
- const chatBox = document.getElementById('chat-box');
438
- let attachHtml = '';
439
- if (currentAttachment.type === 'image') attachHtml = `<br><img src="${currentAttachment.data}" style="max-height:100px; margin-top:10px; border-radius:8px;">`;
440
- if (currentAttachment.type === 'file') attachHtml = `<br><small>📄 ${currentAttachment.name}</small>`;
441
-
442
- const userHtml = `
443
- <div class="msg user-msg">
444
- <div class="user-content">${text.replace(/</g, "&lt;")}${attachHtml}</div>
445
- <div class="msg-actions">
446
- <i class="fas fa-copy action-icon" onclick="copyText('${text}')"></i>
447
- <i class="fas fa-pen action-icon" onclick="editMessage('${text}')"></i>
448
- </div>
449
- </div>`;
450
- chatBox.insertAdjacentHTML('beforeend', userHtml);
451
-
452
- const promptText = text;
453
- const imgData = currentAttachment.type === 'image' ? currentAttachment.data : null;
454
- const fileText = currentAttachment.type === 'file' ? currentAttachment.data : null;
455
-
456
- input.value = ''; input.style.height = 'auto';
457
- clearAttachment();
458
- scrollToBottom();
459
-
460
- const msgId = "ai-" + Date.now();
461
- chatBox.insertAdjacentHTML('beforeend', `<div id="${msgId}" class="msg ai-msg"><i class="fas fa-circle-notch fa-spin"></i></div>`);
462
- scrollToBottom();
463
-
464
- try {
465
- if (!currentChatId) {
466
- const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
467
- const d = await r.json(); currentChatId = d.chat_id;
468
- loadHistory();
469
- }
470
- const res = await fetch('/chat', {
471
- method: 'POST', headers: {'Content-Type': 'application/json'},
472
- body: JSON.stringify({ message: promptText, image: imgData, file_text: fileText, username: currentUser, chat_id: currentChatId })
473
- });
474
- const data = await res.json();
475
-
476
- const aiDiv = document.getElementById(msgId);
477
- aiDiv.innerHTML = "";
478
- const contentDiv = document.createElement('div');
479
- contentDiv.className = 'ai-content';
480
- aiDiv.appendChild(contentDiv);
481
-
482
- await typeWriter(contentDiv, data.response);
483
-
484
- aiDiv.insertAdjacentHTML('beforeend', `
485
- <div class="msg-actions">
486
- <i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i>
487
- <i class="fas fa-share-alt action-icon" onclick="shareResponse(this)"></i>
488
- <i class="fas fa-redo action-icon" onclick="regenerate('${promptText}')"></i>
489
- </div>`);
490
-
491
- scrollToBottom();
492
- if(data.new_title) loadHistory();
493
- } catch (e) { document.getElementById(msgId).innerHTML = "⚠️ Error: " + e.message; }
494
- }
495
-
496
  function copyText(text) { navigator.clipboard.writeText(text); }
497
- function copyAiResponse(btn) {
498
- const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
499
- navigator.clipboard.writeText(text);
500
- }
501
- function shareResponse(btn) {
502
- const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
503
- if (navigator.share) navigator.share({ title: 'Student AI', text: text });
504
- else navigator.clipboard.writeText(text);
505
- }
506
  function editMessage(oldText) { document.getElementById('input').value = oldText; document.getElementById('input').focus(); }
507
  function regenerate(text) { document.getElementById('input').value = text; send(); }
508
-
509
- document.getElementById('chat-box').addEventListener('click', function(e) {
510
- if(e.target.tagName === 'IMG') {
511
- const modal = document.getElementById('image-modal');
512
- const modalImg = document.getElementById('modal-img');
513
- modalImg.src = e.target.src;
514
- modal.style.display = 'flex';
515
- setTimeout(() => modal.classList.add('active'), 10);
516
- }
517
- });
518
- function closeImagePreview() {
519
- const modal = document.getElementById('image-modal');
520
- modal.classList.remove('active');
521
- setTimeout(() => modal.style.display = 'none', 300);
522
- }
523
-
524
- function handleHistoryTouchStart(e, cid) {
525
- longPressTimer = setTimeout(() => {
526
- e.target.closest('.history-item').classList.add('active-mode');
527
- }, 600);
528
- }
529
  function handleHistoryTouchEnd(e) { clearTimeout(longPressTimer); }
530
-
531
- function startRename(cid) {
532
- const item = document.getElementById('chat-' + cid);
533
- const titleSpan = item.querySelector('.h-title');
534
- const currentTitle = titleSpan.innerText;
535
- const input = document.createElement('input');
536
- input.type = 'text'; input.value = currentTitle; input.className = 'rename-input';
537
-
538
- async function save() {
539
- const newTitle = input.value.trim();
540
- if(newTitle && newTitle !== currentTitle) {
541
- await fetch('/rename_chat', {
542
- method:'POST', headers:{'Content-Type':'application/json'},
543
- body:JSON.stringify({username:currentUser, chat_id:cid, title:newTitle})
544
- });
545
- loadHistory();
546
- } else { loadHistory(); }
547
- }
548
- input.addEventListener('blur', save);
549
- input.addEventListener('keydown', (e) => { if(e.key === 'Enter') { input.blur(); } });
550
- titleSpan.replaceWith(input); input.focus();
551
- }
552
-
553
- async function deleteChat(cid) {
554
- const el = document.getElementById('chat-' + cid);
555
- if(el) el.remove();
556
- await fetch('/delete_chat', {
557
- method:'POST', headers:{'Content-Type':'application/json'},
558
- body:JSON.stringify({username:currentUser, chat_id:cid})
559
- });
560
- if(currentChatId === cid) newChat();
561
- loadHistory();
562
- }
563
-
564
- async function loadHistory() {
565
- try {
566
- const res = await fetch('/get_history', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
567
- const data = await res.json();
568
- const list = document.getElementById('history-list'); list.innerHTML = "";
569
- if (data.chats) {
570
- Object.keys(data.chats).reverse().forEach(cid => {
571
- const title = data.chats[cid].title || "New Chat";
572
- list.innerHTML += `
573
- <div class="history-item" id="chat-${cid}" onclick="loadChat('${cid}')" oncontextmenu="return false;"
574
- ontouchstart="handleHistoryTouchStart(event, '${cid}')" ontouchend="handleHistoryTouchEnd(event)">
575
- <span class="h-title">${title}</span>
576
- <div class="h-actions">
577
- <i class="fas fa-pen h-icon" onclick="event.stopPropagation(); startRename('${cid}')"></i>
578
- <i class="fas fa-trash h-icon" onclick="event.stopPropagation(); deleteChat('${cid}')"></i>
579
- </div>
580
- </div>`;
581
- });
582
- }
583
- } catch(e) {}
584
- }
585
-
586
- async function typeWriter(element, markdownText) {
587
- element.innerHTML = marked.parse(markdownText);
588
- hljs.highlightAll();
589
- if (window.MathJax) await MathJax.typesetPromise([element]);
590
- if (window.mermaid) {
591
- const m = element.querySelectorAll('code.language-mermaid');
592
- m.forEach(c => { const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d); });
593
- window.mermaid.init(undefined, element.querySelectorAll('.mermaid'));
594
- }
595
- element.style.opacity = 0; element.style.transition = 'opacity 0.4s';
596
- setTimeout(() => { element.style.opacity = 1; scrollToBottom(); }, 50);
597
- }
598
-
599
  function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }
600
- async function newChat() {
601
- currentChatId = null;
602
- document.getElementById('chat-box').innerHTML = getIntroHtml(currentUser);
603
- const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
604
- const d = await r.json(); currentChatId = d.chat_id; loadHistory();
605
- document.getElementById('sidebar').classList.remove('open');
606
- }
607
- async function loadChat(cid) {
608
- currentChatId = cid; const res = await fetch('/get_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid})});
609
- const data = await res.json(); const box = document.getElementById('chat-box'); box.innerHTML = "";
610
- data.messages.forEach(msg => {
611
- const isUser = msg.role === 'user';
612
- if(isUser) {
613
- box.insertAdjacentHTML('beforeend', `<div class="msg user-msg"><div class="user-content">${msg.content.replace(/</g, "&lt;")}</div></div>`);
614
- } else {
615
- const div = document.createElement('div'); div.className = 'msg ai-msg';
616
- div.innerHTML = `<div class="ai-content">${marked.parse(msg.content)}</div>`;
617
- box.appendChild(div);
618
- hljs.highlightAll();
619
- if(window.MathJax) MathJax.typesetPromise([div]);
620
- div.insertAdjacentHTML('beforeend', `<div class="msg-actions"><i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i></div>`);
621
- }
622
- });
623
- document.getElementById('sidebar').classList.remove('open');
624
- box.scrollTop = box.scrollHeight;
625
- }
626
-
627
- @app.route('/manifest.json')
628
- def manifest():
629
- data = {
630
- "name": "Student's AI",
631
- "short_name": "Student's AI",
632
- "start_url": "/",
633
- "display": "standalone",
634
- "orientation": "portrait",
635
- "background_color": "#09090b",
636
- "theme_color": "#09090b",
637
- "icons": [
638
- {
639
- "src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
640
- "sizes": "192x192",
641
- "type": "image/png"
642
- },
643
- {
644
- "src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
645
- "sizes": "512x512",
646
- "type": "image/png"
647
- }
648
- ]
649
- }
650
- return Response(json.dumps(data), mimetype='application/json')
651
 
652
- if __name__ == '__main__':
653
- 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)
 
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
+
264
+ @app.route("/new_chat", methods=["POST"])
265
+ def new_chat():
266
+ u = request.json.get("username")
267
+ if u not in user_db: user_db[u] = {}
268
+ nid = str(uuid.uuid4())
269
+ user_db[u][nid] = {"title": "New Chat", "messages": []}
270
+ save_db(user_db)
271
+ return jsonify({"chat_id": nid})
272
+
273
+ @app.route("/rename_chat", methods=["POST"])
274
+ def rename_chat():
275
+ d = request.json
276
+ u, cid, t = d.get("username"), d.get("chat_id"), d.get("title")
277
+ if u in user_db and cid in user_db[u]:
278
+ user_db[u][cid]["title"] = t
279
+ save_db(user_db)
280
+ return jsonify({"status":"ok"})
281
+
282
+ @app.route("/delete_chat", methods=["POST"])
283
+ def delete_chat():
284
+ d = request.json
285
+ u, cid = d.get("username"), d.get("chat_id")
286
+ if u in user_db and cid in user_db[u]:
287
+ del user_db[u][cid]
288
+ save_db(user_db)
289
+ return jsonify({"status":"ok"})
290
+
291
+ @app.route("/get_history", methods=["POST"])
292
+ def get_history():
293
+ u = request.json.get("username")
294
+ return jsonify({"chats": user_db.get(u, {})})
295
+
296
+ @app.route("/get_chat", methods=["POST"])
297
+ def get_chat():
298
+ d = request.json
299
+ return jsonify({"messages": user_db.get(d["username"], {}).get(d["chat_id"], {}).get("messages", [])})
300
+
301
+ @app.route("/chat", methods=["POST"])
302
+ def chat():
303
+ d = request.json
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
+
319
+ @app.route('/manifest.json')
320
+ def manifest():
321
+ data = {
322
+ "name": "Student's AI",
323
+ "short_name": "StudentAI",
324
+ "start_url": "/",
325
+ "display": "standalone",
326
+ "orientation": "portrait",
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)