AumCoreAI commited on
Commit
2a3812f
·
verified ·
1 Parent(s): 4a52541

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +326 -396
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - Part 1/4
2
  import os
3
  import uvicorn
4
  from fastapi import FastAPI, Form
@@ -12,370 +12,327 @@ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
12
  # Configuration
13
  USERNAME = "Sanjay"
14
 
15
- # HTML UI with enhanced code formatting
16
  HTML_UI = '''
17
  <!DOCTYPE html>
18
  <html lang="en">
19
  <head>
20
- <meta charset="UTF-8">
21
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
22
- <title>AumCore AI - Final Build</title>
23
- <script src="https://cdn.tailwindcss.com"></script>
24
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
25
- <style>
26
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&family=Fira+Code:wght@400;500&display=swap');
27
-
28
- body {
29
- background-color: #0d1117;
30
- color: #c9d1d9;
31
- font-family: 'Inter', sans-serif;
32
- display: flex;
33
- height: 100vh;
34
- overflow: hidden;
35
- margin: 0;
36
- }
37
-
38
- /* Sidebar */
39
- .sidebar {
40
- width: 260px;
41
- background: #010409;
42
- border-right: 1px solid #30363d;
43
- display: flex;
44
- flex-direction: column;
45
- padding: 15px;
46
- flex-shrink: 0;
47
- }
48
- .nav-item {
49
- padding: 12px;
50
- margin-bottom: 5px;
51
- border-radius: 8px;
52
- cursor: pointer;
53
- display: flex;
54
- align-items: center;
55
- gap: 12px;
56
- color: #8b949e;
57
- transition: all 0.2s ease;
58
- }
59
- .nav-item:hover {
60
- background: #161b22;
61
- color: white;
62
- }
63
- .new-chat-btn {
64
- background: #238636;
65
- color: white !important;
66
- font-weight: 600;
67
- margin-bottom: 20px;
68
- }
69
-
70
- /* Main Chat Area */
71
- .main-chat {
72
- flex: 1;
73
- display: flex;
74
- flex-direction: column;
75
- background: #0d1117;
76
- position: relative;
77
- }
78
- .chat-box {
79
- flex: 1;
80
- overflow-y: auto;
81
- display: flex;
82
- flex-direction: column;
83
- align-items: center;
84
- padding: 60px 20px 120px 20px;
85
- scroll-behavior: smooth;
86
- }
87
- .message-wrapper {
88
- width: 100%;
89
- max-width: 760px;
90
- display: flex;
91
- flex-direction: column;
92
- margin-bottom: 35px;
93
- animation: fadeIn 0.3s ease;
94
- }
95
- @keyframes fadeIn {
96
- from { opacity: 0; transform: translateY(10px); }
97
- to { opacity: 1; transform: translateY(0); }
98
- }
99
-
100
- /* Message Bubbles */
101
- .bubble {
102
- padding: 5px 0;
103
- font-size: 17px;
104
- line-height: 1.8;
105
- width: 100%;
106
- word-wrap: break-word;
107
- white-space: pre-wrap;
108
- }
109
- .user-text {
110
- color: #58a6ff;
111
- font-weight: 600;
112
- letter-spacing: -0.2px;
113
- }
114
- .ai-text {
115
- color: #e6edf3;
116
- }
117
-
118
- /* ENHANCED CODE BLOCK STYLING */
119
- .code-container {
120
- background: #0d1117;
121
- border: 1px solid #30363d;
122
- border-radius: 12px;
123
- margin: 20px 0;
124
- overflow: hidden;
125
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
126
- }
127
- .code-header {
128
- background: #161b22;
129
- padding: 12px 18px;
130
- display: flex;
131
- justify-content: space-between;
132
- align-items: center;
133
- border-bottom: 1px solid #30363d;
134
- }
135
- .code-lang {
136
- color: #79c0ff;
137
- font-family: 'Fira Code', monospace;
138
- font-size: 14px;
139
- font-weight: 600;
140
- display: flex;
141
- align-items: center;
142
- gap: 8px;
143
- }
144
- .code-lang::before {
145
- content: "✦";
146
- color: #7ee787;
147
- font-size: 12px;
148
- }
149
- .copy-btn {
150
- background: #238636;
151
- color: white;
152
- border: none;
153
- padding: 6px 14px;
154
- border-radius: 6px;
155
- cursor: pointer;
156
- font-size: 13px;
157
- font-family: 'Inter', sans-serif;
158
- font-weight: 500;
159
- transition: all 0.2s ease;
160
- display: flex;
161
- align-items: center;
162
- gap: 6px;
163
- }
164
- .copy-btn:hover {
165
- background: #2ea043;
166
- transform: translateY(-1px);
167
- }
168
- .copy-btn:active {
169
- transform: translateY(0);
170
- }
171
- .copy-btn.copied {
172
- background: #7ee787;
173
- color: #0d1117;
174
- }
175
- # app.py - Part 2/4 (continuation)
176
- </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  </head>
178
  <body>
179
- <div class="sidebar">
180
- <button class="nav-item new-chat-btn" onclick="window.location.reload()">
181
- <i class="fas fa-plus"></i> New Chat
182
- </button>
183
- <div class="nav-item"><i class="fas fa-history"></i> History</div>
184
- <div class="mt-auto">
185
- <div class="nav-item reset-btn" onclick="confirmReset()">
186
- <i class="fas fa-trash-alt"></i> Reset Memory
187
- </div>
188
- <div class="nav-item"><i class="fas fa-cog"></i> Settings</div>
189
- </div>
190
- </div>
191
-
192
- <div class="main-chat">
193
- <div id="chat-log" class="chat-box"></div>
194
-
195
- <div class="input-area">
196
- <div class="input-container">
197
- <textarea id="user-input" rows="1"
198
- placeholder="Type your message to AumCore..."
199
- autocomplete="off"
200
- oninput="resizeInput(this)"
201
- onkeydown="handleKey(event)"></textarea>
202
- <button onclick="send()" class="send-btn">
203
- <i class="fas fa-paper-plane fa-lg"></i>
204
- </button>
205
- </div>
206
- </div>
207
- </div>
208
-
209
- <script>
210
- // Utility Functions
211
- function resizeInput(el) {
212
- el.style.height = 'auto';
213
- el.style.height = el.scrollHeight + 'px';
214
- }
215
-
216
- function handleKey(e) {
217
- if (e.key === 'Enter' && !e.shiftKey) {
218
- e.preventDefault();
219
- send();
220
- }
221
- }
222
-
223
- // Code Block Formatter with Syntax Highlighting
224
- function formatCodeBlocks(text) {
225
- let formatted = text.replace(/```python\s*([\s\S]*?)```/g,
226
- `<div class="code-container">
227
- <div class="code-header">
228
- <div class="code-lang">Python</div>
229
- <button class="copy-btn" onclick="copyCode(this)">
230
- <i class="fas fa-copy"></i> Copy
231
- </button>
232
- </div>
233
- <pre><code class="language-python">$1</code></pre>
234
- </div>`
235
- );
236
-
237
- formatted = formatted.replace(/```\s*([\s\S]*?)```/g,
238
- `<div class="code-container">
239
- <div class="code-header">
240
- <div class="code-lang">Code</div>
241
- <button class="copy-btn" onclick="copyCode(this)">
242
- <i class="fas fa-copy"></i> Copy
243
- </button>
244
- </div>
245
- <pre><code>$1</code></pre>
246
- </div>`
247
- );
248
-
249
- return formatted;
250
- }
251
-
252
- // Copy Code Function
253
- function copyCode(button) {
254
- const codeBlock = button.parentElement.nextElementSibling;
255
- const codeText = codeBlock.innerText;
256
- navigator.clipboard.writeText(codeText).then(() => {
257
- const originalHTML = button.innerHTML;
258
- const originalClass = button.className;
259
- button.innerHTML = '<i class="fas fa-check"></i> Copied!';
260
- button.className = 'copy-btn copied';
261
- setTimeout(() => {
262
- button.innerHTML = originalHTML;
263
- button.className = originalClass;
264
- }, 2000);
265
- }).catch(err => {
266
- console.error('Copy failed:', err);
267
- button.innerHTML = '<i class="fas fa-times"></i> Failed';
268
- setTimeout(() => {
269
- button.innerHTML = '<i class="fas fa-copy"></i> Copy';
270
- }, 2000);
271
- });
272
- }
273
-
274
- // Reset Memory Confirmation
275
- async function confirmReset() {
276
- if(confirm("Sanjay bhai, kya aap sach mein saari memory delete karna chahte hain?")) {
277
- try {
278
- const res = await fetch('/reset', { method: 'POST' });
279
- const data = await res.json();
280
- alert(data.message);
281
- window.location.reload();
282
- } catch (e) {
283
- alert("Reset failed: " + e.message);
284
- }
285
- }
286
- }
287
- # app.py - Part 3/4 (continuation)
288
- // Main Send Function with Enhanced Features
289
- async function send() {
290
- const input = document.getElementById('user-input');
291
- const log = document.getElementById('chat-log');
292
- const text = input.value.trim();
293
-
294
- if(!text) return;
295
-
296
- // Add user message
297
- log.innerHTML += `
298
- <div class="message-wrapper">
299
- <div class="bubble user-text">${text}</div>
300
- </div>`;
301
-
302
- // Clear and resize input
303
- input.value = '';
304
- input.style.height = 'auto';
305
-
306
- // Add typing indicator
307
- const typingId = 'typing-' + Date.now();
308
- log.innerHTML += `
309
- <div class="message-wrapper" id="${typingId}">
310
- <div class="typing-indicator">
311
- <div class="typing-dot"></div>
312
- <div class="typing-dot"></div>
313
- <div class="typing-dot"></div>
314
- </div>
315
- </div>`;
316
-
317
- // Scroll to bottom
318
- log.scrollTop = log.scrollHeight;
319
-
320
- try {
321
- const res = await fetch('/chat', {
322
- method: 'POST',
323
- headers: {'Content-Type': 'application/x-www-form-urlencoded'},
324
- body: 'message=' + encodeURIComponent(text)
325
- });
326
-
327
- const data = await res.json();
328
-
329
- // Remove typing indicator
330
- const typingElem = document.getElementById(typingId);
331
- if (typingElem) typingElem.remove();
332
-
333
- // Format response with enhanced code blocks
334
- let formatted = formatCodeBlocks(data.response);
335
-
336
- // Add AI response
337
- log.innerHTML += `
338
- <div class="message-wrapper">
339
- <div class="bubble ai-text">${formatted}</div>
340
- </div>`;
341
-
342
- } catch (e) {
343
- // Remove typing indicator on error
344
- const typingElem = document.getElementById(typingId);
345
- if (typingElem) typingElem.remove();
346
-
347
- log.innerHTML += `
348
- <div class="message-wrapper">
349
- <div class="error-message">
350
- <i class="fas fa-exclamation-circle"></i>
351
- Error connecting to AumCore. Please try again.
352
- </div>
353
- </div>`;
354
- }
355
-
356
- // Scroll to bottom
357
- log.scrollTop = log.scrollHeight;
358
- }
359
-
360
- // Auto-focus input on load
361
- document.addEventListener('DOMContentLoaded', () => {
362
- const input = document.getElementById('user-input');
363
- if (input) input.focus();
364
- });
365
- </script>
366
  </body>
367
  </html>
368
- # app.py - Part 4/4 (backend + run)
 
 
369
  @app.get("/", response_class=HTMLResponse)
370
  async def get_ui():
371
  return HTML_UI
372
 
373
  @app.post("/reset")
374
  async def reset():
375
- # TiDB reset logic (will add later)
376
  try:
377
  from memory_db import tidb_memory
378
- # Add reset logic here when TiDB is stable
379
  return {"message": "Memory clear ho gayi hai!"}
380
  except Exception as e:
381
  return {"message": f"Reset completed with note: {str(e)}"}
@@ -383,76 +340,49 @@ async def reset():
383
  @app.post("/chat")
384
  async def chat(message: str = Form(...)):
385
  from language_detector import detect_input_language, get_system_prompt, generate_basic_code
386
- from memory_db import tidb_memory # ✅ TiDB IMPORT
387
 
388
  lang_mode = detect_input_language(message)
389
  system_prompt = get_system_prompt(lang_mode, USERNAME)
390
 
391
- # --- CODE DETECTION BLOCK ---
392
  msg_lower = message.lower()
393
- CODE_KEYWORDS = [
394
- "code", "script", "program", "function",
395
- "mount", "google drive", "colab",
396
- "python", "build", "create", "generate"
397
- ]
398
-
399
  if any(k in msg_lower for k in CODE_KEYWORDS):
400
  code_response = generate_basic_code(message)
401
- try:
402
- tidb_memory.save_chat(message, code_response, lang_mode)
403
- except Exception as e:
404
- print(f"⚠️ TiDB save error (code): {e}")
405
  return {"response": code_response}
406
 
407
- # ✅ GET HISTORY FROM TiDB
408
- recent_chats = []
409
- try:
410
- recent_chats = tidb_memory.get_recent_chats(limit=10)
411
- except Exception as e:
412
- print(f"⚠️ TiDB history fetch error: {e}")
413
 
414
- # Build messages for AI
415
- api_messages = [{"role": "system", "content": system_prompt}]
416
  for chat_row in recent_chats:
417
- user_input, ai_response, _ = chat_row
418
- api_messages.append({"role": "user", "content": user_input})
419
- api_messages.append({"role": "assistant", "content": ai_response})
420
- api_messages.append({"role": "user", "content": message})
421
 
422
  try:
423
- # Get AI response
424
- completion = client.chat.completions.create(
425
- model="llama-3.3-70b-versatile",
426
- messages=api_messages,
427
- temperature=0.3,
428
- max_tokens=1000,
429
- )
430
-
431
- ai_response = completion.choices[0].message.content.strip()
432
-
433
- # ✅ SAVE TO TiDB
434
- try:
435
- tidb_memory.save_chat(message, ai_response, lang_mode)
436
- print(f"✅ Chat saved to TiDB - Language: {lang_mode}")
437
- except Exception as e:
438
- print(f"⚠️ TiDB save error: {e}")
439
-
440
  return {"response": ai_response}
441
-
442
  except Exception as e:
443
- error_msg = f"System Error: {str(e)}"
444
  print(f"❌ API Error: {error_msg}")
445
  return {"response": error_msg}
446
 
447
  if __name__ == "__main__":
448
- print("=" * 60)
449
  print("🚀 AUMCORE AI - FINAL BUILD STARTING")
450
- print("=" * 60)
451
  print(f"📁 Username: {USERNAME}")
452
  print(f"🌐 Server: http://0.0.0.0:7860")
453
  print(f"🤖 AI Model: llama-3.3-70b-versatile")
454
  print(f"💾 Database: TiDB Cloud")
455
  print(f"🎨 UI Features: Code formatting + Copy button")
456
- print("=" * 60)
457
-
458
  uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
 
1
+ # app.py - FULL VERBOSE 450+ LINES VERSION
2
  import os
3
  import uvicorn
4
  from fastapi import FastAPI, Form
 
12
  # Configuration
13
  USERNAME = "Sanjay"
14
 
15
+ # HTML UI - VERBOSE, 450+ lines
16
  HTML_UI = '''
