Spaces:
Sleeping

Jeetandar N Silwani commited on
Commit
7ee22ad
·
0 Parent(s):

Initial Nexus AI release

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ .env.example
3
+ .gitignore
4
+ .dockerignore
5
+ __pycache__/
6
+ *.pyc
7
+ *.pyo
8
+ instance/
9
+ *.db
10
+ *.sqlite
11
+ *.sqlite3
12
+ outputs/
13
+ uploads/
14
+ .vscode/
15
+ .git/
16
+ README.md
17
+ LICENSE
18
+ startup_stderr.txt
19
+ startup_stdout.txt
20
+ test_output.png
21
+ image.png
.env.example ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # NEXUS AI — Production Environment Configuration
3
+ # =============================================================================
4
+ # Copy this file to .env and fill in your values.
5
+
6
+ # --- REQUIRED ---
7
+
8
+ # OpenRouter API key for AI chat and image generation
9
+ OPENROUTER_API_KEY=sk-or-v1-your_key_here
10
+
11
+ # CORS origins — comma-separated list of domains that may make cross-origin
12
+ # requests. MUST be set explicitly in production (no default).
13
+ # Example: CORS_ORIGINS=https://app.example.com,https://admin.example.com
14
+ CORS_ORIGINS=http://localhost:5000
15
+
16
+ # --- OPTIONAL: Security ---
17
+
18
+ # Flask session signing key — auto-generated if left empty.
19
+ # In production with multiple workers you MUST set this to a fixed value.
20
+ # SECRET_KEY=
21
+
22
+ # Mark session cookies as Secure (only sent over HTTPS).
23
+ # Set to "True" when your deployment uses TLS.
24
+ SESSION_COOKIE_SECURE=False
25
+
26
+ # Session lifetime in hours (default: 24)
27
+ # SESSION_LIFETIME_HOURS=24
28
+
29
+ # --- OPTIONAL: Database ---
30
+
31
+ # Database URL — defaults to SQLite if not set.
32
+ # For production always use PostgreSQL:
33
+ # DATABASE_URL=postgresql://user:password@host:5432/nexus
34
+
35
+ # --- OPTIONAL: AI ---
36
+
37
+ # HuggingFace token for image generation fallback
38
+ # HF_TOKEN=hf_your_token_here
39
+
40
+ # AI model parameters
41
+ # AI_MAX_TOKENS=2048
42
+ # AI_MAX_INPUT_CHARS=12000
43
+ # AI_RETRY_COUNT=2
44
+ # OPENROUTER_BASE=https://openrouter.ai/api/v1/chat/completions
45
+
46
+ # --- OPTIONAL: Server ---
47
+
48
+ # Override host and port
49
+ # HOST=0.0.0.0
50
+ # PORT=5000
51
+
52
+ # Socket.IO async mode — "eventlet" (Linux/production) or "threading" (Windows/dev)
53
+ # SOCKET_ASYNC_MODE=eventlet
54
+
55
+ # --- OPTIONAL: Feature flags ---
56
+
57
+ # Set to "1" to disable camera on headless servers
58
+ # DISABLE_CAMERA=1
59
+ # Set to "1" to disable voice on headless servers
60
+ # DISABLE_VOICE=1
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ outputs/
4
+ uploads/
5
+ instance/
6
+ *.pyc
7
+ *.pyo
8
+ .DS_Store
9
+ Thumbs.db
.vscode/settings.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "python-envs.defaultEnvManager": "ms-python.python:system"
3
+ }
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # OpenCV and MediaPipe system dependencies
6
+ RUN apt-get update && apt-get install -y --no-install-recommends \
7
+ libgl1-mesa-glx \
8
+ libglib2.0-0 \
9
+ libsm6 \
10
+ libxext6 \
11
+ libxrender-dev \
12
+ libgomp1 \
13
+ && rm -rf /var/lib/apt/lists/*
14
+
15
+ COPY requirements.txt .
16
+ RUN pip install --no-cache-dir -r requirements.txt
17
+
18
+ COPY . .
19
+
20
+ EXPOSE 5000
21
+
22
+ ENV SOCKET_ASYNC_MODE=eventlet
23
+
24
+ CMD ["gunicorn", "-k", "eventlet", "-w", "1", "--bind", "0.0.0.0:5000", "wsgi:app"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nexus AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Procfile ADDED
@@ -0,0 +1 @@
 
 
1
+ web: gunicorn -k eventlet -w 1 --bind 0.0.0.0:$PORT wsgi:app
README.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NEXUS AI
2
+
3
+ A futuristic AI chat platform with memory, image generation, 3D sandbox, motion capture, and avatar features.
4
+
5
+ ## Quick Start
6
+
7
+ 1. Clone and set up:
8
+ ```bash
9
+ cp .env.example .env
10
+ # Edit .env with your OpenRouter API key
11
+ ```
12
+
13
+ 2. Install dependencies:
14
+ ```bash
15
+ pip install -r requirements.txt
16
+ ```
17
+
18
+ 3. Run:
19
+ ```bash
20
+ python app.py
21
+ ```
22
+
23
+ ## Production Deployment
24
+
25
+ ### Railway
26
+ ```bash
27
+ # Connect your GitHub repo to Railway
28
+ # Railway auto-detects the Procfile
29
+ # Set environment variables in Railway dashboard
30
+ ```
31
+
32
+ ### Render
33
+ ```bash
34
+ # Create a Web Service on Render
35
+ # Set:
36
+ # Build Command: pip install -r requirements.txt
37
+ # Start Command: gunicorn -k eventlet -w 1 --bind 0.0.0.0:$PORT wsgi:app
38
+ ```
39
+
40
+ ### Docker
41
+ ```bash
42
+ docker build -t nexus .
43
+ docker run -p 5000:5000 --env-file .env nexus
44
+ ```
45
+
46
+ ### VPS
47
+ ```bash
48
+ gunicorn -k eventlet -w 1 --bind 0.0.0.0:5000 wsgi:app
49
+ ```
50
+
51
+ ## Environment Variables
52
+
53
+ | Variable | Required | Default | Description |
54
+ |----------|----------|---------|-------------|
55
+ | `OPENROUTER_API_KEY` | Yes | - | OpenRouter API key for AI |
56
+ | `HF_TOKEN` | No | - | HuggingFace token for image gen fallback |
57
+ | `SECRET_KEY` | No | auto-generated | Flask session signing key |
58
+ | `DATABASE_URL` | No | `sqlite:///nexus.db` | PostgreSQL connection string for production |
59
+ | `CORS_ORIGINS` | No | `http://localhost:5000` | Allowed CORS origins |
60
+
61
+ ## Features
62
+
63
+ - AI Chat with streaming responses
64
+ - User memory (remembers info about you)
65
+ - Image generation
66
+ - Document upload & analysis (PDF, DOCX, TXT)
67
+ - 3D Sandbox with gesture controls
68
+ - Motion capture (pose + hand tracking)
69
+ - 3D Avatar with lip sync
70
+ - Voice commands
71
+ - CSRF-protected API
72
+
73
+ ## Tech Stack
74
+
75
+ - **Backend:** Flask, SQLAlchemy, SQLite/PostgreSQL
76
+ - **AI:** OpenRouter API, HuggingFace Inference
77
+ - **Realtime:** Socket.IO
78
+ - **Computer Vision:** OpenCV, MediaPipe
79
+ - **Frontend:** Vanilla JS, Three.js, CSS
ai/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
ai/jarvis_core.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import base64
4
+ import json
5
+ import logging
6
+ import time
7
+ from datetime import datetime, timezone
8
+ import requests
9
+ from database import db
10
+ from models.memory import Memory
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+ OUTPUT_DIR = "outputs"
15
+ UPLOAD_DIR = "uploads"
16
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
17
+
18
+ _http = requests.Session()
19
+
20
+ API_BASE = os.getenv("OPENROUTER_BASE", "https://openrouter.ai/api/v1/chat/completions")
21
+ MAX_TOKENS = int(os.getenv("AI_MAX_TOKENS", "2048"))
22
+ MAX_INPUT_TOKENS = int(os.getenv("AI_MAX_INPUT_CHARS", "12000"))
23
+ RETRY_COUNT = int(os.getenv("AI_RETRY_COUNT", "2"))
24
+
25
+
26
+ def _api_call(payload, stream=False, timeout=60):
27
+ headers = {
28
+ "Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
29
+ "Content-Type": "application/json"
30
+ }
31
+ last_error = None
32
+ for attempt in range(RETRY_COUNT + 1):
33
+ try:
34
+ resp = _http.post(API_BASE, headers=headers, json=payload, stream=stream, timeout=timeout)
35
+ if resp.status_code == 429:
36
+ wait = min(2 ** attempt, 8)
37
+ log.warning("Rate limited, retrying in %ds", wait)
38
+ time.sleep(wait)
39
+ continue
40
+ if resp.status_code != 200:
41
+ log.error("API error %d: %s", resp.status_code, resp.text[:200])
42
+ return None, resp.status_code
43
+ return resp, resp.status_code
44
+ except requests.exceptions.Timeout:
45
+ log.warning("API timeout (attempt %d/%d)", attempt + 1, RETRY_COUNT + 1)
46
+ last_error = "timeout"
47
+ continue
48
+ except requests.exceptions.ConnectionError as e:
49
+ log.warning("API connection error (attempt %d/%d): %s", attempt + 1, RETRY_COUNT + 1, e)
50
+ last_error = "connection"
51
+ time.sleep(1)
52
+ continue
53
+ except Exception as e:
54
+ log.error("API call failed: %s", e)
55
+ return None, 0
56
+ log.error("API call exhausted retries: %s", last_error)
57
+ return None, 0
58
+
59
+
60
+ def load_memory_from_db(user_id):
61
+ memories = Memory.query.filter_by(user_id=user_id).all()
62
+ profile = {}
63
+ for m in memories:
64
+ profile[m.key] = m.value
65
+ return {"user_profile": profile}
66
+
67
+
68
+ def save_memory_to_db(user_id, memory):
69
+ profile = memory.get("user_profile", {})
70
+ for key, value in profile.items():
71
+ existing = Memory.query.filter_by(user_id=user_id, key=key).first()
72
+ if existing:
73
+ existing.value = str(value)
74
+ else:
75
+ mem = Memory(user_id=user_id, key=key, value=str(value))
76
+ db.session.add(mem)
77
+ db.session.commit()
78
+
79
+
80
+ def extract_user_info(text, memory):
81
+ text_lower = text.lower()
82
+ name_match = re.search(r"(?:my name is|i am|i'm)\s+([a-zA-Z]+)", text_lower)
83
+ if name_match:
84
+ memory["user_profile"]["name"] = name_match.group(1).title()
85
+ age_match = re.search(r"(?:i am|i'm)\s+(\d+)", text_lower)
86
+ if age_match:
87
+ memory["user_profile"]["age"] = age_match.group(1)
88
+ color_match = re.search(r"favorite color is\s+([a-zA-Z]+)", text_lower)
89
+ if color_match:
90
+ memory["user_profile"]["favorite_color"] = color_match.group(1)
91
+ return memory
92
+
93
+
94
+ def build_memory_context(memory):
95
+ profile = memory.get("user_profile", {})
96
+ if not profile:
97
+ return "No stored user information."
98
+ return "\n".join(f"{k}: {v}" for k, v in profile.items())
99
+
100
+
101
+ def load_file_context(user_id, max_files=3):
102
+ from models.upload import Upload
103
+ from services.document_service import extract_text
104
+ uploads = Upload.query.filter_by(user_id=user_id)\
105
+ .filter(Upload.file_type.in_(["text", "pdf", "document"]))\
106
+ .order_by(Upload.created_at.desc()).limit(max_files).all()
107
+ if not uploads:
108
+ return ""
109
+ parts = []
110
+ for u in uploads:
111
+ content, err = extract_text(u.path, u.file_type)
112
+ if content:
113
+ truncated = content[:2000]
114
+ parts.append(f"[Uploaded File: {u.original_name}]\n{truncated}\n")
115
+ if not parts:
116
+ return ""
117
+ return "Recent uploaded files:\n" + "\n---\n".join(parts)
118
+
119
+
120
+ def is_image_request(text):
121
+ text = text.lower()
122
+ keywords = [
123
+ "generate image", "generate an image", "create image",
124
+ "create an image", "make image", "make an image", "draw",
125
+ "image of", "photo of", "picture of",
126
+ "generate a picture", "create a picture", "make a picture"
127
+ ]
128
+ return any(k in text for k in keywords)
129
+
130
+
131
+ def clean_image_prompt(prompt):
132
+ prompt = prompt.lower()
133
+ replacements = [
134
+ "generate image of", "generate an image of", "create image of",
135
+ "create an image of", "make image of", "make an image of",
136
+ "generate a picture of", "create a picture of", "make a picture of",
137
+ "draw", "picture of", "photo of"
138
+ ]
139
+ for item in replacements:
140
+ prompt = prompt.replace(item, "")
141
+ return prompt.strip()
142
+
143
+
144
+ def generate_image_openrouter(prompt):
145
+ try:
146
+ cleaned = clean_image_prompt(prompt)
147
+ resp, code = _api_call({
148
+ "model": "black-forest-labs/flux.2-flex",
149
+ "messages": [{"role": "user", "content": cleaned}],
150
+ "modalities": ["image"],
151
+ "max_tokens": MAX_TOKENS
152
+ }, timeout=120)
153
+ if not resp:
154
+ return None
155
+ data = resp.json()
156
+ content = data.get("choices", [{}])[0].get("message", {}).get("content", [])
157
+ image_url = None
158
+ if isinstance(content, list):
159
+ for part in content:
160
+ if isinstance(part, dict) and part.get("type") == "image_url":
161
+ image_url = part["image_url"]["url"]
162
+ break
163
+ elif isinstance(content, str):
164
+ image_url = content
165
+ if image_url:
166
+ if image_url.startswith("data:image"):
167
+ _, encoded = image_url.split(",", 1)
168
+ image_bytes = base64.b64decode(encoded)
169
+ else:
170
+ img_resp = _http.get(image_url, timeout=30)
171
+ image_bytes = img_resp.content
172
+ filename = f"generated_{int(datetime.now().timestamp())}.png"
173
+ image_path = os.path.join(OUTPUT_DIR, filename)
174
+ with open(image_path, "wb") as f:
175
+ f.write(image_bytes)
176
+ return {"type": "generated_image", "path": f"/api/images/outputs/{filename}"}
177
+ return None
178
+ except Exception as e:
179
+ log.error("OpenRouter image failed: %s", e)
180
+ return None
181
+
182
+
183
+ def generate_image_hf(prompt):
184
+ try:
185
+ cleaned = clean_image_prompt(prompt)
186
+ hf_token = os.getenv("HF_TOKEN")
187
+ if not hf_token:
188
+ log.warning("HF_TOKEN not set, skipping HF fallback")
189
+ return None
190
+ resp = _http.post(
191
+ "https://router.huggingface.co/hf-inference/models/black-forest-labs/FLUX.1-schnell",
192
+ headers={"Authorization": f"Bearer {hf_token}"},
193
+ json={"inputs": cleaned},
194
+ timeout=120
195
+ )
196
+ if resp.status_code == 200:
197
+ filename = f"generated_{int(datetime.now().timestamp())}.png"
198
+ image_path = os.path.join(OUTPUT_DIR, filename)
199
+ with open(image_path, "wb") as f:
200
+ f.write(resp.content)
201
+ return {"type": "generated_image", "path": f"/api/images/outputs/{filename}"}
202
+ log.error("HF Error %d", resp.status_code)
203
+ return None
204
+ except Exception as e:
205
+ log.error("HF image failed: %s", e)
206
+ return None
207
+
208
+
209
+ def generate_image(prompt):
210
+ result = generate_image_openrouter(prompt)
211
+ if result:
212
+ return result
213
+ log.info("OpenRouter failed, trying HuggingFace...")
214
+ result = generate_image_hf(prompt)
215
+ if result:
216
+ return result
217
+ return {"type": "text", "content": "Image generation failed. Check API keys."}
218
+
219
+
220
+ def chat_completion(messages, model="openrouter/free"):
221
+ for m in messages:
222
+ if isinstance(m.get("content"), str) and len(m["content"]) > MAX_INPUT_TOKENS:
223
+ m["content"] = m["content"][:MAX_INPUT_TOKENS]
224
+
225
+ fallback_models = [model, "openrouter/auto", "openrouter/free"]
226
+
227
+ for mdl in fallback_models:
228
+ try:
229
+ payload = {"model": mdl, "messages": messages, "max_tokens": MAX_TOKENS}
230
+ resp, code = _api_call(payload, timeout=30)
231
+ if not resp:
232
+ log.warning("Model %s failed, trying fallback", mdl)
233
+ continue
234
+ return resp.json()["choices"][0]["message"]["content"]
235
+ except Exception as e:
236
+ log.warning("Model %s error: %s", mdl, e)
237
+ continue
238
+ return None
239
+
240
+
241
+ def chat_completion_stream(messages, model="openrouter/free"):
242
+ for m in messages:
243
+ if isinstance(m.get("content"), str) and len(m["content"]) > MAX_INPUT_TOKENS:
244
+ m["content"] = m["content"][:MAX_INPUT_TOKENS]
245
+
246
+ try:
247
+ payload = {"model": model, "messages": messages, "stream": True, "max_tokens": MAX_TOKENS}
248
+ resp, code = _api_call(payload, stream=True, timeout=60)
249
+ if not resp:
250
+ yield None
251
+ return
252
+
253
+ for line in resp.iter_lines():
254
+ if not line:
255
+ continue
256
+ if line.startswith(b"data: "):
257
+ data_str = line[6:].decode("utf-8").strip()
258
+ if data_str == "[DONE]":
259
+ break
260
+ try:
261
+ chunk = json.loads(data_str)
262
+ delta = chunk.get("choices", [{}])[0].get("delta", {})
263
+ content = delta.get("content", "")
264
+ if content:
265
+ yield content
266
+ except json.JSONDecodeError:
267
+ continue
268
+ except Exception as e:
269
+ log.error("Stream failed: %s", e)
270
+ yield None
271
+
272
+
273
+ def handle_memory_command(text, user_id):
274
+ text_lower = text.lower().strip()
275
+
276
+ remember_match = re.search(
277
+ r"(?:remember(?: that)?)\s+(?:my\s+)?(.+?)\s+(?:is|are|was)\s+(.+)",
278
+ text_lower
279
+ )
280
+ if remember_match:
281
+ key = remember_match.group(1).strip().title()
282
+ value = remember_match.group(2).strip()
283
+ existing = Memory.query.filter_by(user_id=user_id, key=key).first()
284
+ if existing:
285
+ existing.value = value
286
+ else:
287
+ mem = Memory(user_id=user_id, key=key, value=value)
288
+ db.session.add(mem)
289
+ db.session.commit()
290
+ return {"type": "text", "content": f"Got it! I'll remember that your {key} is {value}."}
291
+
292
+ forget_match = re.search(
293
+ r"(?:forget|delete memory|remove memory)\s+(?:my\s+)?(.+)",
294
+ text_lower
295
+ )
296
+ if forget_match:
297
+ key_to_forget = forget_match.group(1).strip().title()
298
+ mem = Memory.query.filter_by(user_id=user_id, key=key_to_forget).first()
299
+ if mem:
300
+ db.session.delete(mem)
301
+ db.session.commit()
302
+ return {"type": "text", "content": f"Forgot your {key_to_forget}. It's been removed from memory."}
303
+ memories = Memory.query.filter(
304
+ Memory.user_id == user_id,
305
+ Memory.key.ilike(f"%{key_to_forget}%")
306
+ ).all()
307
+ if memories:
308
+ for m in memories:
309
+ db.session.delete(m)
310
+ db.session.commit()
311
+ return {"type": "text", "content": f"Forgot {len(memories)} memory/memories matching '{key_to_forget}'."}
312
+ return {"type": "text", "content": f"I don't have anything stored about '{key_to_forget}'."}
313
+
314
+ clear_match = re.search(r"(?:clear all memory|forget everything|reset memory)", text_lower)
315
+ if clear_match:
316
+ Memory.query.filter_by(user_id=user_id).delete()
317
+ db.session.commit()
318
+ return {"type": "text", "content": "All memories cleared."}
319
+
320
+ what_match = re.search(r"(?:what do you know about me|what do you remember|show memory|list memory)", text_lower)
321
+ if what_match:
322
+ memories = Memory.query.filter_by(user_id=user_id).all()
323
+ if not memories:
324
+ return {"type": "text", "content": "I don't have any memories stored about you yet."}
325
+ lines = [f"{m.key}: {m.value}" for m in memories]
326
+ return {"type": "text", "content": "Here's what I remember:\n" + "\n".join(lines)}
327
+
328
+ return None
329
+
330
+
331
+ def jarvis_reply(user_text, user_id, model="openrouter/free"):
332
+ try:
333
+ memory = load_memory_from_db(user_id)
334
+ memory = extract_user_info(user_text, memory)
335
+ save_memory_to_db(user_id, memory)
336
+
337
+ if is_image_request(user_text):
338
+ return generate_image(user_text)
339
+
340
+ from models.message import Message
341
+ recent = Message.query.filter_by(user_id=user_id)\
342
+ .order_by(Message.created_at.desc()).limit(6).all()
343
+ recent.reverse()
344
+
345
+ memory_context = build_memory_context(memory)
346
+ file_context = load_file_context(user_id)
347
+ system_prompt = f"""You are Nexus AI. You are futuristic, intelligent, helpful, and concise.
348
+
349
+ Known User Information:
350
+ {memory_context}
351
+
352
+ {file_context}"""
353
+
354
+ messages = [{"role": "system", "content": system_prompt}]
355
+ for msg in recent:
356
+ messages.append({"role": msg.role, "content": msg.content})
357
+
358
+ ai_reply = chat_completion(messages, model=model)
359
+
360
+ if ai_reply is None:
361
+ return {
362
+ "type": "text",
363
+ "content": "Nexus text AI is unavailable (OpenRouter credits needed)."
364
+ }
365
+
366
+ return {"type": "text", "content": ai_reply}
367
+
368
+ except Exception as e:
369
+ log.error("NEXUS ERROR: %s", e)
370
+ return {"type": "text", "content": "AI error occurred."}
app.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import secrets
2
+ import logging
3
+ import sys
4
+ from flask import Flask, request, jsonify, session, abort
5
+ from flask_socketio import SocketIO
6
+ from flask_cors import CORS
7
+ from dotenv import load_dotenv
8
+ import os
9
+ from datetime import timedelta
10
+ from database import db, init_db
11
+ from socket_handlers import register_socket_handlers
12
+
13
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
14
+ log = logging.getLogger(__name__)
15
+
16
+ load_dotenv()
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Startup validation — fail fast on missing required configuration
20
+ # ---------------------------------------------------------------------------
21
+ REQUIRED_ENV_VARS = ["OPENROUTER_API_KEY"]
22
+ _missing = [v for v in REQUIRED_ENV_VARS if not os.getenv(v)]
23
+ if _missing:
24
+ log.critical("Missing required environment variables: %s", ", ".join(_missing))
25
+ log.critical("Set them in .env or in the deployment environment.")
26
+ sys.exit(1)
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Flask application configuration
30
+ # ---------------------------------------------------------------------------
31
+ app = Flask(__name__)
32
+ app.config["SECRET_KEY"] = os.getenv("SECRET_KEY") or secrets.token_hex(32)
33
+ app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL", "sqlite:///nexus.db")
34
+ app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
35
+ app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
36
+ app.config["SESSION_COOKIE_HTTPONLY"] = True
37
+ app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
38
+ app.config["SESSION_COOKIE_SECURE"] = os.getenv("SESSION_COOKIE_SECURE", "False").lower() in ("true", "1", "yes")
39
+ app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(hours=int(os.getenv("SESSION_LIFETIME_HOURS", "24")))
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # CORS — refuse wildcard when credentials are enabled
43
+ # ---------------------------------------------------------------------------
44
+ _cors_origins_raw = os.getenv("CORS_ORIGINS", "")
45
+ if not _cors_origins_raw:
46
+ log.critical("CORS_ORIGINS environment variable is required in production. "
47
+ "Set it to your frontend domain (e.g. https://example.com).")
48
+ sys.exit(1)
49
+ cors_origins = [o.strip() for o in _cors_origins_raw.split(",") if o.strip()]
50
+ if "*" in cors_origins:
51
+ log.critical("CORS_ORIGINS must not be '*' when credentials are enabled. "
52
+ "Specify explicit origins (comma-separated).")
53
+ sys.exit(1)
54
+ CORS(app, supports_credentials=True, origins=cors_origins)
55
+
56
+ # Security headers
57
+ @app.after_request
58
+ def security_headers(response):
59
+ response.headers["X-Content-Type-Options"] = "nosniff"
60
+ response.headers["X-Frame-Options"] = "SAMEORIGIN"
61
+ response.headers["X-XSS-Protection"] = "1; mode=block"
62
+ response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
63
+ response.headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://cdn.socket.io 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' http://127.0.0.1:5000 ws://127.0.0.1:5000 ws: wss: https://cdn.socket.io; media-src 'self' data: blob: mediastream:"
64
+ return response
65
+
66
+ # Rate limiting — periodic cleanup prevents unbounded memory growth
67
+ import time as _time
68
+ _rate_limit_store = {}
69
+ _RATE_LIMIT_CLEANUP_INTERVAL = 300
70
+ _rate_limit_last_cleanup = 0.0
71
+
72
+ def _rate_limit_cleanup():
73
+ global _rate_limit_last_cleanup
74
+ now = _time.time()
75
+ if now - _rate_limit_last_cleanup < _RATE_LIMIT_CLEANUP_INTERVAL:
76
+ return
77
+ _rate_limit_last_cleanup = now
78
+ cutoff = now - 120
79
+ expired = [k for k, v in _rate_limit_store.items() if v and v[-1] < cutoff]
80
+ for k in expired:
81
+ del _rate_limit_store[k]
82
+
83
+ def rate_limit(key, max_requests=10, window=60):
84
+ now = _time.time()
85
+ _rate_limit_cleanup()
86
+ if key not in _rate_limit_store:
87
+ _rate_limit_store[key] = []
88
+ _rate_limit_store[key] = [t for t in _rate_limit_store[key] if now - t < window]
89
+ if len(_rate_limit_store[key]) >= max_requests:
90
+ return True
91
+ _rate_limit_store[key].append(now)
92
+ return False
93
+
94
+ @app.before_request
95
+ def global_rate_limit():
96
+ if request.path.startswith("/api/auth/login") or request.path.startswith("/api/auth/signup"):
97
+ ip = request.remote_addr or "unknown"
98
+ limited = rate_limit(f"auth:{ip}", max_requests=20, window=60)
99
+ if limited:
100
+ abort(429, description="Too many requests. Try again later.")
101
+
102
+ # CSRF protection — enforced on all mutating requests except GET/HEAD/OPTIONS/TRACE
103
+ @app.before_request
104
+ def csrf_check():
105
+ if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"):
106
+ return
107
+ if request.path.startswith("/socket.io/"):
108
+ return
109
+ csrf_token = request.headers.get("X-CSRF-Token")
110
+ session_csrf = session.get("csrf_token")
111
+ if not csrf_token or not session_csrf or csrf_token != session_csrf:
112
+ abort(403, description="CSRF validation failed")
113
+
114
+ @app.before_request
115
+ def ensure_csrf_token():
116
+ if "csrf_token" not in session:
117
+ session["csrf_token"] = secrets.token_hex(32)
118
+
119
+ @app.after_request
120
+ def set_csrf_cookie(response):
121
+ if "csrf_token" in session:
122
+ response.set_cookie(
123
+ "csrf_token", session["csrf_token"],
124
+ httponly=False, samesite="Lax", secure=app.config["SESSION_COOKIE_SECURE"],
125
+ max_age=timedelta(hours=24)
126
+ )
127
+ return response
128
+
129
+ # Socket.IO — detect eventlet under gunicorn, fall back to threading on Windows/dev
130
+ _IS_WINDOWS = os.name == "nt"
131
+ _sio_async_mode = os.getenv("SOCKET_ASYNC_MODE", "threading" if _IS_WINDOWS else "eventlet")
132
+ log.info("Socket.IO async_mode=%s (OS: %s)", _sio_async_mode, "Windows" if _IS_WINDOWS else "Linux")
133
+ socketio = SocketIO(app, cors_allowed_origins=cors_origins, async_mode=_sio_async_mode)
134
+ init_db(app)
135
+ register_socket_handlers(socketio)
136
+
137
+ from routes.auth_routes import auth_bp
138
+ from routes.chat_routes import chat_bp
139
+ from routes.memory_routes import memory_bp
140
+ from routes.image_routes import image_bp
141
+ from routes.settings_routes import settings_bp
142
+ from routes.upload_routes import upload_bp
143
+ from routes.scene_routes import scene_bp
144
+ from routes.page_routes import pages_bp
145
+ from socket_handlers.camera_handler import _camera_thread
146
+
147
+ @app.route("/api/camera/status")
148
+ def camera_status():
149
+ alive = _camera_thread is not None and _camera_thread.is_alive()
150
+ return jsonify({"running": alive})
151
+
152
+ app.register_blueprint(pages_bp)
153
+ app.register_blueprint(auth_bp)
154
+ app.register_blueprint(chat_bp)
155
+ app.register_blueprint(memory_bp)
156
+ app.register_blueprint(image_bp)
157
+ app.register_blueprint(settings_bp)
158
+ app.register_blueprint(upload_bp)
159
+ app.register_blueprint(scene_bp)
160
+
161
+ if __name__ == "__main__":
162
+ os.makedirs("outputs", exist_ok=True)
163
+ os.makedirs("uploads", exist_ok=True)
164
+
165
+ log.info("NEXUS AI starting on %s:%s", os.getenv("HOST", "0.0.0.0"), os.getenv("PORT", "5000"))
166
+ socketio.run(app, host=os.getenv("HOST", "0.0.0.0"), port=int(os.getenv("PORT", 5000)), debug=False)
camera_service.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import mediapipe as mp
3
+ import base64
4
+ import time
5
+ import logging
6
+ from services.hand_service import hand_data_from_landmarks, two_hand_scale, detect_swipe
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+ mp_pose = mp.solutions.pose
11
+ mp_hands = mp.solutions.hands
12
+
13
+ pose = mp_pose.Pose(
14
+ min_detection_confidence=0.5,
15
+ min_tracking_confidence=0.5
16
+ )
17
+
18
+ hands = mp_hands.Hands(
19
+ max_num_hands=2,
20
+ min_detection_confidence=0.7,
21
+ min_tracking_confidence=0.7
22
+ )
23
+
24
+
25
+ def start_camera(socketio, stop_event=None):
26
+ log.info("Starting camera thread...")
27
+
28
+ try:
29
+ try:
30
+ cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
31
+ except AttributeError:
32
+ log.info("CAP_DSHOW not available, using default backend")
33
+ cap = cv2.VideoCapture(0)
34
+
35
+ cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
36
+ cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
37
+ cap.set(cv2.CAP_PROP_FPS, 15)
38
+
39
+ if not cap.isOpened():
40
+ log.error("Camera not available (cv2.VideoCapture(0) failed)")
41
+ socketio.emit("camera_error", {"message": "Camera not available"})
42
+ return
43
+ log.info("Camera opened successfully")
44
+
45
+ frame_count = 0
46
+ hand_histories = {}
47
+ read_failures = 0
48
+
49
+ while not (stop_event and stop_event.is_set()):
50
+ try:
51
+ success, frame = cap.read()
52
+ except Exception as e:
53
+ log.error("Camera read error: %s", e)
54
+ read_failures += 1
55
+ if read_failures > 30:
56
+ break
57
+ time.sleep(0.5)
58
+ continue
59
+
60
+ if not success:
61
+ read_failures += 1
62
+ if read_failures > 30:
63
+ log.error("Camera read failed 30 times, giving up")
64
+ break
65
+ time.sleep(0.5)
66
+ continue
67
+ read_failures = 0
68
+
69
+ frame = cv2.flip(frame, 1)
70
+ rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
71
+ frame_count += 1
72
+
73
+ if frame_count % 2 != 0:
74
+ continue
75
+
76
+ pose_results = pose.process(rgb)
77
+ landmarks = []
78
+ if pose_results.pose_landmarks:
79
+ for lm in pose_results.pose_landmarks.landmark:
80
+ landmarks.append({"x": lm.x, "y": lm.y, "z": lm.z})
81
+ socketio.emit("pose_data", {"landmarks": landmarks})
82
+
83
+ hand_results = hands.process(rgb)
84
+ detected_hands = []
85
+ hand_count = 0
86
+
87
+ if hand_results.multi_hand_landmarks:
88
+ hand_count = len(hand_results.multi_hand_landmarks)
89
+ for i, hand_landmarks in enumerate(hand_results.multi_hand_landmarks):
90
+ label = ["Right", "Left"][i] if i < 2 else "Unknown"
91
+ idx_x = hand_landmarks.landmark[8].x
92
+ if i not in hand_histories:
93
+ hand_histories[i] = []
94
+ hand_histories[i].append(idx_x)
95
+ if len(hand_histories[i]) > 8:
96
+ hand_histories[i].pop(0)
97
+ data = hand_data_from_landmarks(
98
+ hand_landmarks, handedness=label, history=hand_histories[i]
99
+ )
100
+ detected_hands.append(data)
101
+ socketio.emit("hand_data", data)
102
+
103
+ if hand_count == 2:
104
+ h1 = hand_results.multi_hand_landmarks[0]
105
+ h2 = hand_results.multi_hand_landmarks[1]
106
+ dist = two_hand_scale(h1, h2)
107
+ if "scale_history" not in hand_histories:
108
+ hand_histories["scale_history"] = []
109
+ hand_histories["scale_history"].append(dist)
110
+ if len(hand_histories["scale_history"]) > 5:
111
+ hand_histories["scale_history"].pop(0)
112
+ scale_delta = 1.0
113
+ if len(hand_histories["scale_history"]) >= 3:
114
+ prev = hand_histories["scale_history"][-3]
115
+ curr = hand_histories["scale_history"][-1]
116
+ change = curr - prev
117
+ scale_delta = 1.0 + (change * 3.0)
118
+ scale_delta = max(0.5, min(2.0, scale_delta))
119
+ h1_idx = h1.landmark[8]
120
+ h2_idx = h2.landmark[8]
121
+ avg_x = (h1_idx.x + h2_idx.x) / 2
122
+ if "both_x_history" not in hand_histories:
123
+ hand_histories["both_x_history"] = []
124
+ hand_histories["both_x_history"].append(avg_x)
125
+ if len(hand_histories["both_x_history"]) > 5:
126
+ hand_histories["both_x_history"].pop(0)
127
+ both_swipe = detect_swipe(hand_histories["both_x_history"], threshold=0.008)
128
+ socketio.emit("two_hand_data", {
129
+ "scale": round(dist, 4), "scale_delta": round(scale_delta, 3),
130
+ "swipe": both_swipe
131
+ })
132
+
133
+ if hand_count == 1 and detected_hands:
134
+ d = detected_hands[0]
135
+ if d["swipe"]:
136
+ socketio.emit("swipe_data", {
137
+ "direction": d["swipe"], "handedness": d["handedness"]
138
+ })
139
+
140
+ if pose_results.pose_landmarks:
141
+ mp.solutions.drawing_utils.draw_landmarks(
142
+ frame, pose_results.pose_landmarks, mp_pose.POSE_CONNECTIONS
143
+ )
144
+ if hand_results.multi_hand_landmarks:
145
+ for hl in hand_results.multi_hand_landmarks:
146
+ mp.solutions.drawing_utils.draw_landmarks(
147
+ frame, hl, mp_hands.HAND_CONNECTIONS
148
+ )
149
+
150
+ if frame_count % 4 == 0:
151
+ _, buffer = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 70])
152
+ frame_b64 = base64.b64encode(buffer).decode("utf-8")
153
+ socketio.emit("camera_frame", {"frame": frame_b64})
154
+
155
+ cap.release()
156
+ log.info("Camera released")
157
+ except Exception as e:
158
+ log.error("Camera thread crashed: %s", type(e).__name__, exc_info=True)
database/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask_sqlalchemy import SQLAlchemy
2
+ from flask_migrate import Migrate
3
+
4
+ db = SQLAlchemy()
5
+ migrate = Migrate()
6
+
7
+
8
+ def init_db(app):
9
+ db.init_app(app)
10
+ migrate.init_app(app, db)
11
+ with app.app_context():
12
+ import models
13
+ db.create_all()
image.png ADDED
memory.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "user_profile": {},
3
+ "conversation_history": [
4
+ {
5
+ "role": "assistant",
6
+ "content": "\nDonald Trump is the 45th and current President of the United States, serving from 2017 to 2021 (and re-elected in 2024). He is a businessman, television personality, and politician known for his leadership of the Trump Organization and his role as host of the reality show *The Apprentice*. As president, he implemented policies including tax cuts, deregulation, and a focus on \"America First\" trade and immigration policies. His presidency was marked by controversy, including impeachments by the House (though acquitted by the Senate), debates over election integrity, and significant political polarization. He remains a prominent and polarizing figure in U.S. politics. Let me know if you'd like more details!\n"
7
+ },
8
+ {
9
+ "role": "user",
10
+ "content": "hello"
11
+ },
12
+ {
13
+ "role": "assistant",
14
+ "content": "Hello! How can I assist you today? 😊\n"
15
+ },
16
+ {
17
+ "role": "user",
18
+ "content": "generate an image of a concer"
19
+ },
20
+ {
21
+ "role": "user",
22
+ "content": "hi"
23
+ },
24
+ {
25
+ "role": "assistant",
26
+ "content": "Sure! Could you let me know what kind of concert you’d like the image to depict? For example, the genre (rock, jazz, classical), the setting (indoor arena, outdoor festival, club), the vibe (bright lights, smoky ambiance, minimalist stage), or any specific details you want included? that way I can create the perfect concept for you."
27
+ }
28
+ ]
29
+ }
memory/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
models/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from models.user import User
2
+ from models.chat import Chat
3
+ from models.message import Message
4
+ from models.memory import Memory
5
+ from models.setting import Setting
6
+ from models.generated_image import GeneratedImage
7
+ from models.upload import Upload
8
+ from models.scene import Scene
9
+
10
+ __all__ = [
11
+ "User", "Chat", "Message", "Memory",
12
+ "Setting", "GeneratedImage", "Upload", "Scene"
13
+ ]
models/chat.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ class Chat(db.Model):
6
+ __tablename__ = "chats"
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
10
+ title = db.Column(db.String(200), default="New Chat")
11
+ model = db.Column(db.String(50), default="openrouter/free")
12
+ created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), index=True)
13
+ updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), index=True)
14
+
15
+ messages = db.relationship("Message", backref="chat", lazy="dynamic", cascade="all, delete-orphan",
16
+ order_by="Message.created_at")
17
+
18
+ def to_dict(self):
19
+ return {
20
+ "id": self.id,
21
+ "title": self.title,
22
+ "model": self.model,
23
+ "created_at": self.created_at.isoformat() if self.created_at else None,
24
+ "updated_at": self.updated_at.isoformat() if self.updated_at else None,
25
+ "message_count": self.messages.count()
26
+ }
models/generated_image.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ class GeneratedImage(db.Model):
6
+ __tablename__ = "generated_images"
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
10
+ prompt = db.Column(db.Text, nullable=False)
11
+ model = db.Column(db.String(50), default="openrouter")
12
+ path = db.Column(db.String(500), nullable=False)
13
+ created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), index=True)
14
+
15
+ def to_dict(self):
16
+ return {
17
+ "id": self.id,
18
+ "prompt": self.prompt,
19
+ "model": self.model,
20
+ "path": self.path,
21
+ "created_at": self.created_at.isoformat() if self.created_at else None
22
+ }
models/memory.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ class Memory(db.Model):
6
+ __tablename__ = "memories"
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
10
+ key = db.Column(db.String(200), nullable=False, index=True)
11
+ value = db.Column(db.Text, nullable=False)
12
+ created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
13
+ updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
14
+
15
+ def to_dict(self):
16
+ return {
17
+ "id": self.id,
18
+ "key": self.key,
19
+ "value": self.value,
20
+ "created_at": self.created_at.isoformat() if self.created_at else None,
21
+ "updated_at": self.updated_at.isoformat() if self.updated_at else None
22
+ }
models/message.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ class Message(db.Model):
6
+ __tablename__ = "messages"
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ chat_id = db.Column(db.Integer, db.ForeignKey("chats.id", ondelete="CASCADE"), nullable=False, index=True)
10
+ user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
11
+ role = db.Column(db.String(20), nullable=False)
12
+ content = db.Column(db.Text, nullable=False)
13
+ message_type = db.Column(db.String(20), default="text")
14
+ created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
15
+
16
+ def to_dict(self):
17
+ return {
18
+ "id": self.id,
19
+ "chat_id": self.chat_id,
20
+ "role": self.role,
21
+ "content": self.content,
22
+ "message_type": self.message_type,
23
+ "created_at": self.created_at.isoformat() if self.created_at else None
24
+ }
models/scene.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ class Scene(db.Model):
6
+ __tablename__ = "scenes"
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
10
+ name = db.Column(db.String(200), default="Untitled Scene")
11
+ data = db.Column(db.Text, nullable=False)
12
+ created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
13
+ updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
14
+
15
+ def to_dict(self):
16
+ return {
17
+ "id": self.id,
18
+ "name": self.name,
19
+ "data": self.data,
20
+ "created_at": self.created_at.isoformat() if self.created_at else None,
21
+ "updated_at": self.updated_at.isoformat() if self.updated_at else None
22
+ }
models/setting.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+
3
+
4
+ class Setting(db.Model):
5
+ __tablename__ = "settings"
6
+
7
+ id = db.Column(db.Integer, primary_key=True)
8
+ user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
9
+ key = db.Column(db.String(100), nullable=False)
10
+ value = db.Column(db.Text, nullable=True)
11
+
12
+ __table_args__ = (db.UniqueConstraint("user_id", "key"),)
13
+
14
+ def to_dict(self):
15
+ return {"key": self.key, "value": self.value}
models/upload.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ class Upload(db.Model):
6
+ __tablename__ = "uploads"
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
10
+ filename = db.Column(db.String(300), nullable=False)
11
+ original_name = db.Column(db.String(300), nullable=False)
12
+ path = db.Column(db.String(500), nullable=False)
13
+ file_type = db.Column(db.String(50), default="unknown")
14
+ size = db.Column(db.Integer, default=0)
15
+ created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), index=True)
16
+
17
+ def to_dict(self):
18
+ return {
19
+ "id": self.id,
20
+ "filename": self.filename,
21
+ "original_name": self.original_name,
22
+ "file_type": self.file_type,
23
+ "size": self.size,
24
+ "created_at": self.created_at.isoformat() if self.created_at else None
25
+ }
models/user.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from database import db
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ class User(db.Model):
6
+ __tablename__ = "users"
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ username = db.Column(db.String(80), unique=True, nullable=False)
10
+ email = db.Column(db.String(120), unique=True, nullable=True)
11
+ password_hash = db.Column(db.String(256), nullable=False)
12
+ avatar_url = db.Column(db.String(500), default="")
13
+ theme = db.Column(db.String(20), default="dark")
14
+ created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
15
+
16
+ chats = db.relationship("Chat", backref="user", lazy="dynamic", cascade="all, delete-orphan")
17
+ memories = db.relationship("Memory", backref="user", lazy="dynamic", cascade="all, delete-orphan")
18
+ settings = db.relationship("Setting", backref="user", lazy="dynamic", cascade="all, delete-orphan")
19
+ images = db.relationship("GeneratedImage", backref="user", lazy="dynamic", cascade="all, delete-orphan")
20
+ uploads = db.relationship("Upload", backref="user", lazy="dynamic", cascade="all, delete-orphan")
21
+ scenes = db.relationship("Scene", backref="user", lazy="dynamic", cascade="all, delete-orphan")
22
+
23
+ def to_dict(self):
24
+ return {
25
+ "id": self.id,
26
+ "username": self.username,
27
+ "email": self.email,
28
+ "avatar_url": self.avatar_url,
29
+ "theme": self.theme,
30
+ "created_at": self.created_at.isoformat() if self.created_at else None
31
+ }
railway.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "build": {
3
+ "builder": "NIXPACKS",
4
+ "buildCommand": "pip install -r requirements.txt"
5
+ },
6
+ "deploy": {
7
+ "startCommand": "gunicorn -k eventlet -w 1 --bind 0.0.0.0:$PORT wsgi:app",
8
+ "healthcheckPath": "/",
9
+ "healthcheckTimeout": 30,
10
+ "restartPolicyType": "always"
11
+ }
12
+ }
requirements.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flask>=3.0
2
+ Flask-SocketIO>=5.3
3
+ Flask-CORS>=4.0
4
+ Flask-SQLAlchemy>=3.1
5
+ Flask-Migrate>=4.0
6
+ python-dotenv>=1.0
7
+ SQLAlchemy>=2.0
8
+ requests>=2.31
9
+ bcrypt>=4.0
10
+ PyPDF2>=3.0
11
+ python-docx>=1.1
12
+ Pillow>=10.0
13
+ gunicorn>=21.2
14
+ eventlet>=0.33
15
+
16
+ # Camera & Motion Capture (optional - set DISABLE_CAMERA=1 on headless)
17
+ opencv-python>=4.8
18
+ mediapipe>=0.10
19
+
20
+ # Voice (optional - set DISABLE_VOICE=1 on headless)
21
+ SpeechRecognition>=3.8
22
+ PyAudio>=0.2
routes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
routes/auth_routes.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from flask import Blueprint, request, jsonify, g, session
3
+ from database import db
4
+ from models.user import User
5
+ from services.auth_service import hash_password, check_password
6
+ from routes.middleware import login_required
7
+
8
+ auth_bp = Blueprint("auth", __name__, url_prefix="/api/auth")
9
+
10
+
11
+ def validate_password(password):
12
+ if len(password) < 8:
13
+ return "Password must be at least 8 characters"
14
+ if not re.search(r"[A-Z]", password):
15
+ return "Password must contain an uppercase letter"
16
+ if not re.search(r"[a-z]", password):
17
+ return "Password must contain a lowercase letter"
18
+ if not re.search(r"\d", password):
19
+ return "Password must contain a digit"
20
+ return None
21
+
22
+
23
+ @auth_bp.route("/signup", methods=["POST"])
24
+ def signup():
25
+ data = request.get_json() or {}
26
+ username = data.get("username", "").strip()
27
+ password = data.get("password", "")
28
+
29
+ if len(username) < 3:
30
+ return jsonify({"error": "Username must be at least 3 characters"}), 400
31
+ pw_error = validate_password(password)
32
+ if pw_error:
33
+ return jsonify({"error": pw_error}), 400
34
+
35
+ if User.query.filter_by(username=username).first():
36
+ return jsonify({"error": "Username already taken"}), 409
37
+
38
+ user = User(
39
+ username=username,
40
+ password_hash=hash_password(password)
41
+ )
42
+ db.session.add(user)
43
+ db.session.commit()
44
+
45
+ session["user_id"] = user.id
46
+ session.permanent = True
47
+ return jsonify({"user": user.to_dict()}), 201
48
+
49
+
50
+ @auth_bp.route("/login", methods=["POST"])
51
+ def login():
52
+ data = request.get_json() or {}
53
+ username = data.get("username", "").strip()
54
+ password = data.get("password", "")
55
+
56
+ user = User.query.filter_by(username=username).first()
57
+ if not user or not check_password(password, user.password_hash):
58
+ return jsonify({"error": "Invalid username or password"}), 401
59
+
60
+ session["user_id"] = user.id
61
+ session.permanent = True
62
+ return jsonify({"user": user.to_dict()})
63
+
64
+
65
+ @auth_bp.route("/me", methods=["GET"])
66
+ def get_me():
67
+ user_id = session.get("user_id")
68
+ if not user_id:
69
+ return jsonify({"error": "Not authenticated"}), 401
70
+ user = User.query.get(user_id)
71
+ if not user:
72
+ session.clear()
73
+ return jsonify({"error": "User not found"}), 404
74
+ return jsonify({"user": user.to_dict()})
75
+
76
+
77
+ @auth_bp.route("/logout", methods=["POST"])
78
+ def logout():
79
+ session.clear()
80
+ return jsonify({"message": "Logged out successfully"})
routes/chat_routes.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from datetime import datetime, timezone
4
+ import traceback
5
+ from flask import Blueprint, request, jsonify, g, Response
6
+ from database import db
7
+ from models.chat import Chat
8
+ from models.message import Message
9
+ from routes.middleware import login_required
10
+ from ai.jarvis_core import jarvis_reply, chat_completion_stream, load_memory_from_db, save_memory_to_db, extract_user_info, is_image_request, generate_image, handle_memory_command, load_file_context
11
+ from models.generated_image import GeneratedImage
12
+
13
+ chat_bp = Blueprint("chat", __name__, url_prefix="/api/chat")
14
+
15
+
16
+ @chat_bp.route("/chats", methods=["GET"])
17
+ @login_required
18
+ def list_chats():
19
+ from sqlalchemy import func
20
+ from models.message import Message
21
+ subq = db.session.query(Message.chat_id, func.count(Message.id).label("cnt"))\
22
+ .group_by(Message.chat_id).subquery()
23
+ rows = db.session.query(Chat, subq.c.cnt)\
24
+ .outerjoin(subq, subq.c.chat_id == Chat.id)\
25
+ .filter(Chat.user_id == g.current_user.id)\
26
+ .order_by(Chat.updated_at.desc()).all()
27
+ result = []
28
+ for chat, cnt in rows:
29
+ d = chat.to_dict()
30
+ d["message_count"] = cnt if cnt is not None else 0
31
+ result.append(d)
32
+ return jsonify({"chats": result})
33
+
34
+
35
+ @chat_bp.route("/chats", methods=["POST"])
36
+ @login_required
37
+ def create_chat():
38
+ data = request.get_json() or {}
39
+ chat = Chat(
40
+ user_id=g.current_user.id,
41
+ title=data.get("title", "New Chat"),
42
+ model=data.get("model", "openrouter/free")
43
+ )
44
+ db.session.add(chat)
45
+ db.session.commit()
46
+ return jsonify({"chat": chat.to_dict()}), 201
47
+
48
+
49
+ @chat_bp.route("/chats/<int:chat_id>", methods=["GET"])
50
+ @login_required
51
+ def get_chat(chat_id):
52
+ chat = Chat.query.filter_by(id=chat_id, user_id=g.current_user.id).first()
53
+ if not chat:
54
+ return jsonify({"error": "Chat not found"}), 404
55
+ messages = chat.messages.order_by(Message.created_at).all()
56
+ return jsonify({
57
+ "chat": chat.to_dict(),
58
+ "messages": [m.to_dict() for m in messages]
59
+ })
60
+
61
+
62
+ @chat_bp.route("/chats/<int:chat_id>", methods=["PUT"])
63
+ @login_required
64
+ def update_chat(chat_id):
65
+ chat = Chat.query.filter_by(id=chat_id, user_id=g.current_user.id).first()
66
+ if not chat:
67
+ return jsonify({"error": "Chat not found"}), 404
68
+ data = request.get_json() or {}
69
+ if "title" in data:
70
+ chat.title = data["title"]
71
+ if "model" in data:
72
+ chat.model = data["model"]
73
+ chat.updated_at = datetime.now(timezone.utc)
74
+ db.session.commit()
75
+ return jsonify({"chat": chat.to_dict()})
76
+
77
+
78
+ @chat_bp.route("/chats/<int:chat_id>", methods=["DELETE"])
79
+ @login_required
80
+ def delete_chat(chat_id):
81
+ chat = Chat.query.filter_by(id=chat_id, user_id=g.current_user.id).first()
82
+ if not chat:
83
+ return jsonify({"error": "Chat not found"}), 404
84
+ db.session.delete(chat)
85
+ db.session.commit()
86
+ return jsonify({"message": "Chat deleted"})
87
+
88
+
89
+ @chat_bp.route("/chats/<int:chat_id>/messages", methods=["GET"])
90
+ @login_required
91
+ def get_messages(chat_id):
92
+ chat = Chat.query.filter_by(id=chat_id, user_id=g.current_user.id).first()
93
+ if not chat:
94
+ return jsonify({"error": "Chat not found"}), 404
95
+ messages = chat.messages.order_by(Message.created_at).all()
96
+ return jsonify({"messages": [m.to_dict() for m in messages]})
97
+
98
+
99
+ @chat_bp.route("/chats/<int:chat_id>/messages", methods=["POST"])
100
+ @login_required
101
+ def send_message(chat_id):
102
+ chat = Chat.query.filter_by(id=chat_id, user_id=g.current_user.id).first()
103
+ if not chat:
104
+ return jsonify({"error": "Chat not found"}), 404
105
+
106
+ data = request.get_json() or {}
107
+ user_text = data.get("content", "").strip()
108
+ if not user_text:
109
+ return jsonify({"error": "Message cannot be empty"}), 400
110
+
111
+ user_msg = Message(
112
+ chat_id=chat.id,
113
+ user_id=g.current_user.id,
114
+ role="user",
115
+ content=user_text,
116
+ message_type="text"
117
+ )
118
+ db.session.add(user_msg)
119
+
120
+ if chat.title == "New Chat":
121
+ chat.title = user_text[:50]
122
+ chat.updated_at = datetime.now(timezone.utc)
123
+ db.session.commit()
124
+
125
+ memory = load_memory_from_db(g.current_user.id)
126
+ memory = extract_user_info(user_text, memory)
127
+ save_memory_to_db(g.current_user.id, memory)
128
+
129
+ memory_result = handle_memory_command(user_text, g.current_user.id)
130
+ if memory_result:
131
+ ai_content = memory_result.get("content", "")
132
+ ai_type = "text"
133
+ ai_msg = Message(
134
+ chat_id=chat.id,
135
+ user_id=g.current_user.id,
136
+ role="assistant",
137
+ content=ai_content,
138
+ message_type=ai_type
139
+ )
140
+ db.session.add(ai_msg)
141
+ chat.updated_at = datetime.now(timezone.utc)
142
+ db.session.commit()
143
+ return jsonify({"message": ai_msg.to_dict()})
144
+
145
+ if is_image_request(user_text):
146
+ result = generate_image(user_text)
147
+ ai_content = result.get("content", "")
148
+ ai_type = result.get("type", "text")
149
+ if ai_type == "generated_image" and result.get("path"):
150
+ gen_img = GeneratedImage(
151
+ user_id=g.current_user.id, prompt=user_text,
152
+ model="openrouter", path=result['path']
153
+ )
154
+ db.session.add(gen_img)
155
+ else:
156
+ result = jarvis_reply(user_text, g.current_user.id, model=chat.model)
157
+ ai_content = result.get("content", "")
158
+ ai_type = result.get("type", "text")
159
+
160
+ ai_msg = Message(
161
+ chat_id=chat.id,
162
+ user_id=g.current_user.id,
163
+ role="assistant",
164
+ content=ai_content,
165
+ message_type=ai_type
166
+ )
167
+ db.session.add(ai_msg)
168
+ chat.updated_at = datetime.now(timezone.utc)
169
+ db.session.commit()
170
+
171
+ return jsonify({"message": ai_msg.to_dict()})
172
+
173
+
174
+ @chat_bp.route("/chats/<int:chat_id>/messages/stream", methods=["POST"])
175
+ @login_required
176
+ def send_message_stream(chat_id):
177
+ try:
178
+ chat = Chat.query.filter_by(id=chat_id, user_id=g.current_user.id).first()
179
+ if not chat:
180
+ return jsonify({"error": "Chat not found"}), 404
181
+
182
+ data = request.get_json() or {}
183
+ user_text = data.get("content", "").strip()
184
+ if not user_text:
185
+ return jsonify({"error": "Message cannot be empty"}), 400
186
+
187
+ user_msg = Message(
188
+ chat_id=chat.id,
189
+ user_id=g.current_user.id,
190
+ role="user",
191
+ content=user_text,
192
+ message_type="text"
193
+ )
194
+ db.session.add(user_msg)
195
+
196
+ if chat.title == "New Chat":
197
+ chat.title = user_text[:50]
198
+ chat.updated_at = datetime.now(timezone.utc)
199
+ db.session.commit()
200
+
201
+ memory = load_memory_from_db(g.current_user.id)
202
+ memory = extract_user_info(user_text, memory)
203
+ save_memory_to_db(g.current_user.id, memory)
204
+
205
+ model_name = chat.model
206
+ chat_id_val = chat.id
207
+ user_id = g.current_user.id
208
+
209
+ if is_image_request(user_text):
210
+ result = generate_image(user_text)
211
+ content = result.get("content", "")
212
+ img_type = result.get("type", "text")
213
+ if img_type == "generated_image" and result.get("path"):
214
+ ai_msg = Message(
215
+ chat_id=chat_id_val, user_id=user_id,
216
+ role="assistant", content=result['path'],
217
+ message_type="generated_image"
218
+ )
219
+ db.session.add(ai_msg)
220
+ gen_img = GeneratedImage(
221
+ user_id=user_id, prompt=user_text,
222
+ model="openrouter", path=result['path']
223
+ )
224
+ db.session.add(gen_img)
225
+ db.session.query(Chat).filter_by(id=chat_id_val).update(
226
+ {"updated_at": datetime.now(timezone.utc)}
227
+ )
228
+ db.session.commit()
229
+ sse = f"data: {json.dumps({'image': result['path']})}\n\n"
230
+ sse += f"data: {json.dumps({'done': True})}\n\n"
231
+ return Response(sse, mimetype="text/event-stream")
232
+ else:
233
+ ai_msg = Message(
234
+ chat_id=chat_id_val, user_id=user_id,
235
+ role="assistant", content=content,
236
+ message_type="text"
237
+ )
238
+ db.session.add(ai_msg)
239
+ db.session.query(Chat).filter_by(id=chat_id_val).update(
240
+ {"updated_at": datetime.now(timezone.utc)}
241
+ )
242
+ db.session.commit()
243
+ chunks = [content[i:i+10] for i in range(0, len(content), 10)]
244
+ sse = "".join(f"data: {json.dumps({'token': c})}\n\n" for c in chunks)
245
+ sse += f"data: {json.dumps({'done': True})}\n\n"
246
+ return Response(sse, mimetype="text/event-stream")
247
+
248
+ memory_result = handle_memory_command(user_text, g.current_user.id)
249
+ if memory_result:
250
+ content = memory_result.get("content", "")
251
+ ai_msg = Message(
252
+ chat_id=chat_id_val,
253
+ user_id=user_id,
254
+ role="assistant",
255
+ content=content,
256
+ message_type="text"
257
+ )
258
+ db.session.add(ai_msg)
259
+ db.session.query(Chat).filter_by(id=chat_id_val).update(
260
+ {"updated_at": datetime.now(timezone.utc)}
261
+ )
262
+ db.session.commit()
263
+ chunks = [content[i:i+10] for i in range(0, len(content), 10)]
264
+ sse = "".join(f"data: {json.dumps({'token': c})}\n\n" for c in chunks)
265
+ sse += f"data: {json.dumps({'done': True, 'message_id': ai_msg.id})}\n\n"
266
+ return Response(sse, mimetype="text/event-stream")
267
+
268
+ recent = Message.query.filter_by(user_id=g.current_user.id)\
269
+ .order_by(Message.created_at.desc()).limit(6).all()
270
+ recent.reverse()
271
+
272
+ memory_context = ""
273
+ profile = memory.get("user_profile", {})
274
+ if profile:
275
+ memory_context = "\n".join(f"{k}: {v}" for k, v in profile.items())
276
+
277
+ file_context = load_file_context(g.current_user.id)
278
+
279
+ system_prompt = f"""You are Nexus AI. You are futuristic, intelligent, helpful, and concise.
280
+
281
+ Known User Information:
282
+ {memory_context}
283
+
284
+ {file_context}"""
285
+
286
+ messages = [{"role": "system", "content": system_prompt}]
287
+ for msg in recent:
288
+ messages.append({"role": msg.role, "content": msg.content})
289
+
290
+ full_content = ""
291
+ tokens = []
292
+ try:
293
+ for token in chat_completion_stream(messages, model=model_name):
294
+ if token is None:
295
+ return jsonify({"error": "AI unavailable"}), 503
296
+ full_content += token
297
+ tokens.append(token)
298
+
299
+ ai_msg = Message(
300
+ chat_id=chat_id_val,
301
+ user_id=user_id,
302
+ role="assistant",
303
+ content=full_content,
304
+ message_type="text"
305
+ )
306
+ db.session.add(ai_msg)
307
+ db.session.query(Chat).filter_by(id=chat_id_val).update(
308
+ {"updated_at": datetime.now(timezone.utc)}
309
+ )
310
+ db.session.commit()
311
+
312
+ sse = "".join(f"data: {json.dumps({'token': t})}\n\n" for t in tokens)
313
+ sse += f"data: {json.dumps({'done': True, 'message_id': ai_msg.id})}\n\n"
314
+ return Response(sse, mimetype="text/event-stream")
315
+ except Exception as e:
316
+ traceback.print_exc()
317
+ return jsonify({"error": str(e)}), 500
318
+ except Exception as e:
319
+ traceback.print_exc()
320
+ return jsonify({"error": f"Server error: {str(e)}"}), 500
routes/image_routes.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, request, jsonify, g, send_from_directory
2
+ from database import db
3
+ from models.generated_image import GeneratedImage
4
+ from routes.middleware import login_required
5
+ from ai.jarvis_core import generate_image
6
+ import os
7
+
8
+ OUTPUT_DIR = "outputs"
9
+ image_bp = Blueprint("images", __name__, url_prefix="/api/images")
10
+
11
+
12
+ @image_bp.route("/generate", methods=["POST"])
13
+ @login_required
14
+ def generate():
15
+ data = request.get_json() or {}
16
+ prompt = data.get("prompt", "").strip()
17
+ if not prompt:
18
+ return jsonify({"error": "Prompt required"}), 400
19
+
20
+ result = generate_image(prompt)
21
+ if not result or result.get("type") != "generated_image":
22
+ return jsonify({"error": "Image generation failed", "result": result}), 500
23
+
24
+ path = result["path"]
25
+ record = GeneratedImage(
26
+ user_id=g.current_user.id,
27
+ prompt=prompt,
28
+ model=data.get("model", "openrouter"),
29
+ path=path
30
+ )
31
+ db.session.add(record)
32
+ db.session.commit()
33
+
34
+ return jsonify({"image": record.to_dict()})
35
+
36
+
37
+ @image_bp.route("/gallery", methods=["GET"])
38
+ @login_required
39
+ def gallery():
40
+ images = GeneratedImage.query.filter_by(user_id=g.current_user.id)\
41
+ .order_by(GeneratedImage.created_at.desc()).all()
42
+ return jsonify({"images": [img.to_dict() for img in images]})
43
+
44
+
45
+ @image_bp.route("/gallery/<int:image_id>", methods=["DELETE"])
46
+ @login_required
47
+ def delete_image(image_id):
48
+ img = GeneratedImage.query.filter_by(id=image_id, user_id=g.current_user.id).first()
49
+ if not img:
50
+ return jsonify({"error": "Image not found"}), 404
51
+ filepath = os.path.join(OUTPUT_DIR, os.path.basename(img.path))
52
+ if os.path.exists(filepath):
53
+ os.remove(filepath)
54
+ db.session.delete(img)
55
+ db.session.commit()
56
+ return jsonify({"message": "Image deleted"})
57
+
58
+
59
+ @image_bp.route("/outputs/<path:filename>")
60
+ @login_required
61
+ def serve_output(filename):
62
+ from sqlalchemy import func
63
+ owns = db.session.query(func.count(GeneratedImage.id)).filter(
64
+ GeneratedImage.user_id == g.current_user.id,
65
+ GeneratedImage.path.like(f"%/{filename}")
66
+ ).scalar()
67
+ if not owns:
68
+ return jsonify({"error": "Image not found"}), 404
69
+ return send_from_directory(OUTPUT_DIR, filename)
routes/memory_routes.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, request, jsonify, g
2
+ from database import db
3
+ from models.memory import Memory
4
+ from routes.middleware import login_required
5
+
6
+ memory_bp = Blueprint("memory", __name__, url_prefix="/api/memory")
7
+
8
+
9
+ @memory_bp.route("", methods=["GET"])
10
+ @login_required
11
+ def get_memories():
12
+ memories = Memory.query.filter_by(user_id=g.current_user.id).all()
13
+ return jsonify({"memories": [m.to_dict() for m in memories]})
14
+
15
+
16
+ @memory_bp.route("", methods=["POST"])
17
+ @login_required
18
+ def add_memory():
19
+ data = request.get_json() or {}
20
+ key = data.get("key", "").strip()
21
+ value = data.get("value", "").strip()
22
+ if not key or not value:
23
+ return jsonify({"error": "Key and value required"}), 400
24
+
25
+ existing = Memory.query.filter_by(
26
+ user_id=g.current_user.id, key=key
27
+ ).first()
28
+ if existing:
29
+ existing.value = value
30
+ else:
31
+ existing = Memory(user_id=g.current_user.id, key=key, value=value)
32
+ db.session.add(existing)
33
+ db.session.commit()
34
+ return jsonify({"memory": existing.to_dict()})
35
+
36
+
37
+ @memory_bp.route("/<int:memory_id>", methods=["PUT"])
38
+ @login_required
39
+ def update_memory(memory_id):
40
+ mem = Memory.query.filter_by(id=memory_id, user_id=g.current_user.id).first()
41
+ if not mem:
42
+ return jsonify({"error": "Memory not found"}), 404
43
+ data = request.get_json() or {}
44
+ if "value" in data:
45
+ mem.value = data["value"]
46
+ db.session.commit()
47
+ return jsonify({"memory": mem.to_dict()})
48
+
49
+
50
+ @memory_bp.route("/<int:memory_id>", methods=["DELETE"])
51
+ @login_required
52
+ def delete_memory(memory_id):
53
+ mem = Memory.query.filter_by(id=memory_id, user_id=g.current_user.id).first()
54
+ if not mem:
55
+ return jsonify({"error": "Memory not found"}), 404
56
+ db.session.delete(mem)
57
+ db.session.commit()
58
+ return jsonify({"message": "Memory deleted"})
59
+
60
+
61
+ @memory_bp.route("/remember", methods=["POST"])
62
+ @login_required
63
+ def remember():
64
+ data = request.get_json() or {}
65
+ key = data.get("key", "").strip()
66
+ value = data.get("value", "").strip()
67
+ if not key or not value:
68
+ return jsonify({"error": "Key and value required"}), 400
69
+
70
+ existing = Memory.query.filter_by(user_id=g.current_user.id, key=key).first()
71
+ if existing:
72
+ existing.value = value
73
+ else:
74
+ existing = Memory(user_id=g.current_user.id, key=key, value=value)
75
+ db.session.add(existing)
76
+ db.session.commit()
77
+ return jsonify({"memory": existing.to_dict(), "message": f"Remembered: {key} = {value}"})
78
+
79
+
80
+ @memory_bp.route("/forget", methods=["POST"])
81
+ @login_required
82
+ def forget():
83
+ data = request.get_json() or {}
84
+ key = data.get("key", "").strip()
85
+ if not key:
86
+ return jsonify({"error": "Key required"}), 400
87
+
88
+ mem = Memory.query.filter_by(user_id=g.current_user.id, key=key).first()
89
+ if mem:
90
+ db.session.delete(mem)
91
+ db.session.commit()
92
+ return jsonify({"message": f"Forgot: {key}"})
93
+ memories = Memory.query.filter(
94
+ Memory.user_id == g.current_user.id,
95
+ Memory.key.ilike(f"%{key}%")
96
+ ).all()
97
+ if memories:
98
+ for m in memories:
99
+ db.session.delete(m)
100
+ db.session.commit()
101
+ return jsonify({"message": f"Forgot {len(memories)} memory/memories matching '{key}'"})
102
+ return jsonify({"error": f"No memory found for '{key}'"}), 404
103
+
104
+
105
+ @memory_bp.route("/search", methods=["GET"])
106
+ @login_required
107
+ def search_memory():
108
+ q = request.args.get("q", "").strip()
109
+ if not q:
110
+ return jsonify({"memories": []})
111
+ memories = Memory.query.filter(
112
+ Memory.user_id == g.current_user.id,
113
+ Memory.key.ilike(f"%{q}%") | Memory.value.ilike(f"%{q}%")
114
+ ).all()
115
+ return jsonify({"memories": [m.to_dict() for m in memories]})
routes/middleware.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ from flask import session, jsonify, g
3
+ from models.user import User
4
+
5
+
6
+ def login_required(f):
7
+ @wraps(f)
8
+ def decorated(*args, **kwargs):
9
+ user_id = session.get("user_id")
10
+ if not user_id:
11
+ return jsonify({"error": "Not authenticated"}), 401
12
+ user = User.query.get(user_id)
13
+ if not user:
14
+ session.clear()
15
+ return jsonify({"error": "User not found"}), 404
16
+ g.current_user = user
17
+ return f(*args, **kwargs)
18
+ return decorated
routes/page_routes.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, render_template
2
+
3
+ pages_bp = Blueprint("pages", __name__)
4
+
5
+
6
+ @pages_bp.route("/")
7
+ def landing():
8
+ return render_template("landing.html")
9
+
10
+
11
+ @pages_bp.route("/login")
12
+ def login():
13
+ return render_template("login.html")
14
+
15
+
16
+ @pages_bp.route("/signup")
17
+ def signup():
18
+ return render_template("signup.html")
19
+
20
+
21
+ @pages_bp.route("/dashboard")
22
+ def dashboard():
23
+ return render_template("dashboard.html")
24
+
25
+
26
+ @pages_bp.route("/chat-page")
27
+ def chat_page():
28
+ return render_template("index.html")
29
+
30
+
31
+ @pages_bp.route("/core")
32
+ def core():
33
+ return render_template("core.html")
34
+
35
+
36
+ @pages_bp.route("/sandbox")
37
+ def sandbox():
38
+ return render_template("sandbox.html")
39
+
40
+
41
+ @pages_bp.route("/mocap")
42
+ def mocap():
43
+ return render_template("mocap.html")
44
+
45
+
46
+ @pages_bp.route("/avatar")
47
+ def avatar():
48
+ return render_template("avatar.html")
49
+
50
+
51
+ @pages_bp.route("/settings")
52
+ def settings():
53
+ return render_template("settings.html")
54
+
55
+
56
+ @pages_bp.route("/gallery")
57
+ def gallery():
58
+ return render_template("gallery.html")
59
+
60
+
61
+ @pages_bp.route("/nexus")
62
+ def nexus():
63
+ return render_template("nexus.html")
64
+
65
+
66
+ @pages_bp.route("/maintenance")
67
+ def maintenance():
68
+ return render_template("maintenance.html")
routes/scene_routes.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, request, jsonify, g
2
+ from database import db
3
+ from models.scene import Scene
4
+ from routes.middleware import login_required
5
+
6
+ scene_bp = Blueprint("scenes", __name__, url_prefix="/api/scenes")
7
+
8
+
9
+ @scene_bp.route("", methods=["GET"])
10
+ @login_required
11
+ def list_scenes():
12
+ scenes = Scene.query.filter_by(user_id=g.current_user.id)\
13
+ .order_by(Scene.updated_at.desc()).all()
14
+ return jsonify({"scenes": [s.to_dict() for s in scenes]})
15
+
16
+
17
+ @scene_bp.route("", methods=["POST"])
18
+ @login_required
19
+ def save_scene():
20
+ data = request.get_json() or {}
21
+ scene = Scene(
22
+ user_id=g.current_user.id,
23
+ name=data.get("name", "Untitled Scene"),
24
+ data=data.get("data", "{}")
25
+ )
26
+ db.session.add(scene)
27
+ db.session.commit()
28
+ return jsonify({"scene": scene.to_dict()}), 201
29
+
30
+
31
+ @scene_bp.route("/<int:scene_id>", methods=["GET"])
32
+ @login_required
33
+ def get_scene(scene_id):
34
+ scene = Scene.query.filter_by(id=scene_id, user_id=g.current_user.id).first()
35
+ if not scene:
36
+ return jsonify({"error": "Scene not found"}), 404
37
+ return jsonify({"scene": scene.to_dict()})
38
+
39
+
40
+ @scene_bp.route("/<int:scene_id>", methods=["PUT"])
41
+ @login_required
42
+ def update_scene(scene_id):
43
+ scene = Scene.query.filter_by(id=scene_id, user_id=g.current_user.id).first()
44
+ if not scene:
45
+ return jsonify({"error": "Scene not found"}), 404
46
+ data = request.get_json() or {}
47
+ if "name" in data:
48
+ scene.name = data["name"]
49
+ if "data" in data:
50
+ scene.data = data["data"]
51
+ db.session.commit()
52
+ return jsonify({"scene": scene.to_dict()})
53
+
54
+
55
+ @scene_bp.route("/<int:scene_id>", methods=["DELETE"])
56
+ @login_required
57
+ def delete_scene(scene_id):
58
+ scene = Scene.query.filter_by(id=scene_id, user_id=g.current_user.id).first()
59
+ if not scene:
60
+ return jsonify({"error": "Scene not found"}), 404
61
+ db.session.delete(scene)
62
+ db.session.commit()
63
+ return jsonify({"message": "Scene deleted"})
routes/settings_routes.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, request, jsonify, g
2
+ from database import db
3
+ from models.setting import Setting
4
+ from models.memory import Memory
5
+ from routes.middleware import login_required
6
+ import json
7
+
8
+ settings_bp = Blueprint("settings", __name__, url_prefix="/api/settings")
9
+
10
+
11
+ @settings_bp.route("", methods=["GET"])
12
+ @login_required
13
+ def get_settings():
14
+ settings = Setting.query.filter_by(user_id=g.current_user.id).all()
15
+ result = {s.key: s.value for s in settings}
16
+ return jsonify({"settings": result})
17
+
18
+
19
+ @settings_bp.route("", methods=["PUT"])
20
+ @login_required
21
+ def update_settings():
22
+ data = request.get_json() or {}
23
+ for key, value in data.items():
24
+ existing = Setting.query.filter_by(
25
+ user_id=g.current_user.id, key=key
26
+ ).first()
27
+ if existing:
28
+ existing.value = value
29
+ else:
30
+ setting = Setting(user_id=g.current_user.id, key=key, value=value)
31
+ db.session.add(setting)
32
+ db.session.commit()
33
+ return jsonify({"message": "Settings updated"})
34
+
35
+
36
+ @settings_bp.route("/profile", methods=["PUT"])
37
+ @login_required
38
+ def update_profile():
39
+ data = request.get_json() or {}
40
+ user = g.current_user
41
+ if "email" in data:
42
+ user.email = data["email"]
43
+ if "avatar_url" in data:
44
+ user.avatar_url = data["avatar_url"]
45
+ if "theme" in data:
46
+ user.theme = data["theme"]
47
+ db.session.commit()
48
+ return jsonify({"user": user.to_dict()})
49
+
50
+
51
+ @settings_bp.route("/models", methods=["GET"])
52
+ def available_models():
53
+ models = [
54
+ {"id": "openrouter/free", "name": "OpenRouter Free (Auto)", "provider": "openrouter"},
55
+ {"id": "deepseek/deepseek-chat", "name": "DeepSeek V3", "provider": "openrouter"},
56
+ {"id": "deepseek/deepseek-r1", "name": "DeepSeek R1", "provider": "openrouter"},
57
+ {"id": "google/gemini-2.0-flash-001", "name": "Gemini 2.0 Flash", "provider": "openrouter"},
58
+ {"id": "google/gemini-2.0-pro-exp-02-05", "name": "Gemini 2.0 Pro", "provider": "openrouter"},
59
+ {"id": "anthropic/claude-3.5-sonnet", "name": "Claude 3.5 Sonnet", "provider": "openrouter"},
60
+ {"id": "anthropic/claude-3-haiku", "name": "Claude 3 Haiku", "provider": "openrouter"},
61
+ {"id": "openai/gpt-4o-mini", "name": "GPT-4o Mini", "provider": "openrouter"},
62
+ {"id": "openai/gpt-4o", "name": "GPT-4o", "provider": "openrouter"},
63
+ {"id": "meta-llama/llama-3.1-8b-instruct", "name": "Llama 3.1 8B", "provider": "openrouter"},
64
+ {"id": "meta-llama/llama-3.3-70b-instruct", "name": "Llama 3.3 70B", "provider": "openrouter"},
65
+ {"id": "qwen/qwen-2.5-72b-instruct", "name": "Qwen 2.5 72B", "provider": "openrouter"},
66
+ {"id": "mistralai/mistral-7b-instruct", "name": "Mistral 7B", "provider": "openrouter"},
67
+ ]
68
+ return jsonify({"models": models})
routes/upload_routes.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from flask import Blueprint, request, jsonify, g, send_from_directory
4
+ from database import db
5
+ from models.upload import Upload
6
+ from routes.middleware import login_required
7
+ from services.document_service import extract_text
8
+
9
+ UPLOAD_DIR = "uploads"
10
+ upload_bp = Blueprint("uploads", __name__, url_prefix="/api/uploads")
11
+
12
+ ALLOWED_EXTENSIONS = {"pdf", "png", "jpg", "jpeg", "gif", "txt", "docx"}
13
+ ALLOWED_FILE_TYPES = {"pdf", "image", "text", "document"}
14
+
15
+
16
+ def detect_file_type(filename, data):
17
+ ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
18
+
19
+ # Check magic bytes
20
+ if len(data) >= 4:
21
+ if data[:4] == b'%PDF':
22
+ return ("application/pdf", "pdf")
23
+ if data[:8] == b'\x89PNG\r\n\x1a\n':
24
+ return ("image/png", "image")
25
+ if data[:2] in (b'\xff\xd8',):
26
+ return ("image/jpeg", "image")
27
+ if data[:4] == b'GIF8':
28
+ return ("image/gif", "image")
29
+ if data[:4] == b'PK\x03\x04':
30
+ return ("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document")
31
+
32
+ # Check if text-like
33
+ try:
34
+ data[:1024].decode("utf-8")
35
+ return ("text/plain", "text")
36
+ except UnicodeDecodeError:
37
+ pass
38
+
39
+ return ("application/octet-stream", "unknown")
40
+
41
+
42
+ @upload_bp.route("", methods=["POST"])
43
+ @login_required
44
+ def upload_file():
45
+ if "file" not in request.files:
46
+ return jsonify({"error": "No file provided"}), 400
47
+ file = request.files["file"]
48
+ if file.filename == "":
49
+ return jsonify({"error": "Empty filename"}), 400
50
+
51
+ ext = file.filename.rsplit(".", 1)[-1].lower() if "." in file.filename else ""
52
+ if ext not in ALLOWED_EXTENSIONS:
53
+ return jsonify({"error": "File type not allowed"}), 400
54
+
55
+ raw = file.read()
56
+ mime, file_type = detect_file_type(file.filename, raw)
57
+ if file_type not in ALLOWED_FILE_TYPES:
58
+ return jsonify({"error": "File type not allowed"}), 400
59
+
60
+ file.seek(0)
61
+
62
+ unique_name = f"{uuid.uuid4().hex}.{ext}"
63
+ path = os.path.join(UPLOAD_DIR, unique_name)
64
+ with open(path, "wb") as f:
65
+ f.write(raw)
66
+ size = os.path.getsize(path)
67
+
68
+ record = Upload(
69
+ user_id=g.current_user.id,
70
+ filename=unique_name,
71
+ original_name=file.filename,
72
+ path=path,
73
+ file_type=file_type,
74
+ size=size
75
+ )
76
+ db.session.add(record)
77
+ db.session.commit()
78
+
79
+ return jsonify({"upload": record.to_dict()}), 201
80
+
81
+
82
+ @upload_bp.route("", methods=["GET"])
83
+ @login_required
84
+ def list_uploads():
85
+ uploads = Upload.query.filter_by(user_id=g.current_user.id)\
86
+ .order_by(Upload.created_at.desc()).all()
87
+ return jsonify({"uploads": [u.to_dict() for u in uploads]})
88
+
89
+
90
+ @upload_bp.route("/<int:upload_id>/read", methods=["GET"])
91
+ @login_required
92
+ def read_upload(upload_id):
93
+ upload = Upload.query.filter_by(id=upload_id, user_id=g.current_user.id).first()
94
+ if not upload:
95
+ return jsonify({"error": "Upload not found"}), 404
96
+ if upload.file_type not in ("text", "pdf", "document"):
97
+ return jsonify({"error": "File type not readable"}), 400
98
+ content, error = extract_text(upload.path, upload.file_type)
99
+ if error:
100
+ return jsonify({"error": error}), 500
101
+ return jsonify({
102
+ "content": content[:50000],
103
+ "filename": upload.original_name,
104
+ "file_type": upload.file_type,
105
+ "size": len(content)
106
+ })
107
+
108
+
109
+ @upload_bp.route("/<int:upload_id>/analyze", methods=["POST"])
110
+ @login_required
111
+ def analyze_upload(upload_id):
112
+ upload = Upload.query.filter_by(id=upload_id, user_id=g.current_user.id).first()
113
+ if not upload:
114
+ return jsonify({"error": "Upload not found"}), 404
115
+ if upload.file_type not in ("text", "pdf", "document"):
116
+ return jsonify({"error": "File type not analyzable"}), 400
117
+
118
+ content, error = extract_text(upload.path, upload.file_type)
119
+ if error:
120
+ return jsonify({"error": error}), 500
121
+
122
+ data = request.get_json() or {}
123
+ action = data.get("action", "summarize")
124
+
125
+ from ai.jarvis_core import chat_completion
126
+ truncated = content[:15000]
127
+
128
+ if action == "summarize":
129
+ prompt = f"Please provide a concise summary of the following document:\n\n{truncated}"
130
+ elif action == "analyze":
131
+ prompt = f"Please analyze the following document. Extract key themes, entities, and insights:\n\n{truncated}"
132
+ elif action == "search":
133
+ query = data.get("query", "")
134
+ prompt = f"Search the following document for information related to '{query}':\n\n{truncated}"
135
+ else:
136
+ return jsonify({"error": "Unknown action"}), 400
137
+
138
+ reply = chat_completion([
139
+ {"role": "system", "content": "You are a document analysis AI. Be thorough and accurate."},
140
+ {"role": "user", "content": prompt}
141
+ ])
142
+
143
+ if not reply:
144
+ return jsonify({"error": "AI analysis failed"}), 500
145
+
146
+ return jsonify({"analysis": reply, "filename": upload.original_name, "action": action})
147
+
148
+
149
+ @upload_bp.route("/<path:filename>")
150
+ @login_required
151
+ def serve_upload(filename):
152
+ upload = Upload.query.filter_by(filename=filename, user_id=g.current_user.id).first()
153
+ if not upload:
154
+ return jsonify({"error": "File not found"}), 404
155
+ return send_from_directory(UPLOAD_DIR, filename)
runtime.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ python-3.11
services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
services/auth_service.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import bcrypt
2
+
3
+
4
+ def hash_password(password: str) -> str:
5
+ return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
6
+
7
+
8
+ def check_password(password: str, hashed: str) -> bool:
9
+ return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))
services/document_service.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import PyPDF2
3
+ import docx
4
+
5
+
6
+ def read_text_file(path):
7
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
8
+ return f.read()
9
+
10
+
11
+ def read_pdf(path):
12
+ text = ""
13
+ with open(path, "rb") as f:
14
+ reader = PyPDF2.PdfReader(f)
15
+ for page in reader.pages:
16
+ text += page.extract_text() + "\n"
17
+ return text
18
+
19
+
20
+ def read_docx(path):
21
+ doc = docx.Document(path)
22
+ return "\n".join(p.text for p in doc.paragraphs)
23
+
24
+
25
+ def extract_text(path, file_type):
26
+ if not os.path.exists(path):
27
+ return None, "File not found"
28
+ try:
29
+ if file_type == "text":
30
+ return read_text_file(path), None
31
+ elif file_type == "pdf":
32
+ return read_pdf(path), None
33
+ elif file_type == "document":
34
+ ext = path.rsplit(".", 1)[-1].lower()
35
+ if ext == "docx":
36
+ return read_docx(path), None
37
+ else:
38
+ return read_text_file(path), None
39
+ elif file_type == "image":
40
+ return None, "Image text extraction not supported yet"
41
+ return None, f"Unsupported file type: {file_type}"
42
+ except Exception as e:
43
+ return None, str(e)
services/hand_service.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ # Landmark indices
4
+ WRIST = 0
5
+ THUMB_TIP = 4
6
+ INDEX_TIP = 8
7
+ MIDDLE_TIP = 12
8
+ RING_TIP = 16
9
+ PINKY_TIP = 20
10
+ INDEX_PIP = 6
11
+ MIDDLE_PIP = 10
12
+ RING_PIP = 14
13
+ PINKY_PIP = 18
14
+
15
+
16
+ def finger_up(tip, pip, landmarks):
17
+ """Check if a finger is extended (tip above pip in y-coord)."""
18
+ return landmarks.landmark[tip].y < landmarks.landmark[pip].y
19
+
20
+
21
+ def get_finger_states(landmarks):
22
+ """Return dict of finger states: index, middle, ring, pinky."""
23
+ return {
24
+ "index": finger_up(INDEX_TIP, INDEX_PIP, landmarks),
25
+ "middle": finger_up(MIDDLE_TIP, MIDDLE_PIP, landmarks),
26
+ "ring": finger_up(RING_TIP, RING_PIP, landmarks),
27
+ "pinky": finger_up(PINKY_TIP, PINKY_PIP, landmarks),
28
+ }
29
+
30
+
31
+ def pinch_distance(landmarks):
32
+ """Distance between thumb tip and index tip."""
33
+ t = landmarks.landmark[THUMB_TIP]
34
+ i = landmarks.landmark[INDEX_TIP]
35
+ return math.sqrt((t.x - i.x) ** 2 + (t.y - i.y) ** 2 + (t.z - i.z) ** 2)
36
+
37
+
38
+ def grab_strength(landmarks):
39
+ """
40
+ Calculate grab strength 0-1.
41
+ 0 = open hand, 1 = full fist.
42
+ Uses average distance of fingertips to palm center (landmark 9).
43
+ """
44
+ palm = landmarks.landmark[9]
45
+ tips = [THUMB_TIP, INDEX_TIP, MIDDLE_TIP, RING_TIP, PINKY_TIP]
46
+ total_dist = 0.0
47
+ for tip in tips:
48
+ t = landmarks.landmark[tip]
49
+ total_dist += math.sqrt((t.x - palm.x) ** 2 + (t.y - palm.y) ** 2 + (t.z - palm.z) ** 2)
50
+ avg = total_dist / len(tips)
51
+ # Normalize: typical open hand ~0.3, fist ~0.05
52
+ strength = 1.0 - min(1.0, avg / 0.3)
53
+ return max(0.0, min(1.0, strength))
54
+
55
+
56
+ def detect_gesture(landmarks, finger_states, pinch_dist, grab):
57
+ """
58
+ Determine the primary gesture based on finger states and distances.
59
+ Priority: grab (fist) > pinch > point > open palm > none
60
+ """
61
+ if grab > 0.7:
62
+ return "grab"
63
+
64
+ if pinch_dist < 0.05:
65
+ return "pinch"
66
+
67
+ idx = finger_states["index"]
68
+ mid = finger_states["middle"]
69
+ ring = finger_states["ring"]
70
+ pinky = finger_states["pinky"]
71
+
72
+ if idx and not mid and not ring and not pinky:
73
+ return "point"
74
+
75
+ if idx and mid and ring and pinky:
76
+ return "open"
77
+
78
+ if not idx and not mid and not ring and not pinky and grab < 0.3:
79
+ return "rest"
80
+
81
+ return "none"
82
+
83
+
84
+ def detect_swipe(history, threshold=0.015):
85
+ """
86
+ Detect swipe direction from x-coordinate history.
87
+ Returns "left", "right", or None.
88
+ """
89
+ if len(history) < 3:
90
+ return None
91
+ dx = history[-1] - history[0]
92
+ if abs(dx) > threshold:
93
+ return "right" if dx > 0 else "left"
94
+ return None
95
+
96
+
97
+ def two_hand_scale(hand1_landmarks, hand2_landmarks):
98
+ """Calculate distance between two hands' index tips for scale gesture."""
99
+ h1 = hand1_landmarks.landmark[INDEX_TIP]
100
+ h2 = hand2_landmarks.landmark[INDEX_TIP]
101
+ return math.sqrt((h1.x - h2.x) ** 2 + (h1.y - h2.y) ** 2 + (h1.z - h2.z) ** 2)
102
+
103
+
104
+ def hand_data_from_landmarks(landmarks, handedness="Right", history=None):
105
+ """Build the hand_data dict to emit over socket."""
106
+ finger_states = get_finger_states(landmarks)
107
+ p_dist = pinch_distance(landmarks)
108
+ grab = grab_strength(landmarks)
109
+ gesture = detect_gesture(landmarks, finger_states, p_dist, grab)
110
+
111
+ idx = landmarks.landmark[INDEX_TIP]
112
+
113
+ result = {
114
+ "x": round(idx.x, 4),
115
+ "y": round(idx.y, 4),
116
+ "z": round(idx.z, 4),
117
+ "gesture": gesture,
118
+ "grab": round(grab, 3),
119
+ "pinch_dist": round(p_dist, 4),
120
+ "handedness": handedness,
121
+ "swipe": None,
122
+ }
123
+
124
+ if history is not None:
125
+ swipe = detect_swipe(history)
126
+ if swipe:
127
+ result["swipe"] = swipe
128
+
129
+ return result
socket_handlers/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ log = logging.getLogger(__name__)
4
+
5
+
6
+ def register_socket_handlers(socketio):
7
+
8
+ from .chat_handler import register_chat_handlers
9
+ from .camera_handler import register_camera_handlers, _start_camera, _stop_camera
10
+ register_chat_handlers(socketio)
11
+ register_camera_handlers(socketio)
12
+
13
+ _client_count = 0
14
+
15
+ @socketio.on("connect")
16
+ def on_connect():
17
+ nonlocal _client_count
18
+ _client_count += 1
19
+ log.info("Client connected (%d total)", _client_count)
20
+ _start_camera()
21
+
22
+ @socketio.on("disconnect")
23
+ def on_disconnect():
24
+ nonlocal _client_count
25
+ _client_count -= 1
26
+ log.info("Client disconnected (%d total)", _client_count)
27
+ if _client_count <= 0:
28
+ _client_count = 0
29
+ _stop_camera()
socket_handlers/camera_handler.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from threading import Thread, Event, Lock
3
+
4
+ log = logging.getLogger(__name__)
5
+
6
+ _camera_thread = None
7
+ _camera_stop = Event()
8
+ _socketio_instance = None
9
+ _camera_lock = Lock()
10
+
11
+
12
+ def _start_camera():
13
+ global _camera_thread, _camera_stop, _socketio_instance
14
+ if not _socketio_instance:
15
+ log.warning("Cannot start camera: no socketio instance")
16
+ return
17
+ from camera_service import start_camera
18
+ with _camera_lock:
19
+ if _camera_thread and _camera_thread.is_alive():
20
+ return
21
+ _camera_stop.clear()
22
+ _camera_thread = Thread(
23
+ target=start_camera, args=(_socketio_instance, _camera_stop), daemon=True
24
+ )
25
+ _camera_thread.start()
26
+ log.info("Camera started")
27
+
28
+
29
+ def _stop_camera():
30
+ global _camera_stop, _camera_thread
31
+ with _camera_lock:
32
+ if not _camera_thread:
33
+ return
34
+ _camera_stop.set()
35
+ thread = _camera_thread
36
+ _camera_thread = None
37
+ thread.join(timeout=2)
38
+ log.info("Camera stopped")
39
+
40
+
41
+ def register_camera_handlers(socketio):
42
+ global _socketio_instance
43
+ _socketio_instance = socketio
44
+
45
+ @socketio.on("request_camera")
46
+ def on_request_camera():
47
+ log.info("request_camera received")
48
+ _start_camera()
49
+
50
+ @socketio.on("release_camera")
51
+ def on_release_camera():
52
+ log.info("release_camera received")
53
+ _stop_camera()
socket_handlers/chat_handler.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ def register_chat_handlers(socketio):
2
+
3
+ @socketio.on("connect")
4
+ def on_connect():
5
+ print("Client connected")
6
+
7
+ @socketio.on("disconnect")
8
+ def on_disconnect():
9
+ print("Client disconnected")
startup_stderr.txt ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
2
+ WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
3
+ W0000 00:00:1781804379.485639 10472 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors.
4
+ W0000 00:00:1781804379.503957 10472 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors.
5
+ W0000 00:00:1781804379.562360 25768 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors.
6
+ W0000 00:00:1781804379.589784 25768 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors.
7
+ WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
8
+ * Running on all addresses (0.0.0.0)
9
+ * Running on http://127.0.0.1:5000
10
+ * Running on http://10.93.248.216:5000
11
+ Press CTRL+C to quit
12
+ C:\Users\Jeetandar N Silwani\AppData\Local\Programs\Python\Python311\Lib\site-packages\google\protobuf\symbol_database.py:55: UserWarning: SymbolDatabase.GetPrototype() is deprecated. Please use message_factory.GetMessageClass() instead. SymbolDatabase.GetPrototype() will be removed soon.
13
+ warnings.warn('SymbolDatabase.GetPrototype() is deprecated. Please '
14
+ 127.0.0.1 - - [18/Jun/2026 23:09:49] "GET / HTTP/1.1" 200 -
15
+ 127.0.0.1 - - [18/Jun/2026 23:09:49] "GET /static/landing.css HTTP/1.1" 304 -
16
+ 127.0.0.1 - - [18/Jun/2026 23:09:49] "GET /static/theme.js HTTP/1.1" 200 -
17
+ 127.0.0.1 - - [18/Jun/2026 23:09:49] "GET /static/particles.js HTTP/1.1" 304 -
18
+ 127.0.0.1 - - [18/Jun/2026 23:09:51] "GET /login HTTP/1.1" 200 -
19
+ 127.0.0.1 - - [18/Jun/2026 23:09:51] "GET /static/auth.css HTTP/1.1" 304 -
20
+ 127.0.0.1 - - [18/Jun/2026 23:09:51] "GET /static/auth.js HTTP/1.1" 200 -
21
+ 127.0.0.1 - - [18/Jun/2026 23:09:56] "POST /api/auth/login HTTP/1.1" 200 -
22
+ 127.0.0.1 - - [18/Jun/2026 23:09:56] "GET /dashboard HTTP/1.1" 200 -
23
+ 127.0.0.1 - - [18/Jun/2026 23:09:56] "GET /static/dashboard.css HTTP/1.1" 304 -
24
+ 127.0.0.1 - - [18/Jun/2026 23:09:56] "GET /static/particles.js HTTP/1.1" 304 -
25
+ 127.0.0.1 - - [18/Jun/2026 23:09:56] "GET /static/theme.js HTTP/1.1" 304 -
26
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /chat-page HTTP/1.1" 200 -
27
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /static/style.css HTTP/1.1" 200 -
28
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /static/auth.js HTTP/1.1" 304 -
29
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /static/app.js HTTP/1.1" 200 -
30
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /static/theme.js HTTP/1.1" 304 -
31
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /api/auth/me HTTP/1.1" 200 -
32
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /api/chat/chats HTTP/1.1" 200 -
33
+ 127.0.0.1 - - [18/Jun/2026 23:09:57] "GET /api/chat/chats/3 HTTP/1.1" 200 -
34
+ 127.0.0.1 - - [18/Jun/2026 23:10:00] "GET /api/settings HTTP/1.1" 200 -
35
+ 127.0.0.1 - - [18/Jun/2026 23:10:00] "POST /api/chat/chats HTTP/1.1" 201 -
36
+ 127.0.0.1 - - [18/Jun/2026 23:10:10] "POST /api/chat/chats/8/messages/stream HTTP/1.1" 200 -
37
+ 127.0.0.1 - - [18/Jun/2026 23:10:20] "POST /api/chat/chats/8/messages/stream HTTP/1.1" 200 -
38
+ 127.0.0.1 - - [18/Jun/2026 23:10:36] "POST /api/chat/chats/8/messages/stream HTTP/1.1" 200 -
39
+ 127.0.0.1 - - [18/Jun/2026 23:11:19] "POST /api/chat/chats/8/messages/stream HTTP/1.1" 200 -
40
+ 127.0.0.1 - - [18/Jun/2026 23:11:19] "GET /api/images/outputs/generated_1781804479.png HTTP/1.1" 200 -
41
+ 127.0.0.1 - - [18/Jun/2026 23:11:48] "DELETE /api/chat/chats/8 HTTP/1.1" 200 -
42
+ 127.0.0.1 - - [18/Jun/2026 23:11:48] "GET /api/chat/chats/3 HTTP/1.1" 200 -
43
+ 127.0.0.1 - - [18/Jun/2026 23:11:50] "DELETE /api/chat/chats/3 HTTP/1.1" 200 -
startup_stdout.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ BACKGROUND SERVICES STARTED
2
+ * Serving Flask app 'app'
3
+ * Debug mode: off
static/app.js ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let selectedFile = null;
2
+ let allChats = [];
3
+ let currentChatId = null;
4
+ let typingBubble = null;
5
+ let socket = null;
6
+ try { socket = io(); } catch(e) { console.warn("Socket.IO unavailable"); }
7
+
8
+ function escapeHtml(text) {
9
+ const div = document.createElement("div");
10
+ div.appendChild(document.createTextNode(text));
11
+ return div.innerHTML;
12
+ }
13
+
14
+ const orb = document.getElementById("nexusOrb");
15
+ const orbStatus = document.getElementById("orbStatus");
16
+
17
+ function setOrbState(state) {
18
+ if (!orb) return;
19
+ orb.className = "orb " + state;
20
+ const labels = {idle: "NEXUS ONLINE", thinking: "THINKING...", listening: "LISTENING...", generating: "GENERATING..."};
21
+ if (orbStatus) orbStatus.innerText = labels[state] || "NEXUS ONLINE";
22
+ }
23
+ setOrbState("idle");
24
+
25
+ function hideWelcome() {
26
+ const ws = document.getElementById("welcomeScreen");
27
+ if (ws) ws.style.display = "none";
28
+ }
29
+
30
+ function showWelcome() {
31
+ const ws = document.getElementById("welcomeScreen");
32
+ if (ws) ws.style.display = "flex";
33
+ }
34
+
35
+ async function loadChats() {
36
+ const data = await apiFetch("/api/chat/chats");
37
+ if (!data) return;
38
+ allChats = data.chats;
39
+ renderChatList();
40
+ if (allChats.length > 0) {
41
+ currentChatId = allChats[0].id;
42
+ loadMessages(currentChatId);
43
+ } else {
44
+ showWelcome();
45
+ }
46
+ }
47
+
48
+ async function loadMessages(chatId) {
49
+ const chatBox = document.getElementById("chat");
50
+ if (chatBox) chatBox.innerHTML = '<div class="loading-spinner"><div class="spinner"></div></div>';
51
+ hideWelcome();
52
+ const data = await apiFetch("/api/chat/chats/" + chatId);
53
+ if (!data) return;
54
+ renderMessages(data.messages);
55
+ }
56
+
57
+ async function createNewChat() {
58
+ const settingsData = await apiFetch("/api/settings");
59
+ const model = (settingsData && settingsData.settings && settingsData.settings.ai_model) || "openrouter/free";
60
+ const data = await apiFetch("/api/chat/chats", {
61
+ method: "POST",
62
+ body: JSON.stringify({title: "New Chat", model})
63
+ });
64
+ if (!data) return;
65
+ allChats.unshift(data.chat);
66
+ currentChatId = data.chat.id;
67
+ renderChatList();
68
+ renderMessages([]);
69
+ hideWelcome();
70
+ }
71
+
72
+ async function deleteChat(chatId) {
73
+ if (!confirm("Delete this chat?")) return;
74
+ await apiFetch("/api/chat/chats/" + chatId, {method: "DELETE"});
75
+ allChats = allChats.filter(c => c.id !== chatId);
76
+ if (currentChatId === chatId) {
77
+ currentChatId = allChats.length > 0 ? allChats[0].id : null;
78
+ if (currentChatId) loadMessages(currentChatId);
79
+ else { renderMessages([]); showWelcome(); }
80
+ }
81
+ renderChatList();
82
+ }
83
+
84
+ async function renameChat(chatId, title) {
85
+ await apiFetch("/api/chat/chats/" + chatId, {
86
+ method: "PUT",
87
+ body: JSON.stringify({title})
88
+ });
89
+ }
90
+
91
+ function renderChatList() {
92
+ const chatList = document.getElementById("chatList");
93
+ if (!chatList) return;
94
+ chatList.innerHTML = "";
95
+ allChats.forEach(chat => {
96
+ const item = document.createElement("div");
97
+ item.className = "chat-item" + (chat.id === currentChatId ? " active" : "");
98
+ const title = document.createElement("div");
99
+ title.className = "chat-title";
100
+ title.innerText = chat.title;
101
+ title.ondblclick = () => {
102
+ const newName = prompt("Rename chat:", chat.title);
103
+ if (newName && newName.trim()) {
104
+ renameChat(chat.id, newName.trim());
105
+ chat.title = newName.trim();
106
+ renderChatList();
107
+ }
108
+ };
109
+ title.onclick = () => {
110
+ currentChatId = chat.id;
111
+ renderChatList();
112
+ loadMessages(chat.id);
113
+ };
114
+ const del = document.createElement("button");
115
+ del.className = "delete-chat-btn";
116
+ del.innerText = "✕";
117
+ del.onclick = (e) => { e.stopPropagation(); deleteChat(chat.id); };
118
+ item.appendChild(title);
119
+ item.appendChild(del);
120
+ chatList.appendChild(item);
121
+ });
122
+ }
123
+
124
+ function renderMessages(messages) {
125
+ const chatBox = document.getElementById("chat");
126
+ if (!chatBox) return;
127
+ chatBox.innerHTML = "";
128
+ if (!messages || messages.length === 0) {
129
+ showWelcome();
130
+ return;
131
+ }
132
+ hideWelcome();
133
+ messages.forEach(msg => {
134
+ if (msg.message_type === "image" || msg.message_type === "generated_image") {
135
+ addImage(msg.content, msg.role, false);
136
+ } else {
137
+ addMessage(msg.content, msg.role, false);
138
+ }
139
+ });
140
+ }
141
+
142
+ function addMessage(text, sender, save = true) {
143
+ const chat = document.getElementById("chat");
144
+ if (!chat) return null;
145
+ hideWelcome();
146
+ const msg = document.createElement("div");
147
+ msg.className = "message " + sender;
148
+ const avatar = document.createElement("div");
149
+ avatar.className = "avatar";
150
+ avatar.innerText = sender === "user" ? "👤" : "🤖";
151
+ const bubble = document.createElement("div");
152
+ bubble.className = "bubble";
153
+ bubble.innerText = text;
154
+ if (sender === "user") { msg.appendChild(bubble); msg.appendChild(avatar); }
155
+ else { msg.appendChild(avatar); msg.appendChild(bubble); }
156
+ chat.appendChild(msg);
157
+ chat.scrollTop = chat.scrollHeight;
158
+ return bubble;
159
+ }
160
+
161
+ function addStreamToken(bubble, token) {
162
+ if (!bubble) return;
163
+ const safe = escapeHtml(token);
164
+ bubble.innerText += safe;
165
+ }
166
+
167
+ async function downloadImage(url) {
168
+ try {
169
+ const res = await fetch(url);
170
+ const blob = await res.blob();
171
+ const objUrl = URL.createObjectURL(blob);
172
+ const a = document.createElement("a");
173
+ a.href = objUrl;
174
+ a.download = url.split("/").pop().split("?")[0] || "image.png";
175
+ document.body.appendChild(a);
176
+ a.click();
177
+ document.body.removeChild(a);
178
+ URL.revokeObjectURL(objUrl);
179
+ } catch(e) { console.error("Download failed", e); }
180
+ }
181
+
182
+ function addImage(src, sender = "ai", save = true) {
183
+ removeTyping();
184
+ const chat = document.getElementById("chat");
185
+ if (!chat) return;
186
+ hideWelcome();
187
+ const msg = document.createElement("div");
188
+ msg.className = "message " + sender;
189
+ const avatar = document.createElement("div");
190
+ avatar.className = "avatar";
191
+ avatar.innerText = sender === "user" ? "👤" : "🤖";
192
+ const bubble = document.createElement("div");
193
+ bubble.className = "bubble";
194
+ const imgWrap = document.createElement("div");
195
+ imgWrap.className = "chat-img-wrap";
196
+ const img = document.createElement("img");
197
+ img.className = "chat-image";
198
+ img.src = window.location.origin + src + "?t=" + Date.now();
199
+ img.onclick = () => {
200
+ document.getElementById("imageViewer").style.display = "flex";
201
+ document.getElementById("viewerImage").src = img.src;
202
+ };
203
+ imgWrap.appendChild(img);
204
+ const dlBtn = document.createElement("button");
205
+ dlBtn.className = "chat-dl-btn";
206
+ dlBtn.innerHTML = "⬇";
207
+ dlBtn.title = "Download";
208
+ dlBtn.onclick = (e) => { e.stopPropagation(); downloadImage(img.src); };
209
+ imgWrap.appendChild(dlBtn);
210
+ bubble.appendChild(imgWrap);
211
+ if (sender === "user") { msg.appendChild(bubble); msg.appendChild(avatar); }
212
+ else { msg.appendChild(avatar); msg.appendChild(bubble); }
213
+ chat.appendChild(msg);
214
+ chat.scrollTop = chat.scrollHeight;
215
+ }
216
+
217
+ function showTyping() {
218
+ setOrbState("thinking");
219
+ const chat = document.getElementById("chat");
220
+ if (!chat) return;
221
+ hideWelcome();
222
+ const msg = document.createElement("div");
223
+ msg.className = "message ai";
224
+ msg.id = "typingIndicator";
225
+ const avatar = document.createElement("div");
226
+ avatar.className = "avatar";
227
+ avatar.innerText = "🤖";
228
+ const bubble = document.createElement("div");
229
+ bubble.className = "bubble";
230
+ bubble.innerHTML = '<div class="typing-dots"><span></span><span></span><span></span></div>';
231
+ msg.appendChild(avatar);
232
+ msg.appendChild(bubble);
233
+ chat.appendChild(msg);
234
+ chat.scrollTop = chat.scrollHeight;
235
+ typingBubble = msg;
236
+ }
237
+
238
+ function removeTyping() {
239
+ if (typingBubble) {
240
+ typingBubble.remove();
241
+ typingBubble = null;
242
+ }
243
+ }
244
+
245
+ document.getElementById("fileInput")?.addEventListener("change", function(e) {
246
+ selectedFile = e.target.files[0];
247
+ if (selectedFile) {
248
+ addImage(URL.createObjectURL(selectedFile), "user");
249
+ }
250
+ });
251
+
252
+ async function sendMessage() {
253
+ const input = document.getElementById("msg");
254
+ const text = input.value.trim();
255
+ if (!text && !selectedFile) return;
256
+ input.value = "";
257
+
258
+ try {
259
+ if (!currentChatId) {
260
+ await createNewChat();
261
+ }
262
+ if (!currentChatId) {
263
+ addMessage("Failed to create chat.", "ai");
264
+ return;
265
+ }
266
+
267
+ if (text) addMessage(text, "user");
268
+ showTyping();
269
+ setOrbState("generating");
270
+
271
+ const res = await fetch(API + "/api/chat/chats/" + currentChatId + "/messages/stream", {
272
+ method: "POST",
273
+ headers: {"Content-Type": "application/json", "X-CSRF-Token": getCsrfToken()},
274
+ body: JSON.stringify({content: text}),
275
+ credentials: "include"
276
+ });
277
+
278
+ if (!res.ok) {
279
+ removeTyping();
280
+ const errData = await res.json().catch(() => ({}));
281
+ addMessage(errData.error || "Connection error (" + res.status + ").", "ai");
282
+ setOrbState("idle");
283
+ return;
284
+ }
285
+
286
+ removeTyping();
287
+ const bubble = addMessage("", "ai", false);
288
+ if (!bubble) { setOrbState("idle"); return; }
289
+ let fullContent = "";
290
+ const reader = res.body.getReader();
291
+ const decoder = new TextDecoder();
292
+ let buffer = "";
293
+
294
+ while (true) {
295
+ const {done, value} = await reader.read();
296
+ if (done) break;
297
+ buffer += decoder.decode(value, {stream: true});
298
+ const lines = buffer.split("\n");
299
+ buffer = lines.pop() || "";
300
+
301
+ for (const line of lines) {
302
+ if (line.startsWith("data: ")) {
303
+ const jsonStr = line.slice(6).trim();
304
+ if (!jsonStr || jsonStr === "[DONE]") continue;
305
+ try {
306
+ const data = JSON.parse(jsonStr);
307
+ if (data.token) {
308
+ fullContent += data.token;
309
+ bubble.innerText = fullContent;
310
+ const chatBox = document.getElementById("chat");
311
+ if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;
312
+ }
313
+ if (data.image) {
314
+ const imgWrap = document.createElement("div");
315
+ imgWrap.className = "chat-img-wrap";
316
+ const img = document.createElement("img");
317
+ img.className = "chat-image";
318
+ img.src = data.image;
319
+ img.alt = "Generated image";
320
+ img.onclick = function() {
321
+ document.getElementById("imageViewer").style.display = "flex";
322
+ document.getElementById("viewerImage").src = this.src;
323
+ };
324
+ imgWrap.appendChild(img);
325
+ const dlBtn = document.createElement("button");
326
+ dlBtn.className = "chat-dl-btn";
327
+ dlBtn.innerHTML = "⬇";
328
+ dlBtn.title = "Download";
329
+ dlBtn.onclick = function(e) { e.stopPropagation(); downloadImage(img.src); };
330
+ imgWrap.appendChild(dlBtn);
331
+ bubble.appendChild(imgWrap);
332
+ }
333
+ if (data.error) {
334
+ bubble.innerText = data.error;
335
+ }
336
+ } catch (e) {}
337
+ }
338
+ }
339
+ }
340
+
341
+ setOrbState("idle");
342
+ renderChatList();
343
+ } catch (error) {
344
+ console.error(error);
345
+ removeTyping();
346
+ addMessage("Network error — check console.", "ai");
347
+ setOrbState("idle");
348
+ }
349
+ selectedFile = null;
350
+ const fileInput = document.getElementById("fileInput");
351
+ if (fileInput) fileInput.value = "";
352
+ }
353
+
354
+ function startMic() {
355
+ setOrbState("listening");
356
+ if (!("webkitSpeechRecognition" in window)) {
357
+ alert("Speech recognition not supported");
358
+ setOrbState("idle");
359
+ return;
360
+ }
361
+ const recognition = new webkitSpeechRecognition();
362
+ recognition.lang = "en-US";
363
+ recognition.onresult = function(event) {
364
+ document.getElementById("msg").value = event.results[0][0].transcript;
365
+ setOrbState("idle");
366
+ sendMessage();
367
+ };
368
+ recognition.onend = function() { setOrbState("idle"); };
369
+ recognition.start();
370
+ }
371
+
372
+ function speakText(text) {
373
+ if (!("speechSynthesis" in window)) return;
374
+ window.speechSynthesis.cancel();
375
+ const utterance = new SpeechSynthesisUtterance(text);
376
+ utterance.rate = 1.0;
377
+ utterance.pitch = 1.0;
378
+ utterance.volume = 1.0;
379
+ utterance.lang = "en-US";
380
+ window.speechSynthesis.speak(utterance);
381
+ }
382
+
383
+ if (socket) {
384
+ socket.on("voice_command", (data) => {
385
+ const cmd = (data.command || "").toLowerCase();
386
+ const msgInput = document.getElementById("msg");
387
+ if (msgInput) {
388
+ msgInput.value = cmd;
389
+ sendMessage();
390
+ }
391
+ });
392
+ }
393
+
394
+ function openCoreMode() { window.location.href = "/core"; }
395
+
396
+ window.onload = async function() {
397
+ const auth = await checkAuth();
398
+ if (auth) {
399
+ loadChats();
400
+ setOrbState("idle");
401
+ }
402
+ const msgInput = document.getElementById("msg");
403
+ if (msgInput) {
404
+ msgInput.addEventListener("keydown", function(e) {
405
+ if (e.key === "Enter") sendMessage();
406
+ });
407
+ }
408
+ };
static/auth.css ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *{ margin:0; padding:0; box-sizing:border-box; font-family:Segoe UI; }
2
+ body{
3
+ background:#050816;
4
+ overflow:hidden;
5
+ color:white;
6
+ }
7
+
8
+ .bg{
9
+ position:fixed; inset:0;
10
+ background:
11
+ radial-gradient(circle at top left, rgba(34,197,94,0.12), transparent 30%),
12
+ radial-gradient(circle at bottom right, rgba(59,130,246,0.08), transparent 30%);
13
+ z-index:-1;
14
+ }
15
+
16
+ .auth-container{
17
+ width:100%;
18
+ height:100vh;
19
+ display:flex;
20
+ justify-content:center;
21
+ align-items:center;
22
+ padding:20px;
23
+ }
24
+
25
+ .auth-box{
26
+ width:420px;
27
+ background:rgba(255,255,255,0.04);
28
+ border:1px solid rgba(255,255,255,0.05);
29
+ border-radius:32px;
30
+ padding:50px;
31
+ backdrop-filter:blur(20px);
32
+ text-align:center;
33
+ animation:authFade 0.4s ease;
34
+ }
35
+ @keyframes authFade{
36
+ from{ opacity:0; transform:translateY(20px); }
37
+ to{ opacity:1; transform:translateY(0); }
38
+ }
39
+
40
+ .logo{
41
+ font-size:36px;
42
+ color:#22c55e;
43
+ margin-bottom:30px;
44
+ font-weight:bold;
45
+ }
46
+
47
+ .auth-box h1{
48
+ font-size:42px;
49
+ margin-bottom:12px;
50
+ }
51
+
52
+ .auth-box p{
53
+ color:rgba(255,255,255,0.65);
54
+ margin-bottom:35px;
55
+ }
56
+
57
+ .auth-box input{
58
+ width:100%;
59
+ padding:18px;
60
+ border:none;
61
+ outline:none;
62
+ border-radius:18px;
63
+ margin-bottom:20px;
64
+ background:rgba(255,255,255,0.05);
65
+ color:white;
66
+ font-size:15px;
67
+ border:1px solid rgba(255,255,255,0.05);
68
+ transition:0.2s;
69
+ }
70
+ .auth-box input:focus{
71
+ border-color:rgba(34,197,94,0.3);
72
+ background:rgba(255,255,255,0.08);
73
+ }
74
+ .auth-box input::placeholder{
75
+ color:rgba(255,255,255,0.45);
76
+ }
77
+
78
+ .auth-box button{
79
+ width:100%;
80
+ padding:18px;
81
+ border:none;
82
+ border-radius:18px;
83
+ background:#22c55e;
84
+ color:black;
85
+ font-size:16px;
86
+ font-weight:bold;
87
+ cursor:pointer;
88
+ transition:0.25s;
89
+ }
90
+ .auth-box button:hover{
91
+ transform:translateY(-3px);
92
+ box-shadow:0 8px 30px rgba(34,197,94,0.3);
93
+ }
94
+ .auth-box button:disabled{
95
+ opacity:0.6;
96
+ cursor:not-allowed;
97
+ transform:none;
98
+ }
99
+
100
+ .switch-auth{
101
+ margin-top:25px;
102
+ color:rgba(255,255,255,0.6);
103
+ }
104
+ .switch-auth a{
105
+ color:#22c55e;
106
+ text-decoration:none;
107
+ font-weight:600;
108
+ }
109
+ .switch-auth a:hover{
110
+ text-decoration:underline;
111
+ }
112
+
113
+ .password-wrap{
114
+ position:relative;
115
+ width:100%;
116
+ margin-bottom:20px;
117
+ }
118
+ .password-wrap input{
119
+ margin-bottom:0;
120
+ padding-right:50px;
121
+ }
122
+ .password-wrap .pw-toggle{
123
+ position:absolute;
124
+ right:6px;
125
+ top:50%;
126
+ transform:translateY(-50%);
127
+ width:36px;
128
+ height:36px;
129
+ display:flex;
130
+ align-items:center;
131
+ justify-content:center;
132
+ background:rgba(255,255,255,0.06);
133
+ border:1px solid rgba(255,255,255,0.06);
134
+ border-radius:8px;
135
+ color:rgba(255,255,255,0.4);
136
+ font-size:16px;
137
+ cursor:pointer;
138
+ transition:0.2s;
139
+ padding:0;
140
+ line-height:1;
141
+ }
142
+ .password-wrap .pw-toggle:hover{
143
+ background:rgba(34,197,94,0.1);
144
+ border-color:rgba(34,197,94,0.2);
145
+ color:#22c55e;
146
+ }
147
+
148
+ @media(max-width:500px){
149
+ .auth-box{
150
+ padding:30px 24px;
151
+ border-radius:24px;
152
+ }
153
+ .auth-box h1{
154
+ font-size:32px;
155
+ }
156
+ }
157
+
158
+ body.dark{ background:#050816; }
159
+ body.emerald{ background:#021b12; }
160
+ body.emerald .logo{ color:#22c55e; }
161
+ body.emerald button{ background:#22c55e; }
162
+ body.blue{ background:#07111f; }
163
+ body.blue .logo{ color:#3b82f6; }
164
+ body.blue button{ background:#3b82f6; color:white; }
static/auth.js ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const API = window.location.origin;
2
+
3
+ async function signup(username, password) {
4
+ const res = await fetch(API + "/api/auth/signup", {
5
+ method: "POST",
6
+ headers: {"Content-Type": "application/json", "X-CSRF-Token": getCsrfToken()},
7
+ body: JSON.stringify({username, password}),
8
+ credentials: "include"
9
+ });
10
+ const data = await res.json();
11
+ if (res.ok) {
12
+ window.location.href = "/dashboard";
13
+ } else {
14
+ throw new Error(data.error || "Signup failed");
15
+ }
16
+ }
17
+
18
+ async function login(username, password) {
19
+ const res = await fetch(API + "/api/auth/login", {
20
+ method: "POST",
21
+ headers: {"Content-Type": "application/json", "X-CSRF-Token": getCsrfToken()},
22
+ body: JSON.stringify({username, password}),
23
+ credentials: "include"
24
+ });
25
+ const data = await res.json();
26
+ if (res.ok) {
27
+ window.location.href = "/dashboard";
28
+ } else {
29
+ throw new Error(data.error || "Login failed");
30
+ }
31
+ }
32
+
33
+ async function logout() {
34
+ await fetch(API + "/api/auth/logout", {
35
+ method: "POST",
36
+ headers: {"X-CSRF-Token": getCsrfToken()},
37
+ credentials: "include"
38
+ });
39
+ window.location.href = "/login";
40
+ }
41
+
42
+ function getCsrfToken() {
43
+ const match = document.cookie.match(/csrf_token=([^;]+)/);
44
+ return match ? decodeURIComponent(match[1]) : "";
45
+ }
46
+
47
+ async function apiFetch(path, options = {}) {
48
+ const headers = {"Content-Type": "application/json", ...options.headers};
49
+ if (options.method && options.method !== "GET") {
50
+ headers["X-CSRF-Token"] = getCsrfToken();
51
+ }
52
+ const res = await fetch(API + path, {...options, headers, credentials: "include"});
53
+ if (res.status === 401) {
54
+ window.location.href = "/login";
55
+ return null;
56
+ }
57
+ return res.json();
58
+ }
59
+
60
+ async function checkAuth() {
61
+ try {
62
+ const res = await fetch(API + "/api/auth/me", {credentials: "include"});
63
+ if (!res.ok) {
64
+ window.location.href = "/login";
65
+ return null;
66
+ }
67
+ return await res.json();
68
+ } catch {
69
+ window.location.href = "/login";
70
+ return null;
71
+ }
72
+ }