Shirpi commited on
Commit
da52f07
·
verified ·
1 Parent(s): 922f0ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +241 -114
app.py CHANGED
@@ -39,9 +39,10 @@ RULES:
39
  2. **DIAGRAMS:** Use Mermaid.js (```mermaid ... ```).
40
  3. **LANGUAGE:** English by default. Use Tamil/Tanglish ONLY if requested.
41
  4. **FORMAT:** Markdown. Bold key terms.
 
42
  """
43
 
44
- # --- 🧬 MODEL & IMAGE HANDLING ---
45
  def get_working_model(key):
46
  genai.configure(api_key=key)
47
  try:
@@ -63,16 +64,27 @@ def process_image(image_data):
63
  return Image.open(io.BytesIO(image_bytes))
64
  except: return None
65
 
66
- def generate_with_retry(prompt, image_data=None, history_messages=[]):
67
  global current_key_index
68
  if not API_KEYS: return "🚨 API Keys Missing."
69
 
 
70
  formatted_history = []
71
  for m in history_messages[-6:]:
72
  role = "user" if m["role"] == "user" else "model"
73
  formatted_history.append({"role": role, "parts": [m["content"]]})
74
 
75
- current_parts = [prompt]
 
 
 
 
 
 
 
 
 
 
76
  if image_data:
77
  img = process_image(image_data)
78
  if img: current_parts.append(img)
@@ -89,7 +101,10 @@ def generate_with_retry(prompt, image_data=None, history_messages=[]):
89
  genai.configure(api_key=key)
90
  model = genai.GenerativeModel(model_name=model_name, system_instruction=SYSTEM_INSTRUCTION)
91
 
92
- if image_data:
 
 
 
93
  response = model.generate_content(current_parts)
94
  else:
95
  chat = model.start_chat(history=formatted_history)
@@ -102,7 +117,7 @@ def generate_with_retry(prompt, image_data=None, history_messages=[]):
102
 
103
  return "⚠️ System Busy. Please try again."
104
 
105
- # --- UI TEMPLATE (PERFORMANCE OPTIMIZED) ---
106
  HTML_TEMPLATE = """
107
  <!DOCTYPE html>
108
  <html lang="en">
@@ -130,7 +145,7 @@ HTML_TEMPLATE = """
130
  :root {
131
  --bg-color: #09090b; --sidebar-bg: #000000; --card-bg: #18181b;
132
  --user-msg-bg: #27272a; --text-color: #e4e4e7; --code-bg: #0f0f11;
133
- --border-color: #27272a;
134
  }
135
  * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
136
  body, html { margin: 0; padding: 0; height: 100%; width: 100%; background: var(--bg-color); color: var(--text-color); font-family: 'Outfit', sans-serif; overflow: hidden; }
@@ -140,7 +155,7 @@ HTML_TEMPLATE = """
140
  /* HEADER */
141
  header {
142
  height: 65px; padding: 0 20px;
143
- background: rgba(9,9,11, 0.98); /* Less transparency = Less Lag */
144
  border-bottom: 1px solid var(--border-color);
145
  display: flex; align-items: center; justify-content: space-between; flex-shrink: 0; z-index: 50;
146
  }
@@ -157,23 +172,37 @@ HTML_TEMPLATE = """
157
  .overlay.active { opacity: 1; pointer-events: auto; }
158
 
159
  .search-box { background: var(--card-bg); border: 1px solid var(--border-color); padding: 12px; border-radius: 10px; color: #fff; width: 100%; margin-bottom: 15px; outline: none; }
 
160
  #history-list { flex: 1; overflow-y: auto; }
161
- .history-item { padding: 12px; border-radius: 8px; cursor: pointer; color: #a1a1aa; font-size: 14px; margin-bottom: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
 
 
 
162
  .history-item:hover { background: var(--user-msg-bg); color: #fff; }
163
-
164
- /* CHAT AREA - FIX FOR LAG */
 
 
 
 
 
 
 
 
 
 
165
  #chat-box {
166
  flex: 1; overflow-y: auto; padding: 20px 5%;
167
  display: flex; flex-direction: column; gap: 20px;
168
- /* CRITICAL FIX FOR MOBILE SCROLLING */
169
- -webkit-overflow-scrolling: touch;
170
- overscroll-behavior-y: contain;
171
  }
172
 
173
- /* Message Styles */
174
- .msg { width: 100%; line-height: 1.6; font-size: 16px; }
175
- .user-msg { text-align: right; animation: fadeInstant 0.3s forwards; }
176
- .user-bubble { display: inline-block; background: var(--user-msg-bg); padding: 10px 18px; border-radius: 18px 18px 4px 18px; text-align: left; max-width: 85%; }
 
 
177
 
178
  .ai-msg { text-align: left; }
179
  .ai-content strong { color: #fff; font-weight: 700; }
@@ -201,26 +230,25 @@ HTML_TEMPLATE = """
201
  }
202
  textarea { flex: 1; background: transparent; border: none; color: #fff; font-size: 16px; max-height: 120px; padding: 10px 5px; resize: none; outline: none; font-family: 'Outfit', sans-serif; }
203
 
204
- .icon-btn {
205
- width: 36px; height: 36px; display: flex; align-items: center; justify-content: center;
206
- border-radius: 50%; border: none; background: transparent; color: #a1a1aa; cursor: pointer; font-size: 16px;
207
- }
208
  .icon-btn:hover { background: #333; color: #fff; }
209
-
210
- .send-btn {
211
- background: #fff; color: #000; width: 36px; height: 36px; border-radius: 50%; border: none;
212
- display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 16px;
213
- }
214
 
215
- #image-preview-area { max-width: 900px; margin: 0 auto 10px auto; display: none; padding: 0 10px; }
216
- .preview-img { height: 60px; border-radius: 8px; border: 1px solid #333; }
217
- .remove-img { position: absolute; top: -5px; right: -5px; background: red; color: white; border-radius: 50%; width: 18px; height: 18px; font-size: 12px; cursor: pointer; border: none; }
 
 
 
 
 
 
 
218
 
219
  /* LOGIN */
220
  #login-overlay { position: fixed; inset: 0; background: #000; z-index: 2000; display: flex; align-items: center; justify-content: center; }
221
  .login-box { width: 90%; max-width: 350px; text-align: center; padding: 30px; border: 1px solid var(--border-color); border-radius: 20px; background: #0a0a0a; }
222
 
223
- @keyframes fadeInstant { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
224
  </style>
225
  </head>
226
  <body>
@@ -243,8 +271,13 @@ HTML_TEMPLATE = """
243
  </div>
244
  <button onclick="newChat()" style="width:100%; padding:10px; background:#fff; border:none; border-radius:8px; cursor:pointer; font-weight:700; margin-bottom:15px;">+ New Chat</button>
245
  <input type="text" class="search-box" placeholder="Search..." onkeyup="filterHistory(this.value)">
 
246
  <div id="history-list"></div>
247
- <div style="margin-top:auto; padding-top:20px; border-top:1px solid #333; text-align:center; color:#ef4444; cursor:pointer;" onclick="handleLogout()">Log Out</div>
 
 
 
 
248
  </div>
249
 
250
  <header>
@@ -257,23 +290,23 @@ HTML_TEMPLATE = """
257
  <div id="chat-box"></div>
258
 
259
  <div class="input-wrapper">
260
- <div id="image-preview-area">
261
- <div style="position:relative; display:inline-block;">
262
- <img id="preview-img-tag" class="preview-img">
263
- <button class="remove-img" onclick="removeImage()">×</button>
264
  </div>
265
  </div>
266
 
267
  <div class="input-container">
268
- <button class="icon-btn" onclick="document.getElementById('file-upload').click()">
269
  <i class="fas fa-paperclip"></i>
270
  </button>
271
- <input type="file" id="file-upload" accept="image/*" hidden onchange="handleImageSelect(this)">
272
 
273
- <button class="icon-btn" onclick="document.getElementById('camera-upload').click()">
274
  <i class="fas fa-camera"></i>
275
  </button>
276
- <input type="file" id="camera-upload" accept="image/*" capture="environment" hidden onchange="handleImageSelect(this)">
277
 
278
  <textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
279
 
@@ -287,7 +320,7 @@ HTML_TEMPLATE = """
287
  <script>
288
  let currentUser = null;
289
  let currentChatId = null;
290
- let currentImageBase64 = null;
291
 
292
  function checkLogin() {
293
  const stored = localStorage.getItem("student_ai_user");
@@ -312,25 +345,52 @@ HTML_TEMPLATE = """
312
  el.style.height = Math.min(el.scrollHeight, 150) + 'px';
313
  }
314
 
315
- function handleImageSelect(input) {
 
316
  if (input.files && input.files[0]) {
 
317
  const reader = new FileReader();
 
318
  reader.onload = function(e) {
319
- currentImageBase64 = e.target.result;
320
- document.getElementById('preview-img-tag').src = currentImageBase64;
321
- document.getElementById('image-preview-area').style.display = 'block';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
  }
323
- reader.readAsDataURL(input.files[0]);
324
  }
325
  }
326
- function removeImage() {
327
- currentImageBase64 = null;
328
- document.getElementById('file-upload').value = "";
329
- document.getElementById('camera-upload').value = "";
330
- document.getElementById('image-preview-area').style.display = 'none';
 
331
  }
332
 
333
- // --- SCROLL OPTIMIZATION ---
334
  function scrollToBottom() {
335
  const box = document.getElementById('chat-box');
336
  box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });
@@ -339,28 +399,44 @@ HTML_TEMPLATE = """
339
  async function send() {
340
  const input = document.getElementById('input');
341
  const text = input.value.trim();
342
- if (!text && !currentImageBase64) return;
343
 
344
  const chatBox = document.getElementById('chat-box');
345
 
346
- const userHtml = `
 
 
 
 
 
 
 
 
347
  <div class="msg user-msg">
348
- <div class="user-bubble">${text.replace(/</g, "&lt;")}
349
- ${currentImageBase64 ? '<br><img src="'+currentImageBase64+'" style="max-height:100px; margin-top:5px; border-radius:5px;">' : ''}
350
- </div>
351
  <div class="msg-actions">
352
- <span class="action-btn" onclick="editMessage('${text}')"><i class="fas fa-pen"></i> Edit</span>
 
353
  </div>
354
  </div>`;
355
 
356
  chatBox.insertAdjacentHTML('beforeend', userHtml);
357
 
358
- const promptText = text;
359
- const imgData = currentImageBase64;
 
 
 
 
 
 
 
 
360
  input.value = ''; input.style.height = 'auto';
361
- removeImage();
362
  scrollToBottom();
363
 
 
364
  const msgId = "ai-" + Date.now();
365
  chatBox.insertAdjacentHTML('beforeend', `<div id="${msgId}" class="msg ai-msg"><i class="fas fa-circle-notch fa-spin"></i></div>`);
366
  scrollToBottom();
@@ -369,17 +445,13 @@ HTML_TEMPLATE = """
369
  if (!currentChatId) {
370
  const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
371
  const d = await r.json(); currentChatId = d.chat_id;
 
372
  loadHistory();
373
  }
374
 
375
  const res = await fetch('/chat', {
376
  method: 'POST', headers: {'Content-Type': 'application/json'},
377
- body: JSON.stringify({
378
- message: promptText,
379
- image: imgData,
380
- username: currentUser,
381
- chat_id: currentChatId
382
- })
383
  });
384
  const data = await res.json();
385
 
@@ -390,13 +462,14 @@ HTML_TEMPLATE = """
390
  contentDiv.className = 'ai-content';
391
  aiDiv.appendChild(contentDiv);
392
 
393
- // --- RESTORED TYPEWRITER ANIMATION (Optimized) ---
394
  await typeWriter(contentDiv, data.response);
395
 
 
396
  aiDiv.insertAdjacentHTML('beforeend', `
397
  <div class="msg-actions">
398
- <span class="action-btn" onclick="navigator.clipboard.writeText(this.closest('.ai-msg').innerText)"><i class="fas fa-copy"></i> Copy</span>
399
- <span class="action-btn" onclick="regenerate('${promptText}')"><i class="fas fa-redo"></i> Regen</span>
 
400
  </div>`);
401
 
402
  scrollToBottom();
@@ -407,35 +480,22 @@ HTML_TEMPLATE = """
407
  }
408
  }
409
 
410
- // --- ANIMATION LOGIC ---
411
- async function typeWriter(element, markdownText) {
412
- // 1. Render markdown
413
- element.innerHTML = marked.parse(markdownText);
414
-
415
- // 2. Math & Diagrams
416
- if (window.MathJax) await MathJax.typesetPromise([element]);
417
- if (window.mermaid) {
418
- const m = element.querySelectorAll('code.language-mermaid');
419
- m.forEach(c => {
420
- const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d);
421
- });
422
- window.mermaid.init(undefined, element.querySelectorAll('.mermaid'));
423
- }
424
 
425
- // 3. FADE IN ANIMATION (Not Typewriter char-by-char) for Smoothness
426
- // This is "ChatGPT-style" line reveal without the lag.
427
- const children = Array.from(element.children);
428
- children.forEach((child, index) => {
429
- child.style.opacity = '0';
430
- child.style.transform = 'translateY(10px)';
431
- child.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
432
-
433
- setTimeout(() => {
434
- child.style.opacity = '1';
435
- child.style.transform = 'translateY(0)';
436
- scrollToBottom();
437
- }, index * 120);
438
- });
439
  }