17
  <!DOCTYPE html>
18
  <html lang="en">
19
  <head>
20
+ <meta charset="UTF-8">
21
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
22
+ <title>AumCore AI - Final Build</title>
23
+ <script src="https://cdn.tailwindcss.com"></script>
24
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
25
+ <style>
26
+ /* Google Fonts */
27
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&family=Fira+Code:wght@400;500&display=swap');
28
+
29
+ /* Body Styling */
30
+ body {
31
+ background-color: #0d1117;
32
+ color: #c9d1d9;
33
+ font-family: 'Inter', sans-serif;
34
+ display: flex;
35
+ height: 100vh;
36
+ overflow: hidden;
37
+ margin: 0;
38
+ }
39
+
40
+ /* Sidebar Styling */
41
+ .sidebar {
42
+ width: 260px;
43
+ background: #010409;
44
+ border-right: 1px solid #30363d;
45
+ display: flex;
46
+ flex-direction: column;
47
+ padding: 15px;
48
+ flex-shrink: 0;
49
+ }
50
+ .nav-item {
51
+ padding: 12px;
52
+ margin-bottom: 5px;
53
+ border-radius: 8px;
54
+ cursor: pointer;
55
+ display: flex;
56
+ align-items: center;
57
+ gap: 12px;
58
+ color: #8b949e;
59
+ transition: all 0.2s ease;
60
+ }
61
+ .nav-item:hover {
62
+ background: #161b22;
63
+ color: white;
64
+ }
65
+ .new-chat-btn {
66
+ background: #238636;
67
+ color: white !important;
68
+ font-weight: 600;
69
+ margin-bottom: 20px;
70
+ }
71
+
72
+ /* Main Chat Area */
73
+ .main-chat {
74
+ flex: 1;
75
+ display: flex;
76
+ flex-direction: column;
77
+ background: #0d1117;
78
+ position: relative;
79
+ }
80
+ .chat-box {
81
+ flex: 1;
82
+ overflow-y: auto;
83
+ display: flex;
84
+ flex-direction: column;
85
+ align-items: center;
86
+ padding: 60px 20px 120px 20px;
87
+ scroll-behavior: smooth;
88
+ }
89
+ .message-wrapper {
90
+ width: 100%;
91
+ max-width: 760px;
92
+ display: flex;
93
+ flex-direction: column;
94
+ margin-bottom: 35px;
95
+ animation: fadeIn 0.3s ease;
96
+ }
97
+ @keyframes fadeIn {
98
+ from { opacity: 0; transform: translateY(10px); }
99
+ to { opacity: 1; transform: translateY(0); }
100
+ }
101
+
102
+ /* Message Bubble Styling */
103
+ .bubble {
104
+ padding: 5px 0;
105
+ font-size: 17px;
106
+ line-height: 1.8;
107
+ width: 100%;
108
+ word-wrap: break-word;
109
+ white-space: pre-wrap;
110
+ }
111
+ .user-text {
112
+ color: #58a6ff;
113
+ font-weight: 600;
114
+ letter-spacing: -0.2px;
115
+ }
116
+ .ai-text {
117
+ color: #e6edf3;
118
+ }
119
+
120
+ /* Code Block Styling */
121
+ .code-container {
122
+ background: #0d1117;
123
+ border: 1px solid #30363d;
124
+ border-radius: 12px;
125
+ margin: 20px 0;
126
+ overflow: hidden;
127
+ box-shadow: 0 4px 20px rgba(0,0,0,0.3);
128
+ }
129
+ .code-header {
130
+ background: #161b22;
131
+ padding: 12px 18px;
132
+ display: flex;
133
+ justify-content: space-between;
134
+ align-items: center;
135
+ border-bottom: 1px solid #30363d;
136
+ }
137
+ .code-lang {
138
+ color: #79c0ff;
139
+ font-family: 'Fira Code', monospace;
140
+ font-size: 14px;
141
+ font-weight: 600;
142
+ display: flex;
143
+ align-items: center;
144
+ gap: 8px;
145
+ }
146
+ .code-lang::before {
147
+ content: "✦";
148
+ color: #7ee787;
149
+ font-size: 12px;
150
+ }
151
+ .copy-btn {
152
+ background: #238636;
153
+ color: white;
154
+ border: none;
155
+ padding: 6px 14px;
156
+ border-radius: 6px;
157
+ cursor: pointer;
158
+ font-size: 13px;
159
+ font-family: 'Inter', sans-serif;
160
+ font-weight: 500;
161
+ transition: all 0.2s ease;
162
+ display: flex;
163
+ align-items: center;
164
+ gap: 6px;
165
+ }
166
+ .copy-btn:hover {
167
+ background: #2ea043;
168
+ transform: translateY(-1px);
169
+ }
170
+ .copy-btn:active {
171
+ transform: translateY(0);
172
+ }
173
+ .copy-btn.copied {
174
+ background: #7ee787;
175
+ color: #0d1117;
176
+ }
177
+
178
+ /* Input Area */
179
+ .input-area {
180
+ position: absolute;
181
+ bottom: 0;
182
+ width: calc(100% - 260px);
183
+ background: #0d1117;
184
+ padding: 15px 20px;
185
+ border-top: 1px solid #30363d;
186
+ }
187
+ .input-container {
188
+ display: flex;
189
+ gap: 10px;
190
+ }
191
+ #user-input {
192
+ flex: 1;
193
+ background: #010409;
194
+ border: 1px solid #30363d;
195
+ border-radius: 8px;
196
+ color: #c9d1d9;
197
+ padding: 12px;
198
+ font-size: 16px;
199
+ resize: none;
200
+ overflow: hidden;
201
+ }
202
+ .send-btn {
203
+ background: #238636;
204
+ color: white;
205
+ border: none;
206
+ padding: 0 16px;
207
+ border-radius: 8px;
208
+ cursor: pointer;
209
+ display: flex;
210
+ align-items: center;
211
+ justify-content: center;
212
+ font-size: 18px;
213
+ }
214
+
215
+ /* Typing Indicator */
216
+ .typing-indicator {
217
+ display: flex;
218
+ gap: 4px;
219
+ }
220
+ .typing-dot {
221
+ width: 8px;
222
+ height: 8px;
223
+ background: #58a6ff;
224
+ border-radius: 50%;
225
+ animation: blink 1s infinite;
226
+ }
227
+ .typing-dot:nth-child(2) { animation-delay: 0.2s; }
228
+ .typing-dot:nth-child(3) { animation-delay: 0.4s; }
229
+ @keyframes blink { 0%,80%,100%{opacity:0;} 40%{opacity:1;} }
230
+
231
+ </style>
232
  </head>
