Shirpi commited on
Commit
4687026
·
verified ·
1 Parent(s): 65c49d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +483 -89
app.py CHANGED
@@ -9,11 +9,16 @@ from PIL import Image
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,6 +35,7 @@ user_db = load_db()
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,6 +46,7 @@ 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,12 +87,15 @@ def generate_with_retry(prompt, image_data=None, file_text=None, history_message
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,21 +105,25 @@ def generate_with_retry(prompt, image_data=None, file_text=None, history_message
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,80 +134,173 @@ HTML_TEMPLATE = """
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
 
153
- /* INTRO CONTAINER FIX */
154
  #intro-container {
155
- height: 100%;
156
- width: 100%;
157
- display: flex;
158
- flex-direction: column;
159
- justify-content: center;
160
- align-items: center;
161
  text-align: center;
 
 
162
  }
163
 
164
  .msg { width: 100%; line-height: 1.7; font-size: 17px; opacity: 0; animation: fadeInstant 0.3s forwards; display: flex; flex-direction: column; }
165
  @keyframes fadeInstant { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
 
166
  .user-msg { align-items: flex-end; }
167
  .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; }
 
168
  .ai-msg { align-items: flex-start; }
169
  .ai-content { width: 100%; color: #d4d4d8; word-wrap: break-word; }
170
- .ai-content strong { color: #fff; }
171
- .ai-content h1, .ai-content h2 { margin-top: 20px; color: #fff; }
172
- .msg-actions { margin-top: 10px; opacity: 0; transition: opacity 0.2s; display: flex; gap: 20px; }
 
 
 
 
 
 
 
 
 
173
  .msg:hover .msg-actions { opacity: 1; }
174
- .action-icon { cursor: pointer; color: var(--dim); font-size: 18px; }
 
175
 
176
  .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)); }
177
  .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; }
178
  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; }
179
- .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; }
180
- .icon-btn { background: transparent; color: #a1a1aa; }
181
- .send-btn { background: #fff; color: #000; }
182
  #preview-area { position: absolute; bottom: 85px; left: 20px; display: none; z-index: 70; }
183
- .preview-box { width: 60px; height: 60px; border-radius: 12px; border: 2px solid #fff; background: #222; overflow: hidden; position: relative; }
184
  .preview-img { width: 100%; height: 100%; object-fit: cover; }
185
- .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; }
186
 
187
- /* KEYBOARD STABLE LOGIN */
188
- #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; }
 
 
 
 
 
 
189
  #login-overlay.hidden { opacity: 0; pointer-events: none; }
190
- .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; }
 
 
 
 
 
 
191
  #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; }
192
- #image-modal img { max-width: 95%; max-height: 90%; border-radius: 8px; }
193
  #image-modal.active { opacity: 1; }
194
  </style>
195
  </head>
196
  <body>
 
197
  <div id="login-overlay">
198
  <div class="login-box">
199
  <h1 class="app-title" style="margin-bottom:10px;">Student's AI</h1>
@@ -201,7 +308,11 @@ HTML_TEMPLATE = """
201
  <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>
202
  </div>
203
  </div>
204
- <div id="image-modal" onclick="closeImagePreview()"><img id="modal-img" src=""></div>
 
 
 
 
205
  <div id="sidebar">
206
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-shrink:0;">
207
  <div class="user-info"><span id="display-name">User</span></div>
@@ -215,89 +326,360 @@ HTML_TEMPLATE = """
215
  <div class="logout-btn" onclick="handleLogout()">Log Out</div>
216
  </div>
217
  </div>
 
218
  <div id="app-container">
219
  <header>
220
  <div class="menu-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
221
  <span class="app-title">Student's AI</span>
222
  <div style="width:40px;"></div>
223
  </header>
 
224
  <div id="chat-box"></div>
 
225
  <div class="input-wrapper">
226
  <div id="preview-area">
227
  <div class="preview-box"><div id="preview-visual"></div></div>
228
  <button class="remove-preview" onclick="clearAttachment()">×</button>
229
  </div>
 
230
  <div class="input-container">
231
  <button class="icon-btn" onclick="document.getElementById('file-input').click()"><i class="fas fa-paperclip"></i></button>
232
  <input type="file" id="file-input" accept="image/*,.txt,.py,.js,.html,.css,.md,.csv,.json" hidden onchange="handleFileSelect(this)">
 
233
  <button class="icon-btn" onclick="document.getElementById('camera-input').click()"><i class="fas fa-camera"></i></button>
234
  <input type="file" id="camera-input" accept="image/*" capture="environment" hidden onchange="handleFileSelect(this)">
 
235
  <textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
 
236
  <button class="send-btn" onclick="send()"><i class="fas fa-arrow-up"></i></button>
237
  </div>
238
  </div>
239
  </div>
 
240
  <script>
241
- let currentUser = null; let currentChatId = null; let currentAttachment = { type: null, data: null, name: null }; let longPressTimer;
 
 
 
242
 
243
- // FIXED INTRO HTML: CENTERED CONTAINER
244
- function getIntroHtml(name) {
245
- return `<div id="intro-container"><div class="msg ai-msg"><div class="ai-content"><h1>Hi ${name},</h1><p>Ready to master your studies today?</p></div></div></div>`;
 
 
 
 
 
 
 
 
 
 
 
 
246
  }
247
 
248
- function checkLogin() { try { const stored = localStorage.getItem("student_ai_user"); if (stored) { currentUser = stored; document.getElementById("login-overlay").classList.add('hidden'); showApp(); } } catch(e) {} }
249
- 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); } }
250
- 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); }
251
- 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); } } }
252
- function resizeInput(el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 150) + 'px'; }
253
- 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 = ""; }
254
- function clearAttachment() { currentAttachment = { type: null, data: null, name: null }; document.getElementById('preview-area').style.display = 'none'; }
255
- function scrollToBottom() { const box = document.getElementById('chat-box'); setTimeout(() => { box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' }); }, 100); }
 
 
 
 
 
256
 
257
- async function send() {
258
- const input = document.getElementById('input'); const text = input.value.trim();
259
- if (!text && !currentAttachment.data) return;
260
-
261
- // REMOVE INTRO IF EXISTS
262
- const intro = document.getElementById('intro-container');
263
- if(intro) intro.remove();
264
-
265
- const chatBox = document.getElementById('chat-box');
266
- 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>`;
267
- 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>`;
268
- chatBox.insertAdjacentHTML('beforeend', userHtml);
269
- const promptText = text; const imgData = currentAttachment.type === 'image' ? currentAttachment.data : null; const fileText = currentAttachment.type === 'file' ? currentAttachment.data : null;
270
- input.value = ''; input.style.height = 'auto'; clearAttachment(); scrollToBottom();
271
- 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();
272
- try {
273
- 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(); }
274
- 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 }) });
275
- 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();
276
- } catch (e) { document.getElementById(msgId).innerHTML = "⚠️ Error: " + e.message; }
277
  }
278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  function copyText(text) { navigator.clipboard.writeText(text); }
280
- function copyAiResponse(btn) { const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText; navigator.clipboard.writeText(text); }
281
- 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); }
 
 
 
 
 
 
 
282
  function editMessage(oldText) { document.getElementById('input').value = oldText; document.getElementById('input').focus(); }
283
  function regenerate(text) { document.getElementById('input').value = text; send(); }
284
- 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); } });
285
- function closeImagePreview() { const modal = document.getElementById('image-modal'); modal.classList.remove('active'); setTimeout(() => modal.style.display = 'none', 300); }
286
- function handleHistoryTouchStart(e, cid) { longPressTimer = setTimeout(() => { e.target.closest('.history-item').classList.add('active-mode'); }, 600); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  function handleHistoryTouchEnd(e) { clearTimeout(longPressTimer); }
288
- 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(); }
289
- 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(); }
290
- 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) {} }
291
- 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); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }
293
- 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'); }
294
- 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; }
295
- checkLogin();
296
- </script>
297
- </body>
298
- </html>
299
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
 
301
  @app.route("/", methods=["GET"])
302
  def home(): return render_template_string(HTML_TEMPLATE)
303
 
@@ -344,15 +726,19 @@ def chat():
344
  u, cid, msg = d.get("username"), d.get("chat_id"), d.get("message")
345
  img_data = d.get("image")
346
  file_text = d.get("file_text")
 
347
  if u not in user_db: user_db[u] = {}
348
  if cid not in user_db[u]: user_db[u][cid] = {"messages": []}
 
349
  user_db[u][cid]["messages"].append({"role": "user", "content": msg})
350
  reply = generate_with_retry(msg, img_data, file_text, user_db[u][cid]["messages"][:-1])
351
  user_db[u][cid]["messages"].append({"role": "model", "content": reply})
 
352
  new_title = False
353
  if len(user_db[u][cid]["messages"]) <= 2:
354
  user_db[u][cid]["title"] = " ".join(msg.split()[:4])
355
  new_title = True
 
356
  save_db(user_db)
357
  return jsonify({"response": reply, "new_title": new_title})
358
 
@@ -360,15 +746,23 @@ def chat():
360
  def manifest():
361
  data = {
362
  "name": "Student's AI",
363
- "short_name": "StudentAI",
364
  "start_url": "/",
365
  "display": "standalone",
366
  "orientation": "portrait",
367
  "background_color": "#09090b",
368
  "theme_color": "#09090b",
369
  "icons": [
370
- {"src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png", "sizes": "192x192", "type": "image/png"},
371
- {"src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png", "sizes": "512x512", "type": "image/png"}
 
 
 
 
 
 
 
 
372
  ]
373
  }
374
  return Response(json.dumps(data), mimetype='application/json')
 
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
  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
  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
  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
  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 of HTML String) ---
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
  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 (Pushed down for Header) --- */
156
+ #app-container {
157
+ display: flex; flex-direction: column;
158
+ height: 100dvh; width: 100%;
159
+ position: relative; overflow-x: hidden;
160
+ padding-top: 70px; /* Space for fixed header */
161
+ }
162
+
163
+ /* --- HEADER LOCKED --- */
164
+ header {
165
+ height: 70px; padding: 0 20px; background: rgba(9,9,11, 0.98);
166
+ border-bottom: 1px solid var(--border-color);
167
+ display: flex; align-items: center; justify-content: space-between;
168
+ z-index: 50;
169
+ padding-top: env(safe-area-inset-top);
170
+ position: absolute; top: 0; left: 0; right: 0;
171
+ }
172
+ .menu-btn {
173
+ width: 40px; height: 40px; border-radius: 50%; border: 1px solid #333;
174
+ display: flex; align-items: center; justify-content: center; cursor: pointer;
175
+ transition: 0.2s; color: #fff;
176
+ }
177
+ .menu-btn:active { transform: scale(0.95); background: #222; }
178
+ .app-title { font-size: 24px; font-weight: 800; letter-spacing: -0.5px; color: #fff; }
179
+
180
+ /* --- SIDEBAR ANIMATION --- */
181
+ #sidebar {
182
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
183
+ background: var(--bg); z-index: 100;
184
+ display: flex; flex-direction: column; padding: 25px;
185
+ padding-top: calc(70px + env(safe-area-inset-top));
186
+ transform: translateY(-100%);
187
+ transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1);
188
+ overflow-y: auto;
189
+ }
190
  #sidebar.open { transform: translateY(0); }
 
191
 
192
+ @media (min-width: 768px) {
193
+ #sidebar { width: 350px; border-right: 1px solid var(--border); }
194
+ .input-container { max-width: 800px; }
195
+ #chat-box { padding: 20px 15%; }
196
+ }
197
+
198
  .user-info { margin-bottom: 30px; font-size: 20px; font-weight: 700; color: #fff; display: flex; align-items: center; gap: 15px; flex-shrink: 0; }
199
+ .new-chat-btn {
200
+ width: 100%; padding: 15px; background: #fff; color: #000; border: none;
201
+ border-radius: 12px; font-weight: 700; font-size: 16px; cursor: pointer; margin-bottom: 25px; flex-shrink: 0;
202
+ }
203
+
204
+ .history-label { color: var(--dim); font-size: 13px; font-weight: 600; margin-bottom: 10px; letter-spacing: 1px; text-transform: uppercase; flex-shrink: 0; }
205
  #history-list { flex: 1; overflow-y: auto; padding: 10px 0; min-height: 100px; }
206
+
207
+ .history-item {
208
+ display: flex; justify-content: space-between; align-items: center;
209
+ padding: 15px; margin-bottom: 12px; background: var(--card); border: 1px solid var(--border); border-radius: 12px;
210
+ cursor: pointer; color: #a1a1aa; font-size: 15px; transition: 0.2s;
211
+ }
212
+ .history-item:active { background: #222; color: #fff; border-color: #444; }
213
  .h-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; flex: 1; margin-right: 10px; }
214
  .h-actions { display: none; gap: 15px; }
215
  .history-item.active-mode .h-actions { display: flex; }
216
+ .h-icon { font-size: 16px; color: #fff; padding: 5px; }
217
+
218
+ .rename-input {
219
+ background: transparent; border: none; border-bottom: 1px solid #fff;
220
+ color: #fff; font-family: 'Outfit', sans-serif; font-size: 15px;
221
+ width: 100%; outline: none; padding: 0;
222
+ }
223
+
224
  .brand-section { text-align: center; margin-top: 20px; padding-bottom: env(safe-area-inset-bottom); flex-shrink: 0; }
225
+ .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; }
226
  .logout-btn { color: #ef4444; cursor: pointer; font-size: 15px; font-weight: 600; padding: 10px; }
227
 
228
+ #chat-box {
229
+ flex: 1; overflow-y: auto; padding: 20px 5%; padding-bottom: 80px;
230
+ display: flex; flex-direction: column; gap: 25px;
231
+ -webkit-overflow-scrolling: touch; overscroll-behavior-y: contain; min-height: 0;
232
+ }
233
 
234
+ /* --- LOCKED INTRO CONTAINER --- */
235
  #intro-container {
236
+ position: absolute;
237
+ top: 140px; /* Fixed distance from top */
238
+ left: 50%;
239
+ transform: translateX(-50%);
240
+ width: 90%; max-width: 600px;
 
241
  text-align: center;
242
+ z-index: 10;
243
+ pointer-events: none;
244
  }
245
 
246
  .msg { width: 100%; line-height: 1.7; font-size: 17px; opacity: 0; animation: fadeInstant 0.3s forwards; display: flex; flex-direction: column; }
247
  @keyframes fadeInstant { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
248
+
249
  .user-msg { align-items: flex-end; }
250
  .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; }
251
+
252
  .ai-msg { align-items: flex-start; }
253
  .ai-content { width: 100%; color: #d4d4d8; word-wrap: break-word; }
254
+ .ai-content strong { color: #fff; font-weight: 700; }
255
+ .ai-content h1, .ai-content h2 { margin-top: 20px; color: #fff; font-weight: 700; }
256
+ .ai-content img, .user-content img { cursor: pointer; transition: 0.2s; }
257
+ .ai-content img:active, .user-content img:active { transform: scale(0.98); }
258
+
259
+ pre { background: #1e1e1e !important; border-radius: 12px; padding: 15px; overflow-x: auto; margin: 15px 0; border: 1px solid #333; max-width: 100%; }
260
+ code { font-family: 'JetBrains Mono', monospace; font-size: 14px; }
261
+ .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%; }
262
+ .mermaid { background: #111; padding: 15px; border-radius: 10px; text-align: center; margin: 15px 0; overflow-x: auto; }
263
+
264
+ .msg-actions { margin-top: 10px; opacity: 0; transition: opacity 0.2s; display: flex; gap: 20px; align-items: center; }
265
+ .user-msg .msg-actions { justify-content: flex-end; }
266
  .msg:hover .msg-actions { opacity: 1; }
267
+ .action-icon { cursor: pointer; color: var(--dim); font-size: 18px; transition: 0.2s; }
268
+ .action-icon:hover { color: #fff; transform: scale(1.1); }
269
 
270
  .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)); }
271
  .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; }
272
  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; }
273
+ .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; }
274
+ .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; }
275
+
276
  #preview-area { position: absolute; bottom: 85px; left: 20px; display: none; z-index: 70; }
277
+ .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); }
278
  .preview-img { width: 100%; height: 100%; object-fit: cover; }
279
+ .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; }
280
 
281
+ /* --- LOGIN PAGE STABILITY --- */
282
+ #login-overlay {
283
+ position: fixed; inset: 0; background: #000; z-index: 2000;
284
+ display: flex;
285
+ align-items: flex-start; justify-content: center;
286
+ padding-top: 25vh;
287
+ transition: opacity 0.8s ease; opacity: 1; pointer-events: auto;
288
+ }
289
  #login-overlay.hidden { opacity: 0; pointer-events: none; }
290
+
291
+ .login-box {
292
+ width: 90%; max-width: 350px; text-align: center;
293
+ padding: 40px; border: 1px solid var(--border); border-radius: 20px; background: #0a0a0a;
294
+ margin: 0 auto;
295
+ }
296
+
297
  #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; }
298
+ #image-modal img { max-width: 95%; max-height: 90%; border-radius: 8px; box-shadow: 0 0 20px rgba(0,0,0,0.8); }
299
  #image-modal.active { opacity: 1; }
300
  </style>
301
  </head>
302
  <body>
303
+
304
  <div id="login-overlay">
305
  <div class="login-box">
306
  <h1 class="app-title" style="margin-bottom:10px;">Student's AI</h1>
 
308
  <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>
309
  </div>
310
  </div>
311
+
312
+ <div id="image-modal" onclick="closeImagePreview()">
313
+ <img id="modal-img" src="" alt="Preview">
314
+ </div>
315
+
316
  <div id="sidebar">
317
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-shrink:0;">
318
  <div class="user-info"><span id="display-name">User</span></div>
 
326
  <div class="logout-btn" onclick="handleLogout()">Log Out</div>
327
  </div>
328
  </div>
329
+
330
  <div id="app-container">
331
  <header>
332
  <div class="menu-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
333
  <span class="app-title">Student's AI</span>
334
  <div style="width:40px;"></div>
335
  </header>
336
+
337
  <div id="chat-box"></div>
338
+
339
  <div class="input-wrapper">
340
  <div id="preview-area">
341
  <div class="preview-box"><div id="preview-visual"></div></div>
342
  <button class="remove-preview" onclick="clearAttachment()">×</button>
343
  </div>
344
+
345
  <div class="input-container">
346
  <button class="icon-btn" onclick="document.getElementById('file-input').click()"><i class="fas fa-paperclip"></i></button>
347
  <input type="file" id="file-input" accept="image/*,.txt,.py,.js,.html,.css,.md,.csv,.json" hidden onchange="handleFileSelect(this)">
348
+
349
  <button class="icon-btn" onclick="document.getElementById('camera-input').click()"><i class="fas fa-camera"></i></button>
350
  <input type="file" id="camera-input" accept="image/*" capture="environment" hidden onchange="handleFileSelect(this)">
351
+
352
  <textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
353
+
354
  <button class="send-btn" onclick="send()"><i class="fas fa-arrow-up"></i></button>
355
  </div>
356
  </div>
357
  </div>
358
+
359
  <script>
360
+ let currentUser = null;
361
+ let currentChatId = null;
362
+ let currentAttachment = { type: null, data: null, name: null };
363
+ let longPressTimer;
364
 
365
+ // --- FIXED INTRO: LOCKED CONTAINER ---
366
+ function getIntroHtml(name) {
367
+ return `<div id="intro-container"><div class="msg ai-msg"><div class="ai-content"><h1>Hi ${name},</h1><p>Ready to master your studies today?</p></div></div></div>`;
368
+ }
369
+
370
+ // --- AUTH LOGIC ---
371
+ function checkLogin() {
372
+ try {
373
+ const stored = localStorage.getItem("student_ai_user");
374
+ if (stored) {
375
+ currentUser = stored;
376
+ document.getElementById("login-overlay").classList.add('hidden');
377
+ showApp();
378
+ }
379
+ } catch(e) { console.log("Storage access denied"); }
380
  }
381
 
382
+ function handleLogin() {
383
+ const input = document.getElementById("username-input");
384
+ const name = input.value.trim();
385
+ if(name) {
386
+ try { localStorage.setItem("student_ai_user", name); } catch(e){}
387
+ currentUser = name;
388
+ document.getElementById("login-overlay").classList.add('hidden');
389
+ showApp();
390
+ } else {
391
+ input.style.border = "1px solid red";
392
+ setTimeout(() => input.style.border = "1px solid #333", 2000);
393
+ }
394
+ }
395
 
396
+ function handleLogout() {
397
+ try { localStorage.removeItem("student_ai_user"); } catch(e){}
398
+ const overlay = document.getElementById("login-overlay");
399
+ overlay.classList.remove('hidden');
400
+ document.getElementById('sidebar').classList.remove('open');
401
+ setTimeout(() => {
402
+ document.getElementById('chat-box').innerHTML = "";
403
+ currentChatId = null;
404
+ document.getElementById("username-input").value = "";
405
+ }, 500);
 
 
 
 
 
 
 
 
 
 
406
  }
407
 
408
+ function showApp() {
409
+ document.getElementById("display-name").innerText = "Hi " + currentUser;
410
+ loadHistory();
411
+ if(!currentChatId) {
412
+ const box = document.getElementById("chat-box");
413
+ if(box.innerHTML === "") {
414
+ box.innerHTML = getIntroHtml(currentUser);
415
+ }
416
+ }
417
+ }
418
+
419
+ function resizeInput(el) {
420
+ el.style.height = 'auto';
421
+ el.style.height = Math.min(el.scrollHeight, 150) + 'px';
422
+ }
423
+
424
+ function handleFileSelect(input) {
425
+ if (input.files && input.files[0]) {
426
+ const file = input.files[0];
427
+ const reader = new FileReader();
428
+ reader.onload = function(e) {
429
+ const result = e.target.result;
430
+ const isImage = file.type.startsWith('image/');
431
+ currentAttachment = { type: isImage ? 'image' : 'file', data: isImage ? result : atob(result.split(',')[1]), name: file.name };
432
+ const previewArea = document.getElementById('preview-area');
433
+ const visual = document.getElementById('preview-visual');
434
+ previewArea.style.display = 'block';
435
+ visual.innerHTML = isImage ? `<img src="${result}" class="preview-img">` : `<div class="preview-file-icon"><i class="fas fa-file-alt"></i></div>`;
436
+ }
437
+ reader.readAsDataURL(file);
438
+ }
439
+ input.value = "";
440
+ }
441
+
442
+ function clearAttachment() {
443
+ currentAttachment = { type: null, data: null, name: null };
444
+ document.getElementById('preview-area').style.display = 'none';
445
+ }
446
+
447
+ function scrollToBottom() {
448
+ const box = document.getElementById('chat-box');
449
+ setTimeout(() => {
450
+ box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });
451
+ }, 100);
452
+ }
453
+
454
+ async function send() {
455
+ const input = document.getElementById('input');
456
+ const text = input.value.trim();
457
+ if (!text && !currentAttachment.data) return;
458
+
459
+ // --- REMOVE INTRO TEXT IF IT EXISTS ---
460
+ const intro = document.getElementById('intro-container');
461
+ if(intro) { intro.style.display = 'none'; intro.remove(); }
462
+
463
+ const chatBox = document.getElementById('chat-box');
464
+ let attachHtml = '';
465
+ if (currentAttachment.type === 'image') attachHtml = `<br><img src="${currentAttachment.data}" style="max-height:100px; margin-top:10px; border-radius:8px;">`;
466
+ if (currentAttachment.type === 'file') attachHtml = `<br><small>📄 ${currentAttachment.name}</small>`;
467
+
468
+ const userHtml = `
469
+ <div class="msg user-msg">
470
+ <div class="user-content">${text.replace(/</g, "&lt;")}${attachHtml}</div>
471
+ <div class="msg-actions">
472
+ <i class="fas fa-copy action-icon" onclick="copyText('${text}')"></i>
473
+ <i class="fas fa-pen action-icon" onclick="editMessage('${text}')"></i>
474
+ </div>
475
+ </div>`;
476
+ chatBox.insertAdjacentHTML('beforeend', userHtml);
477
+
478
+ const promptText = text;
479
+ const imgData = currentAttachment.type === 'image' ? currentAttachment.data : null;
480
+ const fileText = currentAttachment.type === 'file' ? currentAttachment.data : null;
481
+
482
+ input.value = ''; input.style.height = 'auto';
483
+ clearAttachment();
484
+ scrollToBottom();
485
+
486
+ const msgId = "ai-" + Date.now();
487
+ chatBox.insertAdjacentHTML('beforeend', `<div id="${msgId}" class="msg ai-msg"><i class="fas fa-circle-notch fa-spin"></i></div>`);
488
+ scrollToBottom();
489
+
490
+ try {
491
+ if (!currentChatId) {
492
+ const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
493
+ const d = await r.json(); currentChatId = d.chat_id;
494
+ loadHistory();
495
+ }
496
+ const res = await fetch('/chat', {
497
+ method: 'POST', headers: {'Content-Type': 'application/json'},
498
+ body: JSON.stringify({ message: promptText, image: imgData, file_text: fileText, username: currentUser, chat_id: currentChatId })
499
+ });
500
+ const data = await res.json();
501
+
502
+ const aiDiv = document.getElementById(msgId);
503
+ aiDiv.innerHTML = "";
504
+ const contentDiv = document.createElement('div');
505
+ contentDiv.className = 'ai-content';
506
+ aiDiv.appendChild(contentDiv);
507
+
508
+ await typeWriter(contentDiv, data.response);
509
+
510
+ aiDiv.insertAdjacentHTML('beforeend', `
511
+ <div class="msg-actions">
512
+ <i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i>
513
+ <i class="fas fa-share-alt action-icon" onclick="shareResponse(this)"></i>
514
+ <i class="fas fa-redo action-icon" onclick="regenerate('${promptText}')"></i>
515
+ </div>`);
516
+
517
+ scrollToBottom();
518
+ if(data.new_title) loadHistory();
519
+ } catch (e) { document.getElementById(msgId).innerHTML = "⚠️ Error: " + e.message; }
520
+ }
521
+
522
  function copyText(text) { navigator.clipboard.writeText(text); }
523
+ function copyAiResponse(btn) {
524
+ const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
525
+ navigator.clipboard.writeText(text);
526
+ }
527
+ function shareResponse(btn) {
528
+ const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
529
+ if (navigator.share) navigator.share({ title: 'Student AI', text: text });
530
+ else navigator.clipboard.writeText(text);
531
+ }
532
  function editMessage(oldText) { document.getElementById('input').value = oldText; document.getElementById('input').focus(); }
533
  function regenerate(text) { document.getElementById('input').value = text; send(); }
534
+
535
+ document.getElementById('chat-box').addEventListener('click', function(e) {
536
+ if(e.target.tagName === 'IMG') {
537
+ const modal = document.getElementById('image-modal');
538
+ const modalImg = document.getElementById('modal-img');
539
+ modalImg.src = e.target.src;
540
+ modal.style.display = 'flex';
541
+ setTimeout(() => modal.classList.add('active'), 10);
542
+ }
543
+ });
544
+ function closeImagePreview() {
545
+ const modal = document.getElementById('image-modal');
546
+ modal.classList.remove('active');
547
+ setTimeout(() => modal.style.display = 'none', 300);
548
+ }
549
+
550
+ function handleHistoryTouchStart(e, cid) {
551
+ longPressTimer = setTimeout(() => {
552
+ e.target.closest('.history-item').classList.add('active-mode');
553
+ }, 600);
554
+ }
555
  function handleHistoryTouchEnd(e) { clearTimeout(longPressTimer); }
556
+
557
+ function startRename(cid) {
558
+ const item = document.getElementById('chat-' + cid);
559
+ const titleSpan = item.querySelector('.h-title');
560
+ const currentTitle = titleSpan.innerText;
561
+ const input = document.createElement('input');
562
+ input.type = 'text'; input.value = currentTitle; input.className = 'rename-input';
563
+
564
+ async function save() {
565
+ const newTitle = input.value.trim();
566
+ if(newTitle && newTitle !== currentTitle) {
567
+ await fetch('/rename_chat', {
568
+ method:'POST', headers:{'Content-Type':'application/json'},
569
+ body:JSON.stringify({username:currentUser, chat_id:cid, title:newTitle})
570
+ });
571
+ loadHistory();
572
+ } else { loadHistory(); }
573
+ }
574
+ input.addEventListener('blur', save);
575
+ input.addEventListener('keydown', (e) => { if(e.key === 'Enter') { input.blur(); } });
576
+ titleSpan.replaceWith(input); input.focus();
577
+ }
578
+
579
+ async function deleteChat(cid) {
580
+ const el = document.getElementById('chat-' + cid);
581
+ if(el) el.remove();
582
+ await fetch('/delete_chat', {
583
+ method:'POST', headers:{'Content-Type':'application/json'},
584
+ body:JSON.stringify({username:currentUser, chat_id:cid})
585
+ });
586
+ if(currentChatId === cid) newChat();
587
+ loadHistory();
588
+ }
589
+
590
+ async function loadHistory() {
591
+ try {
592
+ const res = await fetch('/get_history', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
593
+ const data = await res.json();
594
+ const list = document.getElementById('history-list'); list.innerHTML = "";
595
+ if (data.chats) {
596
+ Object.keys(data.chats).reverse().forEach(cid => {
597
+ const title = data.chats[cid].title || "New Chat";
598
+ list.innerHTML += `
599
+ <div class="history-item" id="chat-${cid}" onclick="loadChat('${cid}')" oncontextmenu="return false;"
600
+ ontouchstart="handleHistoryTouchStart(event, '${cid}')" ontouchend="handleHistoryTouchEnd(event)">
601
+ <span class="h-title">${title}</span>
602
+ <div class="h-actions">
603
+ <i class="fas fa-pen h-icon" onclick="event.stopPropagation(); startRename('${cid}')"></i>
604
+ <i class="fas fa-trash h-icon" onclick="event.stopPropagation(); deleteChat('${cid}')"></i>
605
+ </div>
606
+ </div>`;
607
+ });
608
+ }
609
+ } catch(e) {}
610
+ }
611
+
612
+ async function typeWriter(element, markdownText) {
613
+ element.innerHTML = marked.parse(markdownText);
614
+ hljs.highlightAll();
615
+ if (window.MathJax) await MathJax.typesetPromise([element]);
616
+ if (window.mermaid) {
617
+ const m = element.querySelectorAll('code.language-mermaid');
618
+ m.forEach(c => { const d = document.createElement('div'); d.className='mermaid'; d.innerHTML=c.innerText; c.parentElement.replaceWith(d); });
619
+ window.mermaid.init(undefined, element.querySelectorAll('.mermaid'));
620
+ }
621
+ element.style.opacity = 0; element.style.transition = 'opacity 0.4s';
622
+ setTimeout(() => { element.style.opacity = 1; scrollToBottom(); }, 50);
623
+ }
624
+
625
  function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }
626
+ async function newChat() {
627
+ currentChatId = null;
628
+ document.getElementById('chat-box').innerHTML = getIntroHtml(currentUser);
629
+ const r = await fetch('/new_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser})});
630
+ const d = await r.json(); currentChatId = d.chat_id; loadHistory();
631
+ document.getElementById('sidebar').classList.remove('open');
632
+ }
633
+ async function loadChat(cid) {
634
+ currentChatId = cid; const res = await fetch('/get_chat', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({username:currentUser, chat_id:cid})});
635
+ const data = await res.json(); const box = document.getElementById('chat-box'); box.innerHTML = "";
636
+ data.messages.forEach(msg => {
637
+ const isUser = msg.role === 'user';
638
+ if(isUser) {
639
+ box.insertAdjacentHTML('beforeend', `<div class="msg user-msg"><div class="user-content">${msg.content.replace(/</g, "&lt;")}</div></div>`);
640
+ } else {
641
+ const div = document.createElement('div'); div.className = 'msg ai-msg';
642
+ div.innerHTML = `<div class="ai-content">${marked.parse(msg.content)}</div>`;
643
+ box.appendChild(div);
644
+ hljs.highlightAll();
645
+ if(window.MathJax) MathJax.typesetPromise([div]);
646
+ div.insertAdjacentHTML('beforeend', `<div class="msg-actions"><i class="fas fa-copy action-icon" onclick="copyAiResponse(this)"></i></div>`);
647
+ }
648
+ });
649
+ document.getElementById('sidebar').classList.remove('open');
650
+ box.scrollTop = box.scrollHeight;
651
+ }
652
+
653
+ @app.route('/manifest.json')
654
+ def manifest():
655
+ data = {
656
+ "name": "Student's AI",
657
+ "short_name": "StudentAI",
658
+ "start_url": "/",
659
+ "display": "standalone",
660
+ "orientation": "portrait",
661
+ "background_color": "#09090b",
662
+ "theme_color": "#09090b",
663
+ "icons": [
664
+ {
665
+ "src": "https://cdn-icons-png.flaticon.com/512/4712/4712035.png",
666
+ "sizes": "192x192",
667
+ "type": "image/png"
668
+ },
669
+ {
670
+ "src": "https://cdn-icons-png.flaticon.com/512/4712/4712035.png",
671
+ "sizes": "512x512",
672
+ "type": "image/png"
673
+ }
674
+ ]
675
+ }
676
+ return Response(json.dumps(data), mimetype='application/json')
677
+
678
+ if __name__ == '__main__':
679
+ app.run(host='0.0.0.0', port=7860)
680
+ """ # --- END OF HTML TEMPLATE STRING ---
681
 
682
+ # --- BACKEND ROUTES ---
683
  @app.route("/", methods=["GET"])
684
  def home(): return render_template_string(HTML_TEMPLATE)
685
 
 
726
  u, cid, msg = d.get("username"), d.get("chat_id"), d.get("message")
727
  img_data = d.get("image")
728
  file_text = d.get("file_text")
729
+
730
  if u not in user_db: user_db[u] = {}
731
  if cid not in user_db[u]: user_db[u][cid] = {"messages": []}
732
+
733
  user_db[u][cid]["messages"].append({"role": "user", "content": msg})
734
  reply = generate_with_retry(msg, img_data, file_text, user_db[u][cid]["messages"][:-1])
735
  user_db[u][cid]["messages"].append({"role": "model", "content": reply})
736
+
737
  new_title = False
738
  if len(user_db[u][cid]["messages"]) <= 2:
739
  user_db[u][cid]["title"] = " ".join(msg.split()[:4])
740
  new_title = True
741
+
742
  save_db(user_db)
743
  return jsonify({"response": reply, "new_title": new_title})
744
 
 
746
  def manifest():
747
  data = {
748
  "name": "Student's AI",
749
+ "short_name": "Student's AI",
750
  "start_url": "/",
751
  "display": "standalone",
752
  "orientation": "portrait",
753
  "background_color": "#09090b",
754
  "theme_color": "#09090b",
755
  "icons": [
756
+ {
757
+ "src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
758
+ "sizes": "192x192",
759
+ "type": "image/png"
760
+ },
761
+ {
762
+ "src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
763
+ "sizes": "512x512",
764
+ "type": "image/png"
765
+ }
766
  ]
767
  }
768
  return Response(json.dumps(data), mimetype='application/json')