440
 
441
  function editMessage(oldText) {
@@ -447,9 +507,29 @@ HTML_TEMPLATE = """
447
  send();
448
  }
449
 
450
- function toggleSidebar() {
451
- document.getElementById('sidebar').classList.toggle('open');
452
- document.getElementById('overlay').classList.toggle('active');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453
  }
454
 
455
  async function loadHistory() {
@@ -460,17 +540,45 @@ HTML_TEMPLATE = """
460
  if (data.chats) {
461
  Object.keys(data.chats).reverse().forEach(cid => {
462
  const title = data.chats[cid].title || "New Chat";
463
- list.innerHTML += `<div class="history-item" onclick="loadChat('${cid}')">${title}</div>`;
 
 
 
 
 
 
 
464
  });
465
  }
466
  } catch(e) {}
467
  }
468
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469
  function filterHistory(q) {
470
  const items = document.querySelectorAll('.history-item');
471
- items.forEach(i => i.style.display = i.innerText.toLowerCase().includes(q.toLowerCase()) ? 'block' : 'none');
472
  }
473
-
474
  async function newChat() {
475
  currentChatId = null;
476
  document.getElementById('chat-box').innerHTML = "";
@@ -480,31 +588,32 @@ HTML_TEMPLATE = """
480
  document.getElementById('sidebar').classList.remove('open');
481
  document.getElementById('overlay').classList.remove('active');
482
  }
483
-
484
  async function loadChat(cid) {
485
  currentChatId = cid;
486
  const res = await fetch('/get_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid})});
487
  const data = await res.json();
488
  const box = document.getElementById('chat-box'); box.innerHTML = "";
489
-
490
  data.messages.forEach(msg => {
491
  const isUser = msg.role === 'user';
492
  let content = msg.content;
493
  if(isUser) {
494
- box.insertAdjacentHTML('beforeend', `<div class="msg user-msg"><div class="user-bubble">${content.replace(/</g, "&lt;")}</div></div>`);
 
495
  } else {
496
- const div = document.createElement('div');
497
- div.className = 'msg ai-msg';
498
  div.innerHTML = `<div class="ai-content">${marked.parse(content)}</div>`;
499
  box.appendChild(div);
500
  if(window.MathJax) MathJax.typesetPromise([div]);
501
  if(window.mermaid) {
502
  const m = div.querySelectorAll('code.language-mermaid');
503
- m.forEach(c => {
504
- const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d);
505
- });
506
  window.mermaid.init(undefined, div.querySelectorAll('.mermaid'));
507
  }
 
 
 
 
 
508
  }
509
  });
510
  document.getElementById('sidebar').classList.remove('open');
@@ -531,6 +640,24 @@ def new_chat():
531
  save_db(user_db)
532
  return jsonify({"chat_id": nid})
533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  @app.route("/get_history", methods=["POST"])
535
  def get_history():
536
  u = request.json.get("username")
@@ -546,12 +673,13 @@ def chat():
546
  d = request.json
547
  u, cid, msg = d.get("username"), d.get("chat_id"), d.get("message")
548
  img_data = d.get("image")
 
549
 
550
  if u not in user_db: user_db[u] = {}
551
  if cid not in user_db[u]: user_db[u][cid] = {"messages": []}
552
 
553
  user_db[u][cid]["messages"].append({"role": "user", "content": msg})
554
- reply = generate_with_retry(msg, img_data, user_db[u][cid]["messages"][:-1])
555
  user_db[u][cid]["messages"].append({"role": "model", "content": reply})
556
 
557
  new_title = False
@@ -564,4 +692,3 @@ def chat():
564
 
565
  if __name__ == '__main__':
566
  app.run(host='0.0.0.0', port=7860)
567
-
 
39
  2. **DIAGRAMS:** Use Mermaid.js (```mermaid ... ```).
40
  3. **LANGUAGE:** English by default. Use Tamil/Tanglish ONLY if requested.
41
  4. **FORMAT:** Markdown. Bold key terms.
42
+ 5. **FILES:** If a file/image is provided, analyze it thoroughly.
43
  """
44
 
45
+ # --- 🧬 MODEL & FILE HANDLING ---
46
  def get_working_model(key):
47
  genai.configure(api_key=key)
48
  try:
 
64
  return Image.open(io.BytesIO(image_bytes))
65
  except: return None
66
 
67
+ def generate_with_retry(prompt, image_data=None, file_text=None, history_messages=[]):
68
  global current_key_index
69
  if not API_KEYS: return "🚨 API Keys Missing."
70
 
71
+ # Format History
72
  formatted_history = []
73
  for m in history_messages[-6:]:
74
  role = "user" if m["role"] == "user" else "model"
75
  formatted_history.append({"role": role, "parts": [m["content"]]})
76
 
77
+ # Prepare Input Parts
78
+ current_parts = []
79
+
80
+ # Add File Text if exists (e.g. Code files)
81
+ if file_text:
82
+ current_parts.append(f"analyzing this file content:\n\n{file_text}\n\n")
83
+
84
+ # Add User Prompt
85
+ current_parts.append(prompt)
86
+
87
+ # Add Image if exists
88
  if image_data:
89
  img = process_image(image_data)
90
  if img: current_parts.append(img)
 
101
  genai.configure(api_key=key)
102
  model = genai.GenerativeModel(model_name=model_name, system_instruction=SYSTEM_INSTRUCTION)
103
 
104
+ # Use generate_content for stateless logic (Handle Images/Files better)
105
+ # We prepend history manually to prompt if needed, but for simplicity/stability
106
+ # with files, we assume 'current_parts' holds the main context.
107
+ if image_data or file_text:
108
  response = model.generate_content(current_parts)
109
  else:
110
  chat = model.start_chat(history=formatted_history)
 
117
 
118
  return "⚠️ System Busy. Please try again."
119
 
120
+ # --- UI TEMPLATE (UPDATED) ---
121
  HTML_TEMPLATE = """
122
  <!DOCTYPE html>
123
  <html lang="en">
 
145
  :root {
146
  --bg-color: #09090b; --sidebar-bg: #000000; --card-bg: #18181b;
147
  --user-msg-bg: #27272a; --text-color: #e4e4e7; --code-bg: #0f0f11;
148
+ --border-color: #27272a; --dim-text: #71717a;
149
  }
150
  * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
151
  body, html { margin: 0; padding: 0; height: 100%; width: 100%; background: var(--bg-color); color: var(--text-color); font-family: 'Outfit', sans-serif; overflow: hidden; }
 
155
  /* HEADER */
156
  header {
157
  height: 65px; padding: 0 20px;
158
+ 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
  }
 
172
  .overlay.active { opacity: 1; pointer-events: auto; }
173
 
174
  .search-box { background: var(--card-bg); border: 1px solid var(--border-color); padding: 12px; border-radius: 10px; color: #fff; width: 100%; margin-bottom: 15px; outline: none; }
175
+
176
  #history-list { flex: 1; overflow-y: auto; }
177
+ .history-item {
178
+ display: flex; justify-content: space-between; align-items: center;
179
+ padding: 12px; border-radius: 8px; cursor: pointer; color: #a1a1aa; font-size: 14px; margin-bottom: 5px;
180
+ }
181
  .history-item:hover { background: var(--user-msg-bg); color: #fff; }
182
+ .h-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 140px; }
183
+ .h-actions { display: flex; gap: 8px; opacity: 0; transition: 0.2s; }
184
+ .history-item:hover .h-actions { opacity: 1; }
185
+ .h-icon { font-size: 12px; color: #71717a; }
186
+ .h-icon:hover { color: #fff; }
187
+
188
+ /* BRANDING */
189
+ .brand-section { text-align: center; margin-top: auto; padding-top: 15px; border-top: 1px solid #222; }
190
+ .brand-name { font-family: 'Outfit', sans-serif; font-weight: 600; font-size: 13px; color: #52525b; text-transform: uppercase; letter-spacing: 2px; margin-bottom: 10px; opacity: 0.8; }
191
+ .logout-btn { color: #ef4444; cursor: pointer; font-size: 14px; font-weight: 500; }
192
+
193
+ /* CHAT AREA */
194
  #chat-box {
195
  flex: 1; overflow-y: auto; padding: 20px 5%;
196
  display: flex; flex-direction: column; gap: 20px;
197
+ -webkit-overflow-scrolling: touch; overscroll-behavior-y: contain;
 
 
198
  }
199
 
200
+ .msg { width: 100%; line-height: 1.6; font-size: 16px; opacity: 0; animation: fadeInstant 0.3s forwards; }
201
+ @keyframes fadeInstant { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
202
+
203
+ .user-msg { text-align: right; }
204
+ /* Use a span/div for content to easily select for copy */
205
+ .user-content { display: inline-block; background: var(--user-msg-bg); padding: 10px 18px; border-radius: 18px 18px 4px 18px; text-align: left; max-width: 85%; }
206
 
207
  .ai-msg { text-align: left; }
208
  .ai-content strong { color: #fff; font-weight: 700; }
 
230
  }
231
  textarea { flex: 1; background: transparent; border: none; color: #fff; font-size: 16px; max-height: 120px; padding: 10px 5px; resize: none; outline: none; font-family: 'Outfit', sans-serif; }
232
 
233
+ .icon-btn { width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: none; background: transparent; color: #a1a1aa; cursor: pointer; font-size: 16px; }
 
 
 
234
  .icon-btn:hover { background: #333; color: #fff; }
235
+ .send-btn { background: #fff; color: #000; width: 36px; height: 36px; border-radius: 50%; border: none; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 16px; }
 
 
 
 
236
 
237
+ /* PREVIEW AREA (Beautiful) */
238
+ #preview-area {
239
+ max-width: 900px; margin: 0 auto 10px auto; display: none;
240
+ background: #111; padding: 10px; border-radius: 12px; border: 1px solid #333;
241
+ }
242
+ .preview-item { display: flex; align-items: center; gap: 10px; }
243
+ .preview-thumb { width: 40px; height: 40px; border-radius: 6px; object-fit: cover; border: 1px solid #444; }
244
+ .preview-file-icon { width: 40px; height: 40px; border-radius: 6px; background: #222; color: #fff; display: flex; align-items: center; justify-content: center; border: 1px solid #444; }
245
+ .preview-name { font-size: 13px; color: #ccc; flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
246
+ .remove-preview { cursor: pointer; color: #ef4444; padding: 5px; }
247
 
248
  /* LOGIN */
249
  #login-overlay { position: fixed; inset: 0; background: #000; z-index: 2000; display: flex; align-items: center; justify-content: center; }
250
  .login-box { width: 90%; max-width: 350px; text-align: center; padding: 30px; border: 1px solid var(--border-color); border-radius: 20px; background: #0a0a0a; }
251
 
 
252
  </style>
253
  </head>
254
  <body>
 
271
  </div>
272
  <button onclick="newChat()" style="width:100%; padding:10px; background:#fff; border:none; border-radius:8px; cursor:pointer; font-weight:700; margin-bottom:15px;">+ New Chat</button>
273
  <input type="text" class="search-box" placeholder="Search..." onkeyup="filterHistory(this.value)">
274
+
275
  <div id="history-list"></div>
276
+
277
+ <div class="brand-section">
278
+ <div class="brand-name">Designed by Shirpi</div>
279
+ <div class="logout-btn" onclick="handleLogout()">Log Out</div>
280
+ </div>
281
  </div>
282
 
283
  <header>
 
290
  <div id="chat-box"></div>
291
 
292
  <div class="input-wrapper">
293
+ <div id="preview-area">
294
+ <div class="preview-item">
295
+ <div id="preview-visual"></div> <span id="preview-text" class="preview-name">filename.jpg</span>
296
+ <i class="fas fa-times remove-preview" onclick="clearAttachment()"></i>
297
  </div>
298
  </div>
299
 
300
  <div class="input-container">
301
+ <button class="icon-btn" onclick="document.getElementById('file-input').click()">
302
  <i class="fas fa-paperclip"></i>
303
  </button>
304
+ <input type="file" id="file-input" accept="image/*,.txt,.py,.js,.html,.css,.md,.csv,.json" hidden onchange="handleFileSelect(this)">
305
 
306
+ <button class="icon-btn" onclick="document.getElementById('camera-input').click()">
307
  <i class="fas fa-camera"></i>
308
  </button>
309
+ <input type="file" id="camera-input" accept="image/*" capture="environment" hidden onchange="handleFileSelect(this)">
310
 
311
  <textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
312
 
 
320
  <script>
321
  let currentUser = null;
322
  let currentChatId = null;
323
+ let currentAttachment = { type: null, data: null, name: null };
324
 
325
  function checkLogin() {
326
  const stored = localStorage.getItem("student_ai_user");
 
345
  el.style.height = Math.min(el.scrollHeight, 150) + 'px';
346
  }
347
 
348
+ // --- FILE & CAMERA HANDLING ---
349
+ function handleFileSelect(input) {
350
  if (input.files && input.files[0]) {
351
+ const file = input.files[0];
352
  const reader = new FileReader();
353
+
354
  reader.onload = function(e) {
355
+ const result = e.target.result;
356
+ const isImage = file.type.startsWith('image/');
357
+
358
+ currentAttachment = {
359
+ type: isImage ? 'image' : 'file',
360
+ data: isImage ? result : atob(result.split(',')[1]), // Decode text files
361
+ name: file.name
362
+ };
363
+
364
+ // Show Preview
365
+ const previewArea = document.getElementById('preview-area');
366
+ const visual = document.getElementById('preview-visual');
367
+ const name = document.getElementById('preview-text');
368
+
369
+ previewArea.style.display = 'block';
370
+ name.innerText = file.name;
371
+
372
+ if (isImage) {
373
+ visual.innerHTML = `<img src="${result}" class="preview-thumb">`;
374
+ } else {
375
+ visual.innerHTML = `<div class="preview-file-icon"><i class="fas fa-file-alt"></i></div>`;
376
+ }
377
+ }
378
+
379
+ if (file.type.startsWith('image/')) {
380
+ reader.readAsDataURL(file);
381
+ } else {
382
+ reader.readAsDataURL(file); // Read as Base64 to keep logic consistent
383
  }
 
384
  }
385
  }
386
+
387
+ function clearAttachment() {
388
+ currentAttachment = { type: null, data: null, name: null };
389
+ document.getElementById('file-input').value = "";
390
+ document.getElementById('camera-input').value = "";
391
+ document.getElementById('preview-area').style.display = 'none';
392
  }
393
 
 
394
  function scrollToBottom() {
395
  const box = document.getElementById('chat-box');
396
  box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });
 
399
  async function send() {
400
  const input = document.getElementById('input');
401
  const text = input.value.trim();
402
+ if (!text && !currentAttachment.data) return;
403
 
404
  const chatBox = document.getElementById('chat-box');
405
 
406
+ // Render User Message
407
+ let attachHtml = '';
408
+ if (currentAttachment.type === 'image') {
409
+ attachHtml = `<br><img src="${currentAttachment.data}" style="max-height:100px; margin-top:5px; border-radius:5px;">`;
410
+ } else if (currentAttachment.type === 'file') {
411
+ attachHtml = `<br><div style="font-size:12px; color:#aaa; margin-top:5px;"><i class="fas fa-file"></i> ${currentAttachment.name}</div>`;
412
+ }
413
+
414
+ const userHtml= `
415
  <div class="msg user-msg">
416
+ <div class="user-content">${text.replace(/</g, "&lt;")}${attachHtml}</div>
 
 
417
  <div class="msg-actions">
418
+ <span class="action-btn" onclick="copyText('${text}')"><i class="fas fa-copy"></i></span>
419
+ <span class="action-btn" onclick="editMessage('${text}')"><i class="fas fa-pen"></i></span>
420
  </div>
421
  </div>`;
422
 
423
  chatBox.insertAdjacentHTML('beforeend', userHtml);
424
 
425
+ // Prepare Data
426
+ const payload = {
427
+ message: text,
428
+ username: currentUser,
429
+ chat_id: currentChatId,
430
+ image: currentAttachment.type === 'image' ? currentAttachment.data : null,
431
+ file_text: currentAttachment.type === 'file' ? currentAttachment.data : null
432
+ };
433
+
434
+ // Reset UI
435
  input.value = ''; input.style.height = 'auto';
436
+ clearAttachment();
437
  scrollToBottom();
438
 
439
+ // AI Spinner
440
  const msgId = "ai-" + Date.now();
441
  chatBox.insertAdjacentHTML('beforeend', `<div id="${msgId}" class="msg ai-msg"><i class="fas fa-circle-notch fa-spin"></i></div>`);
442
  scrollToBottom();
 
445
  if (!currentChatId) {
446
  const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
447
  const d = await r.json(); currentChatId = d.chat_id;
448
+ payload.chat_id = d.chat_id;
449
  loadHistory();
450
  }
451
 
452
  const res = await fetch('/chat', {
453
  method: 'POST', headers: {'Content-Type': 'application/json'},
454
+ body: JSON.stringify(payload)
 
 
 
 
 
455
  });
456
  const data = await res.json();
457
 
 
462
  contentDiv.className = 'ai-content';
463
  aiDiv.appendChild(contentDiv);
464
 
 
465
  await typeWriter(contentDiv, data.response);
466
 
467
+ // Add Share/Copy/Regen
468
  aiDiv.insertAdjacentHTML('beforeend', `
469
  <div class="msg-actions">
470
+ <span class="action-btn" onclick="copyAiResponse(this)"><i class="fas fa-copy"></i> Copy</span>
471
+ <span class="action-btn" onclick="shareResponse(this)"><i class="fas fa-share-alt"></i> Share</span>
472
+ <span class="action-btn" onclick="regenerate('${text}')"><i class="fas fa-redo"></i> Regen</span>
473
  </div>`);
474
 
475
  scrollToBottom();
 
480
  }
481
  }
482
 
483
+ // --- HELPERS ---
484
+ function copyText(text) { navigator.clipboard.writeText(text); }
485
+
486
+ function copyAiResponse(btn) {
487
+ const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
488
+ navigator.clipboard.writeText(text);
489
+ }
 
 
 
 
 
 
 
490
 
491
+ function shareResponse(btn) {
492
+ const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
493
+ if (navigator.share) {
494
+ navigator.share({ title: 'Student AI Answer', text: text });
495
+ } else {
496
+ navigator.clipboard.writeText(text);
497
+ alert("Text copied to clipboard for sharing!");
498
+ }
 
 
 
 
 
 
499
  }
500
 
501
  function editMessage(oldText) {
 
507
  send();
508
  }
509
 
510
+ // --- HISTORY MANAGEMENT ---
511
+ async function renameChat(cid, oldTitle) {
512
+ const newTitle = prompt("Rename chat:", oldTitle);
513
+ if(newTitle && newTitle !== oldTitle) {
514
+ await fetch('/rename_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid, title:newTitle})});
515
+ loadHistory();
516
+ }
517
+ event.stopPropagation();
518
+ }
519
+
520
+ async function deleteChat(cid) {
521
+ if(confirm("Delete this chat?")) {
522
+ await fetch('/delete_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid})});
523
+ if(currentChatId === cid) newChat();
524
+ loadHistory();
525
+ }
526
+ event.stopPropagation();
527
+ }
528
+
529
+ function shareChat(title) {
530
+ // Simple share for now (sharing links in local app is tricky, so we share title/intent)
531
+ alert("Share feature ready! You can copy the chat content manually for now.");
532
+ event.stopPropagation();
533
  }
534
 
535
  async function loadHistory() {
 
540
  if (data.chats) {
541
  Object.keys(data.chats).reverse().forEach(cid => {
542
  const title = data.chats[cid].title || "New Chat";
543
+ list.innerHTML += `
544
+ <div class="history-item" onclick="loadChat('${cid}')">
545
+ <span class="h-title">${title}</span>
546
+ <div class="h-actions">
547
+ <i class="fas fa-edit h-icon" onclick="renameChat('${cid}', '${title}')" title="Rename"></i>
548
+ <i class="fas fa-trash h-icon" onclick="deleteChat('${cid}')" title="Delete"></i>
549
+ </div>
550
+ </div>`;
551
  });
552
  }
553
  } catch(e) {}
554
  }
555
+
556
+ // --- ANIMATION ---
557
+ async function typeWriter(element, markdownText) {
558
+ element.innerHTML = marked.parse(markdownText);
559
+ if (window.MathJax) await MathJax.typesetPromise([element]);
560
+ if (window.mermaid) {
561
+ const m = element.querySelectorAll('code.language-mermaid');
562
+ m.forEach(c => {
563
+ const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d);
564
+ });
565
+ window.mermaid.init(undefined, element.querySelectorAll('.mermaid'));
566
+ }
567
+ // Simple fade in for smoothness
568
+ element.style.opacity = 0;
569
+ element.style.transition = 'opacity 0.5s';
570
+ setTimeout(() => element.style.opacity = 1, 50);
571
+ }
572
+
573
+ // --- SIDEBAR ---
574
+ function toggleSidebar() {
575
+ document.getElementById('sidebar').classList.toggle('open');
576
+ document.getElementById('overlay').classList.toggle('active');
577
+ }
578
  function filterHistory(q) {
579
  const items = document.querySelectorAll('.history-item');
580
+ items.forEach(i => i.style.display = i.innerText.toLowerCase().includes(q.toLowerCase()) ? 'flex' : 'none');
581
  }
 
582
  async function newChat() {
583
  currentChatId = null;
584
  document.getElementById('chat-box').innerHTML = "";
 
588
  document.getElementById('sidebar').classList.remove('open');
589
  document.getElementById('overlay').classList.remove('active');
590
  }
 
591
  async function loadChat(cid) {
592
  currentChatId = cid;
593
  const res = await fetch('/get_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid})});
594
  const data = await res.json();
595
  const box = document.getElementById('chat-box'); box.innerHTML = "";
 
596
  data.messages.forEach(msg => {
597
  const isUser = msg.role === 'user';
598
  let content = msg.content;
599
  if(isUser) {
600
+ // Check if content has attachment tag (simple check)
601
+ box.insertAdjacentHTML('beforeend', `<div class="msg user-msg"><div class="user-content">${content.replace(/</g, "&lt;")}</div></div>`);
602
  } else {
603
+ const div = document.createElement('div'); div.className = 'msg ai-msg';
 
604
  div.innerHTML = `<div class="ai-content">${marked.parse(content)}</div>`;
605
  box.appendChild(div);
606
  if(window.MathJax) MathJax.typesetPromise([div]);
607
  if(window.mermaid) {
608
  const m = div.querySelectorAll('code.language-mermaid');
609
+ m.forEach(c => { const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d); });
 
 
610
  window.mermaid.init(undefined, div.querySelectorAll('.mermaid'));
611
  }
612
+ // Add actions to history items too
613
+ div.insertAdjacentHTML('beforeend', `
614
+ <div class="msg-actions">
615
+ <span class="action-btn" onclick="copyAiResponse(this)"><i class="fas fa-copy"></i> Copy</span>
616
+ </div>`);
617
  }
618
  });
619
  document.getElementById('sidebar').classList.remove('open');
 
640
  save_db(user_db)
641
  return jsonify({"chat_id": nid})
642
 
643
+ @app.route("/rename_chat", methods=["POST"])
644
+ def rename_chat():
645
+ d = request.json
646
+ u, cid, t = d.get("username"), d.get("chat_id"), d.get("title")
647
+ if u in user_db and cid in user_db[u]:
648
+ user_db[u][cid]["title"] = t
649
+ save_db(user_db)
650
+ return jsonify({"status":"ok"})
651
+
652
+ @app.route("/delete_chat", methods=["POST"])
653
+ def delete_chat():
654
+ d = request.json
655
+ u, cid = d.get("username"), d.get("chat_id")
656
+ if u in user_db and cid in user_db[u]:
657
+ del user_db[u][cid]
658
+ save_db(user_db)
659
+ return jsonify({"status":"ok"})
660
+
661
  @app.route("/get_history", methods=["POST"])
662
  def get_history():
663
  u = request.json.get("username")
 
673
  d = request.json
674
  u, cid, msg = d.get("username"), d.get("chat_id"), d.get("message")
675
  img_data = d.get("image")
676
+ file_text = d.get("file_text")
677
 
678
  if u not in user_db: user_db[u] = {}
679
  if cid not in user_db[u]: user_db[u][cid] = {"messages": []}
680
 
681
  user_db[u][cid]["messages"].append({"role": "user", "content": msg})
682
+ reply = generate_with_retry(msg, img_data, file_text, user_db[u][cid]["messages"][:-1])
683
  user_db[u][cid]["messages"].append({"role": "model", "content": reply})
684
 
685
  new_title = False
 
692
 
693
  if __name__ == '__main__':
694
  app.run(host='0.0.0.0', port=7860)