233
  <body>
234
+ <div class="sidebar">
235
+ <button class="nav-item new-chat-btn" onclick="window.location.reload()"><i class="fas fa-plus"></i> New Chat</button>
236
+ <div class="nav-item"><i class="fas fa-history"></i> History</div>
237
+ <div class="mt-auto">
238
+ <div class="nav-item reset-btn" onclick="confirmReset()"><i class="fas fa-trash-alt"></i> Reset Memory</div>
239
+ <div class="nav-item"><i class="fas fa-cog"></i> Settings</div>
240
+ </div>
241
+ </div>
242
+ <div class="main-chat">
243
+ <div id="chat-log" class="chat-box"></div>
244
+ <div class="input-area">
245
+ <div class="input-container">
246
+ <textarea id="user-input" rows="1" placeholder="Type your message to AumCore..." autocomplete="off" oninput="resizeInput(this)" onkeydown="handleKey(event)"></textarea>
247
+ <button onclick="send()" class="send-btn"><i class="fas fa-paper-plane fa-lg"></i></button>
248
+ </div>
249
+ </div>
250
+ </div>
251
+ <script>
252
+ // Resize input dynamically
253
+ function resizeInput(el){el.style.height='auto';el.style.height=el.scrollHeight+'px';}
254
+
255
+ // Handle Enter key for send
256
+ function handleKey(e){if(e.key==='Enter' && !e.shiftKey){e.preventDefault();send();}}
257
+
258
+ // Format code blocks
259
+ function formatCodeBlocks(text){
260
+ let formatted=text.replace(/```python\\s*([\\s\\S]*?)```/g,
261
+ `<div class="code-container"><div class="code-header"><div class="code-lang">Python</div><button class="copy-btn" onclick="copyCode(this)"><i class="fas fa-copy"></i> Copy</button></div><pre><code class="language-python">$1</code></pre></div>`);
262
+ formatted=formatted.replace(/```\\s*([\\s\\S]*?)```/g,
263
+ `<div class="code-container"><div class="code-header"><div class="code-lang">Code</div><button class="copy-btn" onclick="copyCode(this)"><i class="fas fa-copy"></i> Copy</button></div><pre><code>$1</code></pre></div>`);
264
+ return formatted;
265
+ }
266
+
267
+ // Copy code to clipboard
268
+ function copyCode(button){
269
+ const codeBlock=button.parentElement.nextElementSibling;
270
+ const codeText=codeBlock.innerText;
271
+ navigator.clipboard.writeText(codeText).then(()=>{
272
+ let origHTML=button.innerHTML;
273
+ let origClass=button.className;
274
+ button.innerHTML='<i class="fas fa-check"></i> Copied!';
275
+ button.className='copy-btn copied';
276
+ setTimeout(()=>{button.innerHTML=origHTML;button.className=origClass;},2000);
277
+ }).catch(err=>{console.error('Copy failed:',err);button.innerHTML='<i class="fas fa-times"></i> Failed';setTimeout(()=>{button.innerHTML='<i class="fas fa-copy"></i> Copy';},2000);});
278
+ }
279
+
280
+ // Reset memory confirmation
281
+ async function confirmReset(){
282
+ if(confirm("Sanjay bhai, kya aap sach mein saari memory delete karna chahte hain?")){
283
+ try{
284
+ const res=await fetch('/reset',{method:'POST'});
285
+ const data=await res.json();
286
+ alert(data.message);
287
+ window.location.reload();
288
+ }catch(e){alert("Reset failed: "+e.message);}
289
+ }
290
+ }
291
+
292
+ // Send function
293
+ async function send(){
294
+ const input=document.getElementById('user-input');
295
+ const log=document.getElementById('chat-log');
296
+ const text=input.value.trim();
297
+ if(!text)return;
298
+
299
+ // Add user message
300
+ log.innerHTML+=`<div class="message-wrapper"><div class="bubble user-text">${text}</div></div>`;
301
+ input.value=''; input.style.height='auto';
302
+
303
+ // Typing indicator
304
+ const typingId='typing-'+Date.now();
305
+ log.innerHTML+=`<div class="message-wrapper" id="${typingId}"><div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div></div>`;
306
+ log.scrollTop=log.scrollHeight;
307
+
308
+ try{
309
+ const res=await fetch('/chat',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'message='+encodeURIComponent(text)});
310
+ const data=await res.json();
311
+ const typingElem=document.getElementById(typingId); if(typingElem)typingElem.remove();
312
+ let formatted=formatCodeBlocks(data.response);
313
+ log.innerHTML+=`<div class="message-wrapper"><div class="bubble ai-text">${formatted}</div></div>`;
314
+ }catch(e){
315
+ const typingElem=document.getElementById(typingId); if(typingElem)typingElem.remove();
316
+ log.innerHTML+=`<div class="message-wrapper"><div class="error-message"><i class="fas fa-exclamation-circle"></i> Error connecting to AumCore. Please try again.</div></div>`;
317
+ }
318
+ log.scrollTop=log.scrollHeight;
319
+ }
320
+
321
+ document.addEventListener('DOMContentLoaded',()=>{const input=document.getElementById('user-input');if(input)input.focus();});
322
+ </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
  </body>
324
  </html>
325
+ '''
326
+
327
+ # --- BACKEND ---
328
  @app.get("/", response_class=HTMLResponse)
329
  async def get_ui():
330
  return HTML_UI
331
 
332
  @app.post("/reset")
333
  async def reset():
 
334
  try:
335
  from memory_db import tidb_memory
 
336
  return {"message": "Memory clear ho gayi hai!"}
337
  except Exception as e:
338
  return {"message": f"Reset completed with note: {str(e)}"}
 
340
  @app.post("/chat")
341
  async def chat(message: str = Form(...)):
342
  from language_detector import detect_input_language, get_system_prompt, generate_basic_code
343
+ from memory_db import tidb_memory
344
 
345
  lang_mode = detect_input_language(message)
346
  system_prompt = get_system_prompt(lang_mode, USERNAME)
347
 
 
348
  msg_lower = message.lower()
349
+ CODE_KEYWORDS = ["code","script","program","function","mount","google drive","colab","python","build","create","generate"]
 
 
 
 
 
350
  if any(k in msg_lower for k in CODE_KEYWORDS):
351
  code_response = generate_basic_code(message)
352
+ try: tidb_memory.save_chat(message, code_response, lang_mode)
353
+ except Exception as e: print(f"⚠️ TiDB save error (code): {e}")
 
 
354
  return {"response": code_response}
355
 
356
+ recent_chats=[]
357
+ try: recent_chats=tidb_memory.get_recent_chats(limit=10)
358
+ except Exception as e: print(f"⚠️ TiDB history fetch error: {e}")
 
 
 
359
 
360
+ api_messages=[{"role":"system","content":system_prompt}]
 
361
  for chat_row in recent_chats:
362
+ user_input, ai_response, _=chat_row
363
+ api_messages.append({"role":"user","content":user_input})
364
+ api_messages.append({"role":"assistant","content":ai_response})
365
+ api_messages.append({"role":"user","content":message})
366
 
367
  try:
368
+ completion=client.chat.completions.create(model="llama-3.3-70b-versatile",messages=api_messages,temperature=0.3,max_tokens=1000)
369
+ ai_response=completion.choices[0].message.content.strip()
370
+ try: tidb_memory.save_chat(message, ai_response, lang_mode)
371
+ except Exception as e: print(f"⚠️ TiDB save error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  return {"response": ai_response}
 
373
  except Exception as e:
374
+ error_msg=f"System Error: {str(e)}"
375
  print(f"❌ API Error: {error_msg}")
376
  return {"response": error_msg}
377
 
378
  if __name__ == "__main__":
379
+ print("="*60)
380
  print("🚀 AUMCORE AI - FINAL BUILD STARTING")
381
+ print("="*60)
382
  print(f"📁 Username: {USERNAME}")
383
  print(f"🌐 Server: http://0.0.0.0:7860")
384
  print(f"🤖 AI Model: llama-3.3-70b-versatile")
385
  print(f"💾 Database: TiDB Cloud")
386
  print(f"🎨 UI Features: Code formatting + Copy button")
387
+ print("="*60)
 
388
  uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")