Spaces:
Sleeping
Sleeping
File size: 36,559 Bytes
1f29ed1 1298015 72cca92 1298015 7889a7b b877f0b 1f29ed1 4687026 72cca92 4687026 144825c 4687026 073f3d3 1f29ed1 144825c 1f29ed1 c55cf25 1f29ed1 a531dee 144825c e127816 9f6a49b 922f0ea 144825c 1f29ed1 144825c 073f3d3 72cca92 144825c a531dee 144825c 073f3d3 1298015 144825c 1298015 144825c 1f29ed1 144825c 1f29ed1 1298015 da52f07 7889a7b 144825c 1298015 c55cf25 1f29ed1 144825c 073f3d3 144825c 1298015 144825c a531dee 1298015 073f3d3 5d97563 144825c 1f29ed1 144825c 1f29ed1 144825c 9f6a49b 1298015 144825c e127816 144825c 4687026 1f29ed1 144825c 03027d7 144825c 4687026 144825c 4687026 144825c 6530578 144825c 6530578 144825c e127816 144825c 9d544f3 144825c 9d544f3 144825c 9d4f5aa e127816 144825c c5d0bfa 144825c 1f29ed1 4687026 144825c 9f6a49b 1298015 144825c c5d0bfa 144825c 9f6a49b 4687026 e127816 144825c e127816 144825c 9f6a49b e127816 4687026 e127816 9f6a49b e127816 144825c 72cca92 4687026 1f29ed1 4687026 a531dee 144825c 1298015 144825c 1298015 7889a7b 144825c 7889a7b a531dee 1f29ed1 4687026 1f29ed1 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 6530578 144825c 4687026 144825c c5d0bfa 144825c c5d0bfa 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c affd9fd 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 144825c 4687026 affd9fd 40214d2 144825c 5ea3b18 144825c 5ea3b18 144825c 5ea3b18 144825c affd9fd 144825c 5ea3b18 4687026 5ea3b18 144825c 5ea3b18 144825c 5ea3b18 affd9fd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 |
import os
import uuid
import time
import json
import base64
import io
import warnings
from PIL import Image
from flask import Flask, request, jsonify, render_template_string, Response
import google.generativeai as genai
# --- FIX: IGNORE DEPRECATION WARNINGS ---
warnings.filterwarnings("ignore")
# ==========================================
# 👇 API KEYS SETUP 👇
# ==========================================
keys_string = os.environ.get("API_KEYS", "")
API_KEYS = [k.strip() for k in keys_string.replace(',', ' ').replace('\n', ' ').split() if k.strip()]
# --- 💾 DATABASE ---
DB_FILE = "chat_db.json"
def load_db():
try:
if os.path.exists(DB_FILE):
with open(DB_FILE, 'r') as f: return json.load(f)
except: pass
return {}
def save_db(db):
try:
with open(DB_FILE, 'w') as f: json.dump(db, f, indent=2)
except: pass
user_db = load_db()
current_key_index = 0
app = Flask(__name__)
# --- 🧠SYSTEM INSTRUCTION ---
SYSTEM_INSTRUCTION = """
ROLE: You are "Student's AI", a professional academic tutor.
RULES:
1. **MATH:** Use LaTeX for formulas ($$ ... $$).
2. **DIAGRAMS:** Use Mermaid.js (```mermaid ... ```).
3. **LANGUAGE:** English by default. Use Tamil/Tanglish ONLY if requested.
4. **FORMAT:** Markdown. Bold key terms.
5. **CODE:** Use Python/Java/C++ blocks. Explain logic briefly.
"""
# --- 🧬 MODEL & FILE HANDLING ---
def get_working_model(key):
try:
genai.configure(api_key=key)
models = list(genai.list_models())
chat_models = [m for m in models if 'generateContent' in m.supported_generation_methods]
for m in chat_models:
if "flash" in m.name.lower() and "1.5" in m.name: return m.name
for m in chat_models:
if "pro" in m.name.lower() and "1.5" in m.name: return m.name
if chat_models: return chat_models[0].name
except: return None
return None
def process_image(image_data):
try:
if "base64," in image_data:
image_data = image_data.split("base64,")[1]
image_bytes = base64.b64decode(image_data)
return Image.open(io.BytesIO(image_bytes))
except: return None
def generate_with_retry(prompt, image_data=None, file_text=None, history_messages=[]):
global current_key_index
if not API_KEYS: return "🚨 API Keys Missing."
formatted_history = []
for m in history_messages[-6:]:
role = "user" if m["role"] == "user" else "model"
formatted_history.append({"role": role, "parts": [m["content"]]})
current_parts = []
if file_text: current_parts.append(f"analyzing file:\n{file_text}\n\n")
current_parts.append(prompt)
if image_data:
img = process_image(image_data)
if img: current_parts.append(img)
for i in range(len(API_KEYS)):
key = API_KEYS[current_key_index]
model_name = get_working_model(key)
if not model_name:
current_key_index = (current_key_index + 1) % len(API_KEYS)
continue
try:
genai.configure(api_key=key)
model = genai.GenerativeModel(model_name=model_name, system_instruction=SYSTEM_INSTRUCTION)
if image_data or file_text:
response = model.generate_content(current_parts)
else:
chat = model.start_chat(history=formatted_history)
response = chat.send_message(prompt)
return response.text
except Exception as e:
current_key_index = (current_key_index + 1) % len(API_KEYS)
time.sleep(1)
return "âš ï¸ System Busy. Please try again."
# --- UI TEMPLATE (Fixed Quotes & Logic) ---
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, interactive-widget=resizes-content">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#09090b">
<link rel="manifest" href="/manifest.json">
<title>Student's AI</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>window.MathJax = { tex: { inlineMath: [['$', '$']] }, svg: { fontCache: 'global' } };</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
mermaid.initialize({ startOnLoad: false, theme: 'dark', securityLevel: 'loose' });
window.mermaid = mermaid;
</script>
<style>
:root {
--bg: #09090b; --card: #18181b; --user-msg: #27272a; --text: #e4e4e7;
--accent: #fff; --border: #27272a; --dim: #71717a;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
body, html {
margin: 0; padding: 0; height: 100dvh; width: 100%; max-width: 100%;
background: var(--bg); color: var(--text); font-family: 'Outfit', sans-serif;
overflow: hidden; font-size: 17px;
-webkit-user-select: none; user-select: none;
}
textarea, input { -webkit-user-select: text !important; user-select: text !important; }
.user-content, .ai-content, code, pre { -webkit-user-select: none !important; user-select: none !important; }
/* --- APP CONTAINER (Pushed down for Header) --- */
#app-container {
display: flex; flex-direction: column;
height: 100dvh; width: 100%;
position: relative; overflow-x: hidden;
padding-top: 70px; /* Space for fixed header */
}
/* --- HEADER LOCKED --- */
header {
height: 70px; padding: 0 20px; background: rgba(9,9,11, 0.98);
border-bottom: 1px solid var(--border-color);
display: flex; align-items: center; justify-content: space-between;
z-index: 50;
padding-top: env(safe-area-inset-top);
position: absolute; top: 0; left: 0; right: 0;
}
.menu-btn {
width: 40px; height: 40px; border-radius: 50%; border: 1px solid #333;
display: flex; align-items: center; justify-content: center; cursor: pointer;
transition: 0.2s; color: #fff;
}
.menu-btn:active { transform: scale(0.95); background: #222; }
.app-title { font-size: 24px; font-weight: 800; letter-spacing: -0.5px; color: #fff; }
/* --- SIDEBAR ANIMATION --- */
#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;
}
#sidebar.open { transform: translateY(0); }
@media (min-width: 768px) {
#sidebar { width: 350px; border-right: 1px solid var(--border); }
.input-container { max-width: 800px; }
#chat-box { padding: 20px 15%; }
}
.user-info { margin-bottom: 30px; font-size: 20px; font-weight: 700; color: #fff; display: flex; align-items: center; gap: 15px; flex-shrink: 0; }
.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;
}
.history-label { color: var(--dim); font-size: 13px; font-weight: 600; margin-bottom: 10px; letter-spacing: 1px; text-transform: uppercase; flex-shrink: 0; }
#history-list { flex: 1; overflow-y: auto; padding: 10px 0; min-height: 100px; }
.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;
}
.history-item:active { background: #222; color: #fff; border-color: #444; }
.h-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; flex: 1; margin-right: 10px; }
.h-actions { display: none; gap: 15px; }
.history-item.active-mode .h-actions { display: flex; }
.h-icon { font-size: 16px; color: #fff; padding: 5px; }
.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;
}
.brand-section { text-align: center; margin-top: 20px; padding-bottom: env(safe-area-inset-bottom); flex-shrink: 0; }
.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; }
.logout-btn { color: #ef4444; cursor: pointer; font-size: 15px; font-weight: 600; padding: 10px; }
#chat-box {
flex: 1; overflow-y: auto; padding: 20px 5%; padding-bottom: 80px;
display: flex; flex-direction: column; gap: 25px;
-webkit-overflow-scrolling: touch; overscroll-behavior-y: contain; min-height: 0;
}
/* --- LOCKED INTRO TEXT --- */
#intro-container {
position: absolute;
top: 140px; /* Fixed from top so it won't move up with keyboard */
left: 50%;
transform: translateX(-50%);
width: 90%; max-width: 600px;
text-align: center;
z-index: 10;
pointer-events: none;
}
.msg { width: 100%; line-height: 1.7; font-size: 17px; opacity: 0; animation: fadeInstant 0.3s forwards; display: flex; flex-direction: column; }
@keyframes fadeInstant { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.user-msg { align-items: flex-end; }
.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; }
.ai-msg { align-items: flex-start; }
.ai-content { width: 100%; color: #d4d4d8; word-wrap: break-word; }
.ai-content strong { color: #fff; font-weight: 700; }
.ai-content h1, .ai-content h2 { margin-top: 20px; color: #fff; font-weight: 700; }
.ai-content img, .user-content img { cursor: pointer; transition: 0.2s; }
.ai-content img:active, .user-content img:active { transform: scale(0.98); }
pre { background: #1e1e1e !important; border-radius: 12px; padding: 15px; overflow-x: auto; margin: 15px 0; border: 1px solid #333; max-width: 100%; }
code { font-family: 'JetBrains Mono', monospace; font-size: 14px; }
.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%; }
.mermaid { background: #111; padding: 15px; border-radius: 10px; text-align: center; margin: 15px 0; overflow-x: auto; }
.msg-actions { margin-top: 10px; opacity: 0; transition: opacity 0.2s; display: flex; gap: 20px; align-items: center; }
.user-msg .msg-actions { justify-content: flex-end; }
.msg:hover .msg-actions { opacity: 1; }
.action-icon { cursor: pointer; color: var(--dim); font-size: 18px; transition: 0.2s; }
.action-icon:hover { color: #fff; transform: scale(1.1); }
.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)); }
.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; }
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; }
.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; }
.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; }
#preview-area { position: absolute; bottom: 85px; left: 20px; display: none; z-index: 70; }
.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); }
.preview-img { width: 100%; height: 100%; object-fit: cover; }
.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; }
/* --- LOGIN PAGE LOCKED (FIXED) --- */
#login-overlay {
position: fixed; inset: 0; background: #000; z-index: 2000;
display: flex;
/* Align to START (Top) to prevent centering jump */
align-items: flex-start; justify-content: center;
/* Force padding from top so it never moves */
padding-top: 180px;
transition: opacity 0.8s ease; opacity: 1; pointer-events: auto;
}
#login-overlay.hidden { opacity: 0; pointer-events: none; }
.login-box {
width: 90%; max-width: 350px; text-align: center;
padding: 40px; border: 1px solid var(--border); border-radius: 20px; background: #0a0a0a;
/* No auto margins */
}
#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; }
#image-modal img { max-width: 95%; max-height: 90%; border-radius: 8px; box-shadow: 0 0 20px rgba(0,0,0,0.8); }
#image-modal.active { opacity: 1; }
</style>
</head>
<body>
<div id="login-overlay">
<div class="login-box">
<h1 class="app-title" style="margin-bottom:10px;">Student's AI</h1>
<input type="text" id="username-input" placeholder="Your Name" style="width:100%; padding:15px; border-radius:12px; border:1px solid #333; background:#111; color:#fff; text-align:center; outline:none; margin-bottom:20px; font-size: 16px;" onkeydown="if(event.key==='Enter') handleLogin()">
<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>
</div>
</div>
<div id="image-modal" onclick="closeImagePreview()">
<img id="modal-img" src="" alt="Preview">
</div>
<div id="sidebar">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-shrink:0;">
<div class="user-info"><span id="display-name">User</span></div>
<div class="menu-btn" onclick="toggleSidebar()"><i class="fas fa-times"></i></div>
</div>
<button class="new-chat-btn" onclick="newChat()">New Chat</button>
<div class="history-label">Chat History</div>
<div id="history-list"></div>
<div class="brand-section">
<div class="brand-name">Designed by Shirpi</div>
<div class="logout-btn" onclick="handleLogout()">Log Out</div>
</div>
</div>
<div id="app-container">
<header>
<div class="menu-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
<span class="app-title">Student's AI</span>
<div style="width:40px;"></div>
</header>
<div id="chat-box"></div>
<div class="input-wrapper">
<div id="preview-area">
<div class="preview-box"><div id="preview-visual"></div></div>
<button class="remove-preview" onclick="clearAttachment()">×</button>
</div>
<div class="input-container">
<button class="icon-btn" onclick="document.getElementById('file-input').click()"><i class="fas fa-paperclip"></i></button>
<input type="file" id="file-input" accept="image/*,.txt,.py,.js,.html,.css,.md,.csv,.json" hidden onchange="handleFileSelect(this)">
<button class="icon-btn" onclick="document.getElementById('camera-input').click()"><i class="fas fa-camera"></i></button>
<input type="file" id="camera-input" accept="image/*" capture="environment" hidden onchange="handleFileSelect(this)">
<textarea id="input" placeholder="Type a message..." rows="1" oninput="resizeInput(this)"></textarea>
<button class="send-btn" onclick="send()"><i class="fas fa-arrow-up"></i></button>
</div>
</div>
</div>
<script>
let currentUser = null;
let currentChatId = null;
let currentAttachment = { type: null, data: null, name: null };
let longPressTimer;
// --- FIXED INTRO: LOCKED CONTAINER ---
function getIntroHtml(name) {
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>`;
}
// --- AUTH LOGIC (SMOOTH TRANSITION) ---
function checkLogin() {
try {
const stored = localStorage.getItem("student_ai_user");
if (stored) {
currentUser = stored;
document.getElementById("login-overlay").classList.add('hidden');
showApp();
}
} catch(e) { console.log("Storage access denied"); }
}
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;
// FORCE HIDE DIRECTLY
const overlay = document.getElementById("login-overlay");
overlay.classList.add('hidden');
setTimeout(() => overlay.style.display = 'none', 500);
showApp();
} else {
input.style.border = "1px solid red";
setTimeout(() => input.style.border = "1px solid #333", 2000);
}
}
function handleLogout() {
try { localStorage.removeItem("student_ai_user"); } catch(e){}
const overlay = document.getElementById("login-overlay");
overlay.style.display = 'flex';
setTimeout(() => overlay.classList.remove('hidden'), 10);
document.getElementById('sidebar').classList.remove('open');
setTimeout(() => {
document.getElementById('chat-box').innerHTML = "";
currentChatId = null;
document.getElementById("username-input").value = "";
}, 500);
}
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);
}
}
}
function resizeInput(el) {
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 150) + 'px';
}
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 };
const previewArea = document.getElementById('preview-area');
const visual = document.getElementById('preview-visual');
previewArea.style.display = 'block';
visual.innerHTML = isImage ? `<img src="${result}" class="preview-img">` : `<div class="preview-file-icon"><i class="fas fa-file-alt"></i></div>`;
}
reader.readAsDataURL(file);
}
input.value = "";
}
function clearAttachment() {
currentAttachment = { type: null, data: null, name: null };
document.getElementById('preview-area').style.display = 'none';
}
function scrollToBottom() {
const box = document.getElementById('chat-box');
setTimeout(() => {
box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });
}, 100);
}
async function send() {
const input = document.getElementById('input');
const text = input.value.trim();
if (!text && !currentAttachment.data) return;
// --- REMOVE INTRO TEXT AUTOMATICALLY ---
const intro = document.getElementById('intro-container');
if(intro) { intro.style.display = 'none'; intro.remove(); }
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, "<")}${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; }
}
function copyText(text) { navigator.clipboard.writeText(text); }
function copyAiResponse(btn) {
const text = btn.closest('.ai-msg').querySelector('.ai-content').innerText;
navigator.clipboard.writeText(text);
}
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);
}
function editMessage(oldText) { document.getElementById('input').value = oldText; document.getElementById('input').focus(); }
function regenerate(text) { document.getElementById('input').value = text; send(); }
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);
}
});
function closeImagePreview() {
const modal = document.getElementById('image-modal');
modal.classList.remove('active');
setTimeout(() => modal.style.display = 'none', 300);
}
function handleHistoryTouchStart(e, cid) {
longPressTimer = setTimeout(() => {
e.target.closest('.history-item').classList.add('active-mode');
}, 600);
}
function handleHistoryTouchEnd(e) { clearTimeout(longPressTimer); }
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();
}
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();
}
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) {}
}
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);
}
function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }
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');
}
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, "<")}</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;
}
checkLogin();
</script>
</body>
</html>
"""
# --- BACKEND ROUTES ---
@app.route("/", methods=["GET"])
def home(): return render_template_string(HTML_TEMPLATE)
@app.route("/new_chat", methods=["POST"])
def new_chat():
u = request.json.get("username")
if u not in user_db: user_db[u] = {}
nid = str(uuid.uuid4())
user_db[u][nid] = {"title": "New Chat", "messages": []}
save_db(user_db)
return jsonify({"chat_id": nid})
@app.route("/rename_chat", methods=["POST"])
def rename_chat():
d = request.json
u, cid, t = d.get("username"), d.get("chat_id"), d.get("title")
if u in user_db and cid in user_db[u]:
user_db[u][cid]["title"] = t
save_db(user_db)
return jsonify({"status":"ok"})
@app.route("/delete_chat", methods=["POST"])
def delete_chat():
d = request.json
u, cid = d.get("username"), d.get("chat_id")
if u in user_db and cid in user_db[u]:
del user_db[u][cid]
save_db(user_db)
return jsonify({"status":"ok"})
@app.route("/get_history", methods=["POST"])
def get_history():
u = request.json.get("username")
return jsonify({"chats": user_db.get(u, {})})
@app.route("/get_chat", methods=["POST"])
def get_chat():
d = request.json
return jsonify({"messages": user_db.get(d["username"], {}).get(d["chat_id"], {}).get("messages", [])})
@app.route("/chat", methods=["POST"])
def chat():
d = request.json
u, cid, msg = d.get("username"), d.get("chat_id"), d.get("message")
img_data = d.get("image")
file_text = d.get("file_text")
if u not in user_db: user_db[u] = {}
if cid not in user_db[u]: user_db[u][cid] = {"messages": []}
user_db[u][cid]["messages"].append({"role": "user", "content": msg})
reply = generate_with_retry(msg, img_data, file_text, user_db[u][cid]["messages"][:-1])
user_db[u][cid]["messages"].append({"role": "model", "content": reply})
new_title = False
if len(user_db[u][cid]["messages"]) <= 2:
user_db[u][cid]["title"] = " ".join(msg.split()[:4])
new_title = True
save_db(user_db)
return jsonify({"response": reply, "new_title": new_title})
@app.route('/manifest.json')
def manifest():
data = {
"name": "Student's AI",
"short_name": "Student's AI",
"start_url": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#09090b",
"theme_color": "#09090b",
"icons": [
{
"src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://huggingface.co/spaces/Shirpi/Student-s_AI/resolve/main/1000177401.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
return Response(json.dumps(data), mimetype='application/json')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |