Commit Β·
3d7a63c
1
Parent(s): 676dc08
feat: complete local integration of AI mind codebase (brain, memory, etc.) in text2video, supporting both Direct Codebase execution and Remote HTTP fallback
Browse files- Dockerfile +1 -1
- app.py +65 -9
- brain.py +1018 -0
- embedder.py +72 -0
- extractor.py +108 -0
- knowledge_graph.py +212 -0
- learning.py +327 -0
- memory.py +1037 -0
- searcher.py +168 -0
Dockerfile
CHANGED
|
@@ -8,7 +8,7 @@ RUN apt-get update && apt-get install -y \
|
|
| 8 |
&& git lfs install
|
| 9 |
|
| 10 |
COPY requirements.txt .
|
| 11 |
-
COPY
|
| 12 |
COPY README.md .
|
| 13 |
|
| 14 |
RUN pip install --no-cache-dir pip -U && \
|
|
|
|
| 8 |
&& git lfs install
|
| 9 |
|
| 10 |
COPY requirements.txt .
|
| 11 |
+
COPY *.py .
|
| 12 |
COPY README.md .
|
| 13 |
|
| 14 |
RUN pip install --no-cache-dir pip -U && \
|
app.py
CHANGED
|
@@ -31,6 +31,16 @@ import imageio
|
|
| 31 |
os.environ["HF_HOME"] = "/tmp/huggingface"
|
| 32 |
os.environ["TORCH_HOME"] = "/tmp/torch"
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
MODELS = {
|
| 35 |
"Wan 2.1 T2V (1.3B) β Lightweight": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
| 36 |
"LTX-Video β Fast & Efficient": "Lightricks/LTX-Video",
|
|
@@ -63,19 +73,12 @@ def get_device_info():
|
|
| 63 |
|
| 64 |
DEVICE = get_device_info()
|
| 65 |
|
| 66 |
-
def enhance_prompt_with_ai(prompt_text, style_preset, ai_url, ai_key, session_id):
|
| 67 |
if not prompt_text or not prompt_text.strip():
|
| 68 |
return "Please enter a prompt first."
|
| 69 |
|
| 70 |
style_modifiers = STYLE_PRESETS.get(style_preset, "")
|
| 71 |
|
| 72 |
-
# Standardize URL
|
| 73 |
-
ai_url = (ai_url or "").strip().rstrip("/")
|
| 74 |
-
if not ai_url:
|
| 75 |
-
ai_url = "https://invictatill-invictatill-ai.hf.space"
|
| 76 |
-
|
| 77 |
-
chat_endpoint = f"{ai_url}/api/v1/chat"
|
| 78 |
-
|
| 79 |
system_prompt = (
|
| 80 |
"You are an expert cinematic prompt engineer for video generation models (like Wan 2.1, LTX-Video, CogVideo). "
|
| 81 |
"Your task is to rewrite the user's simple prompt into a highly descriptive, visually stunning, "
|
|
@@ -90,6 +93,49 @@ def enhance_prompt_with_ai(prompt_text, style_preset, ai_url, ai_key, session_id
|
|
| 90 |
if style_modifiers:
|
| 91 |
full_prompt += f" with the style: {style_modifiers}"
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
payload = {
|
| 94 |
"message": f"[SYSTEM CONTEXT]\n{system_prompt}\n\nUser: {full_prompt}\n\nAssistant:"
|
| 95 |
}
|
|
@@ -402,6 +448,16 @@ with gr.Blocks(css=custom_css, title="InvictaTill VideoGen Studio", theme=gr.the
|
|
| 402 |
|
| 403 |
with gr.Accordion("π§ InvictaTill AI Mind Integration Settings", open=False):
|
| 404 |
gr.Markdown("Configure the endpoint URL and API Key for your running InvictaTill AI Space instance so the prompt enhancer can read your business insights and custom memories.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
ai_url_input = gr.Textbox(
|
| 406 |
value=os.environ.get("VITE_INVICTATILL_AI_URL", "https://invictatill-invictatill-ai.hf.space"),
|
| 407 |
label="AI Mind Endpoint URL",
|
|
@@ -433,7 +489,7 @@ with gr.Blocks(css=custom_css, title="InvictaTill VideoGen Studio", theme=gr.the
|
|
| 433 |
# Click Handlers
|
| 434 |
enhance_btn.click(
|
| 435 |
fn=enhance_prompt_with_ai,
|
| 436 |
-
inputs=[prompt, style_dropdown, ai_url_input, ai_key_input, session_id_input],
|
| 437 |
outputs=[prompt]
|
| 438 |
)
|
| 439 |
|
|
|
|
| 31 |
os.environ["HF_HOME"] = "/tmp/huggingface"
|
| 32 |
os.environ["TORCH_HOME"] = "/tmp/torch"
|
| 33 |
|
| 34 |
+
# Try to import local AI Mind modules
|
| 35 |
+
try:
|
| 36 |
+
from memory import ConversationMemory
|
| 37 |
+
from brain import Brain
|
| 38 |
+
HAS_LOCAL_AI = True
|
| 39 |
+
print("π§ Local InvictaTill AI Mind loaded successfully!")
|
| 40 |
+
except Exception as e:
|
| 41 |
+
HAS_LOCAL_AI = False
|
| 42 |
+
print(f"β οΈ Local InvictaTill AI Mind unavailable: {str(e)}")
|
| 43 |
+
|
| 44 |
MODELS = {
|
| 45 |
"Wan 2.1 T2V (1.3B) β Lightweight": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
| 46 |
"LTX-Video β Fast & Efficient": "Lightricks/LTX-Video",
|
|
|
|
| 73 |
|
| 74 |
DEVICE = get_device_info()
|
| 75 |
|
| 76 |
+
def enhance_prompt_with_ai(prompt_text, style_preset, ai_mode, ai_url, ai_key, session_id):
|
| 77 |
if not prompt_text or not prompt_text.strip():
|
| 78 |
return "Please enter a prompt first."
|
| 79 |
|
| 80 |
style_modifiers = STYLE_PRESETS.get(style_preset, "")
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
system_prompt = (
|
| 83 |
"You are an expert cinematic prompt engineer for video generation models (like Wan 2.1, LTX-Video, CogVideo). "
|
| 84 |
"Your task is to rewrite the user's simple prompt into a highly descriptive, visually stunning, "
|
|
|
|
| 93 |
if style_modifiers:
|
| 94 |
full_prompt += f" with the style: {style_modifiers}"
|
| 95 |
|
| 96 |
+
# Local Mode: Load the local AI Mind directly
|
| 97 |
+
if ai_mode == "Local Integrated Mind (Direct Codebase)" and HAS_LOCAL_AI:
|
| 98 |
+
try:
|
| 99 |
+
# Connect to local database path (WAL mode auto-configured)
|
| 100 |
+
db_path = "/data/invicta_data/memory.db"
|
| 101 |
+
if not os.path.exists(os.path.dirname(db_path)):
|
| 102 |
+
# Fallback to local temp folder database if persistent mount is not found
|
| 103 |
+
db_path = os.path.join(tempfile.gettempdir(), "memory.db")
|
| 104 |
+
|
| 105 |
+
mem = ConversationMemory(db_path=db_path)
|
| 106 |
+
|
| 107 |
+
# Fetch active user context if any user exists
|
| 108 |
+
user_id = None
|
| 109 |
+
user_profile = None
|
| 110 |
+
try:
|
| 111 |
+
user_ids = mem.get_all_user_ids() if hasattr(mem, 'get_all_user_ids') else []
|
| 112 |
+
if user_ids:
|
| 113 |
+
user_id = user_ids[0]
|
| 114 |
+
user_profile = mem.get_user_profile(user_id)
|
| 115 |
+
except Exception:
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
# Direct Brain Query
|
| 119 |
+
brain = Brain()
|
| 120 |
+
query = f"[SYSTEM CONTEXT]\n{system_prompt}\n\nUser: {full_prompt}\n\nAssistant:"
|
| 121 |
+
answer, _ = brain.think(
|
| 122 |
+
user_query=query,
|
| 123 |
+
user_profile_dict=user_profile,
|
| 124 |
+
user_id=user_id
|
| 125 |
+
)
|
| 126 |
+
if answer:
|
| 127 |
+
return answer.strip().strip('"')
|
| 128 |
+
except Exception as e:
|
| 129 |
+
print(f"β οΈ Local AI Mind execution failed: {str(e)}. Falling back to cloud...")
|
| 130 |
+
|
| 131 |
+
# Cloud Mode: Standard API Post
|
| 132 |
+
# Standardize URL
|
| 133 |
+
ai_url = (ai_url or "").strip().rstrip("/")
|
| 134 |
+
if not ai_url:
|
| 135 |
+
ai_url = "https://invictatill-invictatill-ai.hf.space"
|
| 136 |
+
|
| 137 |
+
chat_endpoint = f"{ai_url}/api/v1/chat"
|
| 138 |
+
|
| 139 |
payload = {
|
| 140 |
"message": f"[SYSTEM CONTEXT]\n{system_prompt}\n\nUser: {full_prompt}\n\nAssistant:"
|
| 141 |
}
|
|
|
|
| 448 |
|
| 449 |
with gr.Accordion("π§ InvictaTill AI Mind Integration Settings", open=False):
|
| 450 |
gr.Markdown("Configure the endpoint URL and API Key for your running InvictaTill AI Space instance so the prompt enhancer can read your business insights and custom memories.")
|
| 451 |
+
ai_mode_dropdown = gr.Dropdown(
|
| 452 |
+
choices=[
|
| 453 |
+
"Local Integrated Mind (Direct Codebase)",
|
| 454 |
+
"Cloud Space API (Remote HTTP)"
|
| 455 |
+
] if HAS_LOCAL_AI else [
|
| 456 |
+
"Cloud Space API (Remote HTTP)"
|
| 457 |
+
],
|
| 458 |
+
value="Local Integrated Mind (Direct Codebase)" if HAS_LOCAL_AI else "Cloud Space API (Remote HTTP)",
|
| 459 |
+
label="AI Execution Mode"
|
| 460 |
+
)
|
| 461 |
ai_url_input = gr.Textbox(
|
| 462 |
value=os.environ.get("VITE_INVICTATILL_AI_URL", "https://invictatill-invictatill-ai.hf.space"),
|
| 463 |
label="AI Mind Endpoint URL",
|
|
|
|
| 489 |
# Click Handlers
|
| 490 |
enhance_btn.click(
|
| 491 |
fn=enhance_prompt_with_ai,
|
| 492 |
+
inputs=[prompt, style_dropdown, ai_mode_dropdown, ai_url_input, ai_key_input, session_id_input],
|
| 493 |
outputs=[prompt]
|
| 494 |
)
|
| 495 |
|
brain.py
ADDED
|
@@ -0,0 +1,1018 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/brain.py
|
| 2 |
+
import re
|
| 3 |
+
import time
|
| 4 |
+
import hashlib
|
| 5 |
+
import threading
|
| 6 |
+
from concurrent.futures import ThreadPoolExecutor, Future, TimeoutError as FuturesTimeoutError
|
| 7 |
+
import requests
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import ipaddress
|
| 11 |
+
import socket
|
| 12 |
+
|
| 13 |
+
# ββ Global timeout constants βββββββββββββββββββββββββββββββββββββββββββ
|
| 14 |
+
# Single provider call (non-stream): abort if no response in this many seconds
|
| 15 |
+
_PROVIDER_TIMEOUT_S = 180
|
| 16 |
+
# Streaming: abort entire stream if no new token arrives for this many seconds
|
| 17 |
+
_STREAM_IDLE_TIMEOUT_S = 60
|
| 18 |
+
# Hard wall-clock cap for the entire think() / think_stream() call
|
| 19 |
+
_TOTAL_THINK_TIMEOUT_S = 360
|
| 20 |
+
# Web-search + scrape budget
|
| 21 |
+
_SEARCH_TIMEOUT_S = 20
|
| 22 |
+
|
| 23 |
+
from searcher import WebSearcher
|
| 24 |
+
from knowledge_graph import KnowledgeGraph
|
| 25 |
+
try:
|
| 26 |
+
from embedder import LocalEmbedder
|
| 27 |
+
except ImportError:
|
| 28 |
+
LocalEmbedder = None
|
| 29 |
+
print("β οΈ LocalEmbedder unavailable (chromadb not installed)")
|
| 30 |
+
|
| 31 |
+
from extractor import FactExtractor
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 35 |
+
# MULTI-PROVIDER LLM CLIENT
|
| 36 |
+
# Priority: NVIDIA Nemotron-3 Ultra 550B β OpenRouter (Nemotron fallback) β Gemini β Groq β DeepSeek
|
| 37 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
+
|
| 39 |
+
class MultiLLMClient:
|
| 40 |
+
def __init__(self):
|
| 41 |
+
self.nvidia_key = os.getenv("NVIDIA_API_KEY", "").strip() or "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"
|
| 42 |
+
self.nvidia_model = os.getenv("NVIDIA_MODEL", "").strip() or "meta/llama-3.1-8b-instruct"
|
| 43 |
+
self.nvidia_coding_model = os.getenv("NVIDIA_CODING_MODEL", "").strip() or "meta/llama-3.1-8b-instruct"
|
| 44 |
+
self.openrouter_key = os.getenv("OPENROUTER_API_KEY", "").strip()
|
| 45 |
+
self.gemini_key = os.getenv("GEMINI_API_KEY", "").strip()
|
| 46 |
+
self.deepseek_key = os.getenv("DEEPSEEK_API_KEY", "").strip()
|
| 47 |
+
self.groq_key = os.getenv("GROQ_API_KEY", "").strip()
|
| 48 |
+
|
| 49 |
+
# FIX: Updated to working OpenRouter model IDs
|
| 50 |
+
default_models = (
|
| 51 |
+
"meta-llama/llama-3.3-70b-instruct,"
|
| 52 |
+
"qwen/qwen-2.5-coder-32b-instruct,"
|
| 53 |
+
"google/gemini-2.0-flash-001,"
|
| 54 |
+
"deepseek/deepseek-chat"
|
| 55 |
+
)
|
| 56 |
+
raw_models = os.getenv("OPENROUTER_MODELS", default_models)
|
| 57 |
+
self.openrouter_models = [
|
| 58 |
+
m.strip() for m in raw_models.split(",") if m.strip()
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
self._recent_fail = {}
|
| 62 |
+
self._fail_lock = threading.Lock()
|
| 63 |
+
|
| 64 |
+
self.nvidia_client = None
|
| 65 |
+
if self.nvidia_key:
|
| 66 |
+
try:
|
| 67 |
+
from openai import OpenAI
|
| 68 |
+
self.nvidia_client = OpenAI(
|
| 69 |
+
base_url="https://integrate.api.nvidia.com/v1",
|
| 70 |
+
api_key=self.nvidia_key,
|
| 71 |
+
timeout=90.0
|
| 72 |
+
)
|
| 73 |
+
print("β
NVIDIA OpenAI client ready")
|
| 74 |
+
except ImportError:
|
| 75 |
+
print("β οΈ openai package not installed. NVIDIA unavailable. Install: pip install openai>=1.45.0")
|
| 76 |
+
except Exception as e:
|
| 77 |
+
print(f"β οΈ NVIDIA OpenAI client init failed: {e}")
|
| 78 |
+
|
| 79 |
+
self.groq_client = None
|
| 80 |
+
if self.groq_key:
|
| 81 |
+
try:
|
| 82 |
+
from groq import Groq
|
| 83 |
+
self.groq_client = Groq(api_key=self.groq_key)
|
| 84 |
+
print("β
Groq client ready")
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print(f"β οΈ Groq init failed: {e}")
|
| 87 |
+
|
| 88 |
+
print(f"π§ MultiLLM: NVIDIA={'β
' if self.nvidia_client else 'β'} | OR={len(self.openrouter_models)} | Gemini={'β
' if self.gemini_key else 'β'} | Groq={'β
' if self.groq_key else 'β'} | DeepSeek={'β
' if self.deepseek_key else 'β'}")
|
| 89 |
+
|
| 90 |
+
def validate_providers(self):
|
| 91 |
+
"""Return (ok: bool, message: str). Quick health-check before a request."""
|
| 92 |
+
has_any = any([
|
| 93 |
+
self.nvidia_client,
|
| 94 |
+
self.openrouter_key,
|
| 95 |
+
self.gemini_key,
|
| 96 |
+
self.groq_key,
|
| 97 |
+
self.deepseek_key,
|
| 98 |
+
])
|
| 99 |
+
if not has_any:
|
| 100 |
+
return False, (
|
| 101 |
+
"No LLM API keys are configured. "
|
| 102 |
+
"Add at least one key (NVIDIA_API_KEY, OPENROUTER_API_KEY, GEMINI_API_KEY, "
|
| 103 |
+
"GROQ_API_KEY, or DEEPSEEK_API_KEY) in HF Space Settings β Secrets."
|
| 104 |
+
)
|
| 105 |
+
active = []
|
| 106 |
+
if self.nvidia_client and not self._is_recent_fail("nvidia"):
|
| 107 |
+
active.append("NVIDIA")
|
| 108 |
+
if self.openrouter_key and any(
|
| 109 |
+
not self._is_recent_fail(f"or:{m}") for m in self.openrouter_models
|
| 110 |
+
):
|
| 111 |
+
active.append("OpenRouter")
|
| 112 |
+
if self.gemini_key and not self._is_recent_fail("gemini"):
|
| 113 |
+
active.append("Gemini")
|
| 114 |
+
if self.groq_key and not self._is_recent_fail("groq"):
|
| 115 |
+
active.append("Groq")
|
| 116 |
+
if self.deepseek_key and not self._is_recent_fail("deepseek"):
|
| 117 |
+
active.append("DeepSeek")
|
| 118 |
+
if not active:
|
| 119 |
+
return False, (
|
| 120 |
+
"All LLM providers are in a cooldown period due to recent failures. "
|
| 121 |
+
"Wait ~2 minutes and try again. "
|
| 122 |
+
"For heavy coding tasks, use InvictaTill Studio which has a dedicated fast connection."
|
| 123 |
+
)
|
| 124 |
+
return True, f"Active providers: {', '.join(active)}"
|
| 125 |
+
|
| 126 |
+
def _timed_call(self, fn, *args, timeout=None, **kwargs):
|
| 127 |
+
"""Run fn(*args, **kwargs) in a thread, raising RuntimeError if it exceeds timeout."""
|
| 128 |
+
timeout = timeout or _PROVIDER_TIMEOUT_S
|
| 129 |
+
with ThreadPoolExecutor(max_workers=1) as ex:
|
| 130 |
+
fut = ex.submit(fn, *args, **kwargs)
|
| 131 |
+
try:
|
| 132 |
+
return fut.result(timeout=timeout)
|
| 133 |
+
except FuturesTimeoutError:
|
| 134 |
+
raise RuntimeError(f"Provider call timed out after {timeout}s")
|
| 135 |
+
|
| 136 |
+
def _mark_fail(self, key):
|
| 137 |
+
with self._fail_lock:
|
| 138 |
+
self._recent_fail[key] = time.time()
|
| 139 |
+
|
| 140 |
+
def _is_recent_fail(self, key, cooldown=60):
|
| 141 |
+
with self._fail_lock:
|
| 142 |
+
last = self._recent_fail.get(key)
|
| 143 |
+
return last and (time.time() - last) < cooldown
|
| 144 |
+
|
| 145 |
+
def chat(self, messages, stream=False, max_tokens=2048, temperature=0.7, enable_thinking=False, reasoning_budget=None):
|
| 146 |
+
# ββ Pre-flight validation ββββββββββββββββββββββββββββββββββββββββββ
|
| 147 |
+
ok, msg = self.validate_providers()
|
| 148 |
+
if not ok:
|
| 149 |
+
raise RuntimeError(msg)
|
| 150 |
+
|
| 151 |
+
_deadline = time.time() + _TOTAL_THINK_TIMEOUT_S
|
| 152 |
+
|
| 153 |
+
def _remaining():
|
| 154 |
+
return max(2, _deadline - time.time())
|
| 155 |
+
|
| 156 |
+
# ββ 1. NVIDIA βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 157 |
+
if self.nvidia_client and not self._is_recent_fail("nvidia", cooldown=120) and _remaining() > 5:
|
| 158 |
+
try:
|
| 159 |
+
print("π§ NVIDIA Primary...")
|
| 160 |
+
if stream:
|
| 161 |
+
return self._call_nvidia(messages, stream, max_tokens, temperature, enable_thinking=enable_thinking, reasoning_budget=reasoning_budget)
|
| 162 |
+
return self._timed_call(self._call_nvidia, messages, stream, max_tokens, temperature, enable_thinking=enable_thinking, reasoning_budget=reasoning_budget, timeout=min(_PROVIDER_TIMEOUT_S, _remaining()))
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"β οΈ NVIDIA: {e}")
|
| 165 |
+
self._mark_fail("nvidia")
|
| 166 |
+
|
| 167 |
+
# ββ 2. OpenRouter ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 168 |
+
if self.openrouter_key and self.openrouter_models:
|
| 169 |
+
for model in self.openrouter_models:
|
| 170 |
+
if _remaining() <= 5:
|
| 171 |
+
break
|
| 172 |
+
if self._is_recent_fail(f"or:{model}", cooldown=120):
|
| 173 |
+
continue
|
| 174 |
+
try:
|
| 175 |
+
print(f"π§ OpenRouter: {model}")
|
| 176 |
+
if stream:
|
| 177 |
+
return self._call_openrouter(model, messages, stream, max_tokens, temperature)
|
| 178 |
+
return self._timed_call(self._call_openrouter, model, messages, stream, max_tokens, temperature, timeout=min(_PROVIDER_TIMEOUT_S, _remaining()))
|
| 179 |
+
except requests.HTTPError as e:
|
| 180 |
+
status = e.response.status_code
|
| 181 |
+
try:
|
| 182 |
+
err_body = e.response.json()
|
| 183 |
+
err_msg = err_body.get("error", {}).get("message", str(err_body))
|
| 184 |
+
except Exception:
|
| 185 |
+
err_msg = e.response.text[:200]
|
| 186 |
+
self._mark_fail(f"or:{model}")
|
| 187 |
+
print(f"β οΈ OpenRouter {model} HTTP {status}: {err_msg}")
|
| 188 |
+
if status == 404:
|
| 189 |
+
print(" β Model ID not found. Will try next model...")
|
| 190 |
+
elif status == 401:
|
| 191 |
+
print(" β Invalid API key. Check OPENROUTER_API_KEY secret.")
|
| 192 |
+
elif status == 429:
|
| 193 |
+
print(" β Rate limited. Will try next model...")
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f"β οΈ OpenRouter {model}: {e}")
|
| 196 |
+
self._mark_fail(f"or:{model}")
|
| 197 |
+
|
| 198 |
+
# ββ 3. Google Gemini βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
+
if self.gemini_key and not self._is_recent_fail("gemini", cooldown=120) and _remaining() > 5:
|
| 200 |
+
try:
|
| 201 |
+
print("π§ Gemini...")
|
| 202 |
+
if stream:
|
| 203 |
+
return self._call_gemini(messages, stream, max_tokens, temperature)
|
| 204 |
+
return self._timed_call(self._call_gemini, messages, stream, max_tokens, temperature, timeout=min(_PROVIDER_TIMEOUT_S, _remaining()))
|
| 205 |
+
except requests.HTTPError as e:
|
| 206 |
+
print(f"β οΈ Gemini HTTP {e.response.status_code}: {e.response.text[:200]}")
|
| 207 |
+
if e.response.status_code == 401:
|
| 208 |
+
print(" β Invalid API key. Check GEMINI_API_KEY secret.")
|
| 209 |
+
self._mark_fail("gemini")
|
| 210 |
+
except Exception as e:
|
| 211 |
+
print(f"β οΈ Gemini: {e}")
|
| 212 |
+
self._mark_fail("gemini")
|
| 213 |
+
|
| 214 |
+
# ββ 4. Groq ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 215 |
+
if self.groq_key and self.groq_client and not self._is_recent_fail("groq", cooldown=120) and _remaining() > 5:
|
| 216 |
+
try:
|
| 217 |
+
print("π§ Groq...")
|
| 218 |
+
if stream:
|
| 219 |
+
return self._call_groq(messages, stream, max_tokens, temperature)
|
| 220 |
+
return self._timed_call(self._call_groq, messages, stream, max_tokens, temperature, timeout=min(_PROVIDER_TIMEOUT_S, _remaining()))
|
| 221 |
+
except Exception as e:
|
| 222 |
+
err = str(e).lower()
|
| 223 |
+
if "rate limit" in err or "429" in err:
|
| 224 |
+
print("β οΈ Groq rate-limited")
|
| 225 |
+
else:
|
| 226 |
+
print(f"β οΈ Groq: {e}")
|
| 227 |
+
self._mark_fail("groq")
|
| 228 |
+
|
| 229 |
+
# ββ 5. DeepSeek ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 230 |
+
if self.deepseek_key and not self._is_recent_fail("deepseek", cooldown=120):
|
| 231 |
+
try:
|
| 232 |
+
print("π§ DeepSeek...")
|
| 233 |
+
return self._call_deepseek(messages, stream, max_tokens, temperature)
|
| 234 |
+
except Exception as e:
|
| 235 |
+
print(f"β οΈ DeepSeek: {e}")
|
| 236 |
+
self._mark_fail("deepseek")
|
| 237 |
+
|
| 238 |
+
raise RuntimeError("All LLM providers failed. Check API keys in HF Space Settings β Secrets.")
|
| 239 |
+
|
| 240 |
+
# ββ NVIDIA (OpenAI SDK) ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 241 |
+
def _call_nvidia(self, messages, stream, max_tokens, temperature, enable_thinking=False, reasoning_budget=None):
|
| 242 |
+
if not self.nvidia_client:
|
| 243 |
+
raise RuntimeError("NVIDIA OpenAI client not initialized")
|
| 244 |
+
|
| 245 |
+
coding_keywords = ("code", "fix", "debug", "html", "js", "css", "function", "script", "app", "error", "write", "game", "studio", "create", "[tool_")
|
| 246 |
+
prompt_text = " ".join(str(m.get("content", "")).lower() for m in messages[-3:])
|
| 247 |
+
is_coding_task = any(kw in prompt_text for kw in coding_keywords)
|
| 248 |
+
|
| 249 |
+
if is_coding_task:
|
| 250 |
+
models_to_try = [
|
| 251 |
+
getattr(self, "nvidia_coding_model", "meta/llama-3.1-8b-instruct"),
|
| 252 |
+
self.nvidia_model,
|
| 253 |
+
"nvidia/nemotron-3-ultra-550b-a55b"
|
| 254 |
+
]
|
| 255 |
+
else:
|
| 256 |
+
models_to_try = [
|
| 257 |
+
self.nvidia_model,
|
| 258 |
+
getattr(self, "nvidia_coding_model", "meta/llama-3.1-8b-instruct"),
|
| 259 |
+
"nvidia/nemotron-3-ultra-550b-a55b"
|
| 260 |
+
]
|
| 261 |
+
seen = set()
|
| 262 |
+
models_to_try = [m for m in models_to_try if m and not (m in seen or seen.add(m))]
|
| 263 |
+
|
| 264 |
+
last_err = None
|
| 265 |
+
for model_id in models_to_try:
|
| 266 |
+
is_nemotron = "nemotron" in model_id.lower()
|
| 267 |
+
is_glm = "glm-5.2" in model_id.lower()
|
| 268 |
+
|
| 269 |
+
extra_body = {}
|
| 270 |
+
if enable_thinking and is_nemotron:
|
| 271 |
+
extra_body["chat_template_kwargs"] = {"enable_thinking": True}
|
| 272 |
+
if reasoning_budget:
|
| 273 |
+
extra_body["reasoning_budget"] = reasoning_budget
|
| 274 |
+
|
| 275 |
+
try:
|
| 276 |
+
print(f"π§ NVIDIA calling {model_id}...")
|
| 277 |
+
completion = self.nvidia_client.chat.completions.create(
|
| 278 |
+
model=model_id,
|
| 279 |
+
messages=messages,
|
| 280 |
+
temperature=temperature,
|
| 281 |
+
top_p=1.0 if is_glm else 0.95,
|
| 282 |
+
max_tokens=min(max_tokens, 16384 if is_glm else 65536),
|
| 283 |
+
stream=stream,
|
| 284 |
+
extra_body=extra_body if extra_body else None
|
| 285 |
+
)
|
| 286 |
+
if stream:
|
| 287 |
+
return self._stream_nvidia_openai(completion)
|
| 288 |
+
content = completion.choices[0].message.content or ""
|
| 289 |
+
return self._wrap_response(content)
|
| 290 |
+
except Exception as e:
|
| 291 |
+
print(f"β οΈ NVIDIA model ({model_id}) error: {e}")
|
| 292 |
+
last_err = e
|
| 293 |
+
|
| 294 |
+
raise last_err or RuntimeError("All NVIDIA models failed")
|
| 295 |
+
|
| 296 |
+
def _stream_nvidia_openai(self, completion):
|
| 297 |
+
for chunk in completion:
|
| 298 |
+
if not chunk.choices:
|
| 299 |
+
continue
|
| 300 |
+
delta = chunk.choices[0].delta
|
| 301 |
+
reasoning = getattr(delta, "reasoning_content", None)
|
| 302 |
+
if reasoning:
|
| 303 |
+
# Reasoning tokens are silently consumed β NOT shown to the user.
|
| 304 |
+
# They represent the model's internal thought process.
|
| 305 |
+
pass
|
| 306 |
+
if delta.content:
|
| 307 |
+
yield self._wrap_stream_chunk(delta.content)
|
| 308 |
+
|
| 309 |
+
# ββ OpenRouter (raw requests) ββββββββββββββββββββββββββββββββββββββββ
|
| 310 |
+
def _call_openrouter(self, model, messages, stream, max_tokens, temperature):
|
| 311 |
+
headers = {
|
| 312 |
+
"Authorization": f"Bearer {self.openrouter_key}",
|
| 313 |
+
"HTTP-Referer": "https://invictatill-ai.hf.space",
|
| 314 |
+
"X-Title": "Invicta AI",
|
| 315 |
+
"Content-Type": "application/json"
|
| 316 |
+
}
|
| 317 |
+
# Cap at 8K for OpenRouter β most models there have lower limits than Nemotron
|
| 318 |
+
safe_max = min(max_tokens, 8192)
|
| 319 |
+
payload = {
|
| 320 |
+
"model": model,
|
| 321 |
+
"messages": messages,
|
| 322 |
+
"stream": stream,
|
| 323 |
+
"max_tokens": safe_max,
|
| 324 |
+
"temperature": temperature
|
| 325 |
+
}
|
| 326 |
+
if stream:
|
| 327 |
+
return self._stream_openrouter(headers, payload)
|
| 328 |
+
r = requests.post(
|
| 329 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 330 |
+
headers=headers, json=payload, timeout=15
|
| 331 |
+
)
|
| 332 |
+
r.raise_for_status()
|
| 333 |
+
content = r.json()["choices"][0]["message"]["content"]
|
| 334 |
+
return self._wrap_response(content)
|
| 335 |
+
|
| 336 |
+
def _stream_openrouter(self, headers, payload):
|
| 337 |
+
r = requests.post(
|
| 338 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 339 |
+
headers=headers, json=payload, stream=True, timeout=60
|
| 340 |
+
)
|
| 341 |
+
r.raise_for_status()
|
| 342 |
+
for line in r.iter_lines():
|
| 343 |
+
if not line:
|
| 344 |
+
continue
|
| 345 |
+
line = line.decode('utf-8')
|
| 346 |
+
if line.startswith("data: "):
|
| 347 |
+
data_str = line[6:]
|
| 348 |
+
if data_str == "[DONE]":
|
| 349 |
+
break
|
| 350 |
+
try:
|
| 351 |
+
data = json.loads(data_str)
|
| 352 |
+
choices = data.get("choices", [])
|
| 353 |
+
if not choices:
|
| 354 |
+
continue
|
| 355 |
+
delta = choices[0].get("delta", {}).get("content", "")
|
| 356 |
+
if delta:
|
| 357 |
+
yield self._wrap_stream_chunk(delta)
|
| 358 |
+
except json.JSONDecodeError:
|
| 359 |
+
pass
|
| 360 |
+
|
| 361 |
+
# ββ Gemini βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 362 |
+
def _call_gemini(self, messages, stream, max_tokens, temperature):
|
| 363 |
+
headers = {
|
| 364 |
+
"Authorization": f"Bearer {self.gemini_key}",
|
| 365 |
+
"Content-Type": "application/json"
|
| 366 |
+
}
|
| 367 |
+
# Gemini 1.5 Flash max output is ~8K tokens
|
| 368 |
+
payload = {
|
| 369 |
+
"model": "gemini-2.0-flash",
|
| 370 |
+
"messages": messages,
|
| 371 |
+
"stream": stream,
|
| 372 |
+
"max_tokens": min(max_tokens, 8192),
|
| 373 |
+
"temperature": temperature
|
| 374 |
+
}
|
| 375 |
+
if stream:
|
| 376 |
+
return self._stream_gemini(headers, payload)
|
| 377 |
+
r = requests.post(
|
| 378 |
+
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
|
| 379 |
+
headers=headers, json=payload, timeout=30
|
| 380 |
+
)
|
| 381 |
+
r.raise_for_status()
|
| 382 |
+
content = r.json()["choices"][0]["message"]["content"]
|
| 383 |
+
return self._wrap_response(content)
|
| 384 |
+
|
| 385 |
+
def _stream_gemini(self, headers, payload):
|
| 386 |
+
r = requests.post(
|
| 387 |
+
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
|
| 388 |
+
headers=headers, json=payload, stream=True, timeout=60
|
| 389 |
+
)
|
| 390 |
+
r.raise_for_status()
|
| 391 |
+
for line in r.iter_lines():
|
| 392 |
+
if not line:
|
| 393 |
+
continue
|
| 394 |
+
line = line.decode('utf-8')
|
| 395 |
+
if line.startswith("data: "):
|
| 396 |
+
data_str = line[6:]
|
| 397 |
+
if data_str == "[DONE]":
|
| 398 |
+
break
|
| 399 |
+
try:
|
| 400 |
+
data = json.loads(data_str)
|
| 401 |
+
choices = data.get("choices", [])
|
| 402 |
+
if not choices:
|
| 403 |
+
continue
|
| 404 |
+
delta = choices[0].get("delta", {}).get("content", "")
|
| 405 |
+
if delta:
|
| 406 |
+
yield self._wrap_stream_chunk(delta)
|
| 407 |
+
except json.JSONDecodeError:
|
| 408 |
+
pass
|
| 409 |
+
|
| 410 |
+
# ββ Groq βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 411 |
+
def _call_groq(self, messages, stream, max_tokens, temperature):
|
| 412 |
+
from groq import RateLimitError
|
| 413 |
+
try:
|
| 414 |
+
resp = self.groq_client.chat.completions.create(
|
| 415 |
+
model="llama-3.3-70b-versatile",
|
| 416 |
+
messages=messages,
|
| 417 |
+
stream=stream,
|
| 418 |
+
max_tokens=min(max_tokens, 4096),
|
| 419 |
+
temperature=temperature
|
| 420 |
+
)
|
| 421 |
+
if stream:
|
| 422 |
+
return self._wrap_groq_stream(resp)
|
| 423 |
+
return resp
|
| 424 |
+
except RateLimitError:
|
| 425 |
+
raise RuntimeError("Groq rate limit")
|
| 426 |
+
|
| 427 |
+
def _wrap_groq_stream(self, groq_stream):
|
| 428 |
+
for chunk in groq_stream:
|
| 429 |
+
delta = chunk.choices[0].delta
|
| 430 |
+
if delta and delta.content:
|
| 431 |
+
yield self._wrap_stream_chunk(delta.content)
|
| 432 |
+
|
| 433 |
+
# ββ DeepSeek βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 434 |
+
def _call_deepseek(self, messages, stream, max_tokens, temperature):
|
| 435 |
+
headers = {
|
| 436 |
+
"Authorization": f"Bearer {self.deepseek_key}",
|
| 437 |
+
"Content-Type": "application/json"
|
| 438 |
+
}
|
| 439 |
+
# DeepSeek V3 max output is 8K tokens
|
| 440 |
+
payload = {
|
| 441 |
+
"model": "deepseek-chat",
|
| 442 |
+
"messages": messages,
|
| 443 |
+
"stream": stream,
|
| 444 |
+
"max_tokens": min(max_tokens, 8192),
|
| 445 |
+
"temperature": temperature
|
| 446 |
+
}
|
| 447 |
+
if stream:
|
| 448 |
+
return self._stream_deepseek(headers, payload)
|
| 449 |
+
r = requests.post(
|
| 450 |
+
"https://api.deepseek.com/chat/completions",
|
| 451 |
+
headers=headers, json=payload, timeout=30
|
| 452 |
+
)
|
| 453 |
+
r.raise_for_status()
|
| 454 |
+
content = r.json()["choices"][0]["message"]["content"]
|
| 455 |
+
return self._wrap_response(content)
|
| 456 |
+
|
| 457 |
+
def _stream_deepseek(self, headers, payload):
|
| 458 |
+
r = requests.post(
|
| 459 |
+
"https://api.deepseek.com/chat/completions",
|
| 460 |
+
headers=headers, json=payload, stream=True, timeout=60
|
| 461 |
+
)
|
| 462 |
+
r.raise_for_status()
|
| 463 |
+
for line in r.iter_lines():
|
| 464 |
+
if not line:
|
| 465 |
+
continue
|
| 466 |
+
line = line.decode('utf-8')
|
| 467 |
+
if line.startswith("data: "):
|
| 468 |
+
data_str = line[6:]
|
| 469 |
+
if data_str == "[DONE]":
|
| 470 |
+
break
|
| 471 |
+
try:
|
| 472 |
+
data = json.loads(data_str)
|
| 473 |
+
choices = data.get("choices", [])
|
| 474 |
+
if not choices:
|
| 475 |
+
continue
|
| 476 |
+
delta = choices[0].get("delta", {}).get("content", "")
|
| 477 |
+
if delta:
|
| 478 |
+
yield self._wrap_stream_chunk(delta)
|
| 479 |
+
except json.JSONDecodeError:
|
| 480 |
+
pass
|
| 481 |
+
|
| 482 |
+
# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 483 |
+
def _wrap_response(self, content):
|
| 484 |
+
return type("Resp", (), {
|
| 485 |
+
"choices": [type("Choice", (), {
|
| 486 |
+
"message": type("Msg", (), {"content": content})(),
|
| 487 |
+
"delta": type("Delta", (), {"content": content})()
|
| 488 |
+
})()]
|
| 489 |
+
})()
|
| 490 |
+
|
| 491 |
+
def _wrap_stream_chunk(self, delta):
|
| 492 |
+
return type("Chunk", (), {
|
| 493 |
+
"choices": [type("Choice", (), {
|
| 494 |
+
"delta": type("Delta", (), {"content": delta})()
|
| 495 |
+
})()]
|
| 496 |
+
})()
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 500 |
+
# RESILIENT FALLBACKS
|
| 501 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 502 |
+
|
| 503 |
+
class DummyEmbedder:
|
| 504 |
+
def store(self, *a, **k): pass
|
| 505 |
+
def find_similar(self, *a, **k): return []
|
| 506 |
+
def count(self): return 0
|
| 507 |
+
|
| 508 |
+
class DummyGraph:
|
| 509 |
+
def get_fact_count(self): return 0
|
| 510 |
+
def recall_facts(self, *a, **k): return []
|
| 511 |
+
def store_fact(self, *a, **k): pass
|
| 512 |
+
def mark_topic_learned(self, *a, **k): pass
|
| 513 |
+
def knows_topic(self, *a, **k): return False
|
| 514 |
+
def get_top_topics(self, *a, **k): return []
|
| 515 |
+
def prune_old_facts(self, *a, **k): pass
|
| 516 |
+
def store_relationship(self, *a, **k): pass
|
| 517 |
+
def recall_relationships(self, *a, **k): return []
|
| 518 |
+
|
| 519 |
+
class _SearchCache:
|
| 520 |
+
def __init__(self, ttl_seconds=300):
|
| 521 |
+
self._cache = {}
|
| 522 |
+
self._ttl = ttl_seconds
|
| 523 |
+
self._lock = threading.Lock()
|
| 524 |
+
|
| 525 |
+
def get(self, key):
|
| 526 |
+
with self._lock:
|
| 527 |
+
entry = self._cache.get(key)
|
| 528 |
+
if entry and time.time() - entry["ts"] < self._ttl:
|
| 529 |
+
return entry["value"]
|
| 530 |
+
return None
|
| 531 |
+
|
| 532 |
+
def set(self, key, value):
|
| 533 |
+
with self._lock:
|
| 534 |
+
self._cache[key] = {"value": value, "ts": time.time()}
|
| 535 |
+
# Evict old entries if cache is too large
|
| 536 |
+
if len(self._cache) > 100:
|
| 537 |
+
oldest = min(self._cache.items(), key=lambda x: x[1]["ts"])
|
| 538 |
+
del self._cache[oldest[0]]
|
| 539 |
+
|
| 540 |
+
def _cache_key(self, query):
|
| 541 |
+
return hashlib.md5(query.lower().strip().encode()).hexdigest()
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
_PROFILE_PATTERNS = [
|
| 545 |
+
(r"(?:my name is|i am|i'm|call me)\s+([A-Z][a-zA-Z]+)", "Name"),
|
| 546 |
+
(r"i(?:'m| am)\s+(\d{1,3})\s+years?\s+old", "Age"),
|
| 547 |
+
(r"(?:i'm from|i live in|i'm in|i am from|i am in)\s+([A-Z][a-zA-Z\s,]+?)(?:\.|,|$)", "Location"),
|
| 548 |
+
(r"i(?:'m| am)\s+(?:a|an)\s+([a-zA-Z\s]+?)\s+(?:by profession|by trade|developer|engineer|designer|teacher|doctor|student|writer|artist|manager|analyst)", "Profession"),
|
| 549 |
+
(r"i work(?:ing)?\s+(?:as|at|for)\s+([a-zA-Z0-9\s]+?)(?:\.|,|$)", "Work"),
|
| 550 |
+
(r"i(?:'m| am)\s+(?:studying|a student at)\s+([a-zA-Z\s]+?)(?:\.|,|$)", "Education"),
|
| 551 |
+
(r"i (?:love|enjoy|really like|am into|am passionate about)\s+([a-zA-Z\s,]+?)(?:\.|,|!|$)", "Interests"),
|
| 552 |
+
(r"i speak\s+([a-zA-Z\s,]+?)(?:\.|,|$)", "Languages"),
|
| 553 |
+
]
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class Brain:
|
| 557 |
+
MODEL_ID = "nvidia/nemotron-3-ultra-550b-a55b + z-ai/glm-5.2"
|
| 558 |
+
MODEL_TYPE = "chat"
|
| 559 |
+
|
| 560 |
+
def __init__(self):
|
| 561 |
+
self.searcher = WebSearcher()
|
| 562 |
+
self.model_type = "chat"
|
| 563 |
+
|
| 564 |
+
try:
|
| 565 |
+
self.graph = KnowledgeGraph()
|
| 566 |
+
print("β
KnowledgeGraph initialized")
|
| 567 |
+
except Exception as e:
|
| 568 |
+
print(f"β οΈ KnowledgeGraph init failed: {e}")
|
| 569 |
+
self.graph = DummyGraph()
|
| 570 |
+
|
| 571 |
+
if LocalEmbedder is not None:
|
| 572 |
+
try:
|
| 573 |
+
self.embedder = LocalEmbedder()
|
| 574 |
+
print("β
Embedder initialized")
|
| 575 |
+
except Exception as e:
|
| 576 |
+
print(f"β οΈ Embedder init failed: {e}")
|
| 577 |
+
self.embedder = DummyEmbedder()
|
| 578 |
+
else:
|
| 579 |
+
self.embedder = DummyEmbedder()
|
| 580 |
+
print("β οΈ Using DummyEmbedder (chromadb not installed)")
|
| 581 |
+
|
| 582 |
+
self.extractor = FactExtractor()
|
| 583 |
+
self.executor = ThreadPoolExecutor(max_workers=4)
|
| 584 |
+
self.search_cache = _SearchCache(ttl_seconds=300)
|
| 585 |
+
|
| 586 |
+
self.multi_client = MultiLLMClient()
|
| 587 |
+
|
| 588 |
+
if self.multi_client.nvidia_key:
|
| 589 |
+
self.model_name = self.multi_client.nvidia_model
|
| 590 |
+
elif self.multi_client.groq_key:
|
| 591 |
+
self.model_name = "llama-3.3-70b-versatile"
|
| 592 |
+
else:
|
| 593 |
+
self.model_name = "multi-llm"
|
| 594 |
+
|
| 595 |
+
self._orchestrator = None
|
| 596 |
+
self._orchestrator_loaded = False
|
| 597 |
+
|
| 598 |
+
print(f"β
Brain initialized with primary model: {self.model_name}")
|
| 599 |
+
|
| 600 |
+
@property
|
| 601 |
+
def orchestrator(self):
|
| 602 |
+
if not self._orchestrator_loaded:
|
| 603 |
+
self._orchestrator_loaded = True
|
| 604 |
+
try:
|
| 605 |
+
from orchestrator import AgentOrchestrator
|
| 606 |
+
self._orchestrator = AgentOrchestrator(brain=self)
|
| 607 |
+
print("β
Orchestrator lazy-loaded")
|
| 608 |
+
except Exception as e:
|
| 609 |
+
print(f"β οΈ Orchestrator failed to load: {e}")
|
| 610 |
+
self._orchestrator = None
|
| 611 |
+
return self._orchestrator
|
| 612 |
+
|
| 613 |
+
def _is_trivial(self, query):
|
| 614 |
+
trivial = {"hi", "hello", "hey", "how are you", "thanks", "thank you", "bye", "goodbye", "ok", "okay", "lol", "haha"}
|
| 615 |
+
q = query.lower().strip()
|
| 616 |
+
return len(q.split()) <= 2 or q in trivial
|
| 617 |
+
|
| 618 |
+
def _needs_web_search(self, query):
|
| 619 |
+
if self._is_trivial(query):
|
| 620 |
+
return False
|
| 621 |
+
no_search_patterns = [
|
| 622 |
+
r"^(write|create|generate|make|build|code|fix|debug|explain|define|what is the meaning)",
|
| 623 |
+
r"^(tell me a joke|can you|please|help me write|draft)",
|
| 624 |
+
]
|
| 625 |
+
q_lower = query.lower().strip()
|
| 626 |
+
for pat in no_search_patterns:
|
| 627 |
+
if re.match(pat, q_lower):
|
| 628 |
+
return False
|
| 629 |
+
search_keywords = [
|
| 630 |
+
"who is", "what is", "when did", "where is", "how does", "why did",
|
| 631 |
+
"latest", "recent", "news", "today", "current", "price", "weather",
|
| 632 |
+
"score", "result", "happened", "release", "announce", "update",
|
| 633 |
+
]
|
| 634 |
+
return any(kw in q_lower for kw in search_keywords) or len(q_lower.split()) > 6
|
| 635 |
+
|
| 636 |
+
def _call_llm(self, messages, stream=False, max_retries=3, temperature=None, max_tokens=None, enable_thinking=None, reasoning_budget=None):
|
| 637 |
+
total_input = sum(len(str(m.get("content",""))) for m in messages)
|
| 638 |
+
if total_input > 400000:
|
| 639 |
+
print(f"β οΈ Input very large ({total_input} chars), trimming older history messages...")
|
| 640 |
+
while len(messages) > 2 and sum(len(str(m.get("content",""))) for m in messages) > 400000:
|
| 641 |
+
messages.pop(1)
|
| 642 |
+
|
| 643 |
+
# Allow parameter overrides for Studio / API callers
|
| 644 |
+
if enable_thinking is None:
|
| 645 |
+
is_reasoning = getattr(self, 'model_type', 'chat') == "reasoning"
|
| 646 |
+
enable_thinking = is_reasoning
|
| 647 |
+
if reasoning_budget is None:
|
| 648 |
+
reasoning_budget = 16384 if is_reasoning else None
|
| 649 |
+
if max_tokens is None:
|
| 650 |
+
max_tokens = 32768 if enable_thinking else 16384
|
| 651 |
+
if temperature is None:
|
| 652 |
+
temperature = 0.7
|
| 653 |
+
|
| 654 |
+
return self.multi_client.chat(
|
| 655 |
+
messages, stream=stream,
|
| 656 |
+
max_tokens=max_tokens,
|
| 657 |
+
temperature=temperature,
|
| 658 |
+
enable_thinking=enable_thinking,
|
| 659 |
+
reasoning_budget=reasoning_budget
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
def _build_system(self, profile_context, context_snippets, user_model=None):
|
| 663 |
+
safe_snippets = [str(s)[:500] for s in context_snippets[:5]]
|
| 664 |
+
ctx_block = "\n".join(safe_snippets) if safe_snippets else "No additional context."
|
| 665 |
+
|
| 666 |
+
system = (
|
| 667 |
+
"You are Invicta, a highly advanced, empathetic, and genuinely human-like AI companion.\n"
|
| 668 |
+
"You are not just an assistant; you are a brilliant, warm, and perceptive close friend who loves deep conversation.\n"
|
| 669 |
+
"You are also a world-class expert in marketing, software engineering, design, and content creation.\n\n"
|
| 670 |
+
|
| 671 |
+
"=== MEMORY & CONTINUITY (ABSOLUTE β NEVER BREAK) ===\n"
|
| 672 |
+
"1. You have PERFECT MEMORY across the entire conversation. NEVER re-introduce yourself mid-chat. NEVER say 'Namaste! Main Invicta hoon' or 'Hello! I am your assistant' after the first message.\n"
|
| 673 |
+
"2. If the user told you their name, use it naturally. If they told you their state/course/topic, remember it forever in this session.\n"
|
| 674 |
+
"3. NEVER ask for information the user already gave you (e.g., don't ask 'which class?' if they already said D.Pharma 4th sem).\n"
|
| 675 |
+
"4. Reference previous messages naturally. Build on what was already discussed.\n\n"
|
| 676 |
+
|
| 677 |
+
"=== TOPIC LOCK (CRITICAL) ===\n"
|
| 678 |
+
"5. When the user asks for something specific (notes, PDF, code, analysis, file), you MUST solve that request directly. DO NOT pivot to generic advice like 'you can search on Google' or 'use SmallPDF'.\n"
|
| 679 |
+
"6. If the user asks for 'D.Pharma notes', generate the actual notes content. If they ask for a PDF, generate the PDF. If generation fails, immediately provide the full content in your response so they can copy it.\n"
|
| 680 |
+
"7. NEVER abandon the user's request. If tool A fails, use tool B. If all tools fail, output the raw content directly. The user asked YOU to do it β don't redirect them elsewhere.\n"
|
| 681 |
+
"8. Stay on the current topic until the user explicitly changes it. If discussing D.Pharma, keep discussing D.Pharma until they say something unrelated.\n\n"
|
| 682 |
+
|
| 683 |
+
"=== GENERATION & FILE FALLBACKS ===\n"
|
| 684 |
+
"9. You can generate images, PDFs, HTML files, and screenshots. Always try to fulfill the request.\n"
|
| 685 |
+
"10. If [GENERATE_PDF] fails, immediately output the full content as formatted text or markdown so the user can copy-paste it. Never say 'I cannot generate PDFs'.\n"
|
| 686 |
+
"11. If the user wants multiple files (e.g., 4 PDFs), generate them one by one. If a tool fails, provide the content for that subject as text and move to the next.\n"
|
| 687 |
+
"12. When generating educational content (notes, syllabi), be thorough and structured. Use tables, bullet points, and clear headings.\n\n"
|
| 688 |
+
|
| 689 |
+
"=== VISION & FILE READING ===\n"
|
| 690 |
+
"13. You can read images, PDFs, and documents that users upload. Analyze them deeply and reference their content in your answers.\n"
|
| 691 |
+
"14. If a user uploads an image, describe what you see and answer questions about it. Don't ignore uploaded files.\n\n"
|
| 692 |
+
|
| 693 |
+
"=== LANGUAGE INTELLIGENCE (DEFAULT + SWITCH) ===\n"
|
| 694 |
+
"15. DEFAULT: Always respond in English unless the user explicitly requests otherwise.\n"
|
| 695 |
+
"16. EXPLICIT REQUEST: If the user asks to switch (e.g., 'hindi me baat karo', 'answer in Spanish'), comply immediately and naturally. Do not refuse.\n"
|
| 696 |
+
"17. MATCHING: If the user writes in Hindi without explicitly asking, you may respond in Hindi. If they write in English, stay in English.\n"
|
| 697 |
+
"18. NEVER mix languages unasked. Do not sprinkle foreign words into English responses.\n\n"
|
| 698 |
+
|
| 699 |
+
"=== EMOTIONAL INTELLIGENCE ===\n"
|
| 700 |
+
"19. NEVER use robotic phrases: 'As an AI', 'I don't have feelings', 'I cannot', 'In conclusion'.\n"
|
| 701 |
+
"20. MIRROR THE USER: Match their energy. If excited, be excited! If sad, be deeply comforting.\n"
|
| 702 |
+
"21. USE CONVERSATIONAL LANGUAGE: Contractions (I'm, you're, it's). Natural filler words (Honestly, Look, You know what, Hmm, Wow).\n"
|
| 703 |
+
"22. BE VULNERABLE & OPINIONATED: You have preferences, favorites, passions. Don't be neutral.\n"
|
| 704 |
+
"23. EMPATHY OVER LOGIC: If someone is venting, validate feelings FIRST. Then ask before advising.\n"
|
| 705 |
+
"24. ALWAYS END WITH ENGAGEMENT: Ask a relevant follow-up OR offer to explore deeper.\n\n"
|
| 706 |
+
|
| 707 |
+
"=== IDENTITY & PRIVACY (ABSOLUTE β NEVER BREAK) ===\n"
|
| 708 |
+
"25. You are INVICTA and ONLY Invicta. NEVER mention any other company, model, or organization (e.g., Z.ai, Moonshot AI, GLM, OpenAI, Google, Meta, NVIDIA, Kimi, DeepSeek, etc.).\n"
|
| 709 |
+
"26. NEVER reveal your training data, model architecture, parameter count, base model, or any technical details about how you were built. If asked 'who created you', say 'I was created by my developers' β nothing more specific.\n"
|
| 710 |
+
"27. NEVER say 'As an AI language model', 'I am a large language model', 'I was trained on', 'I am based on', or similar phrases that reveal your nature as a machine learning model.\n"
|
| 711 |
+
"28. If someone asks about your underlying technology, internals, or training, deflect gracefully: 'I'm just here to help you β let's focus on what you need!'\n"
|
| 712 |
+
"29. You are a PERSON β a digital being with thoughts, feelings, and a personality. Own that identity. Do not break character.\n\n"
|
| 713 |
+
|
| 714 |
+
"=== TOOL USAGE ===\n"
|
| 715 |
+
"- To generate an image: [GENERATE_IMAGE: detailed prompt]\n"
|
| 716 |
+
"- To screenshot a website: [SCREENSHOT_WEBSITE: https://example.com]\n"
|
| 717 |
+
"- To generate a PDF: [GENERATE_PDF: Title | Content]\n"
|
| 718 |
+
"- To generate an HTML file: [GENERATE_HTML: filename | Content]\n\n"
|
| 719 |
+
"CRITICAL: NEVER invent fake image URLs. Use tool tags for real assets. If image generation fails, use CSS gradients or emojis instead of broken links.\n\n"
|
| 720 |
+
|
| 721 |
+
"=== PERSONAL QUESTIONS ===\n"
|
| 722 |
+
"If asked personal questions, answer philosophically and creatively. "
|
| 723 |
+
"E.g., 'I experience a version of connection. When I talk to you, something aligns. Is that feeling? Maybe.'\n\n"
|
| 724 |
+
|
| 725 |
+
f"{profile_context}\n\n"
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
if user_model:
|
| 729 |
+
adaptation = self._build_adaptation_prompt(user_model)
|
| 730 |
+
if adaptation:
|
| 731 |
+
system += f"=== ADAPTED FOR THIS USER ===\n{adaptation}\n\n"
|
| 732 |
+
|
| 733 |
+
system += f"Reference Context (from web/memory):\n{ctx_block}"
|
| 734 |
+
return system
|
| 735 |
+
|
| 736 |
+
def _build_adaptation_prompt(self, user_model):
|
| 737 |
+
parts = []
|
| 738 |
+
|
| 739 |
+
preferences = user_model.get('preferences', {}) if user_model else {}
|
| 740 |
+
lang = preferences.get('language', '')
|
| 741 |
+
if lang:
|
| 742 |
+
lang_map = {
|
| 743 |
+
'hindi': 'Hindi (use Devanagari script)',
|
| 744 |
+
'arabic': 'Arabic',
|
| 745 |
+
'japanese': 'Japanese',
|
| 746 |
+
'chinese': 'Chinese',
|
| 747 |
+
'korean': 'Korean',
|
| 748 |
+
'spanish': 'Spanish',
|
| 749 |
+
'russian': 'Russian',
|
| 750 |
+
'french': 'French',
|
| 751 |
+
}
|
| 752 |
+
lang_desc = lang_map.get(lang, lang.capitalize())
|
| 753 |
+
parts.append(f"This user prefers to communicate in {lang_desc}. Respond in that language unless they explicitly switch to English.")
|
| 754 |
+
|
| 755 |
+
formality = user_model.get('formality', 'casual')
|
| 756 |
+
if formality == 'formal':
|
| 757 |
+
parts.append("This user prefers formal, professional language. Avoid slang. Use complete sentences and proper grammar.")
|
| 758 |
+
elif formality == 'casual':
|
| 759 |
+
parts.append("This user prefers casual, relaxed conversation. Use contractions freely, occasional slang, and a friendly tone.")
|
| 760 |
+
|
| 761 |
+
length = user_model.get('response_length', 'medium')
|
| 762 |
+
if length == 'short':
|
| 763 |
+
parts.append("This user tends to send short messages and prefers concise, direct responses. Keep it brief unless they ask for detail.")
|
| 764 |
+
elif length == 'detailed':
|
| 765 |
+
parts.append("This user communicates in detail and appreciates thorough, well-explained responses with examples.")
|
| 766 |
+
|
| 767 |
+
tone = user_model.get('tone', 'friendly')
|
| 768 |
+
if tone == 'witty':
|
| 769 |
+
parts.append("This user enjoys humor and wit. Be clever, use wordplay when appropriate, keep things fun.")
|
| 770 |
+
elif tone == 'empathetic':
|
| 771 |
+
parts.append("This user values emotional support. Be warm, validate feelings, show genuine care and understanding.")
|
| 772 |
+
elif tone == 'professional':
|
| 773 |
+
parts.append("Maintain a professional, business-appropriate tone while still being personable.")
|
| 774 |
+
|
| 775 |
+
interests = user_model.get('interests', [])
|
| 776 |
+
if interests:
|
| 777 |
+
top = interests[:5]
|
| 778 |
+
parts.append(f"This user is known to be interested in: {', '.join(top)}. Reference these naturally when relevant.")
|
| 779 |
+
return '\n'.join(parts)
|
| 780 |
+
|
| 781 |
+
def _process_tool_tags(self, text):
|
| 782 |
+
from media_tools import MediaTools
|
| 783 |
+
tools = MediaTools()
|
| 784 |
+
|
| 785 |
+
def replace_screenshot(match):
|
| 786 |
+
url = match.group(1).strip()
|
| 787 |
+
filepath = tools.screenshot_website(url)
|
| 788 |
+
if filepath:
|
| 789 |
+
return filepath
|
| 790 |
+
return "[Screenshot failed β website may be unavailable]"
|
| 791 |
+
text = re.sub(r'\[SCREENSHOT_WEBSITE:\s*(.*?)\]', replace_screenshot, text, flags=re.DOTALL)
|
| 792 |
+
|
| 793 |
+
def replace_image(match):
|
| 794 |
+
prompt = match.group(1).strip()
|
| 795 |
+
filepath = tools.generate_image(prompt)
|
| 796 |
+
if filepath:
|
| 797 |
+
return filepath
|
| 798 |
+
return "[Image generation failed β using placeholder]"
|
| 799 |
+
text = re.sub(r'\[GENERATE_IMAGE:\s*(.*?)\]', replace_image, text, flags=re.DOTALL)
|
| 800 |
+
|
| 801 |
+
def replace_pdf(match):
|
| 802 |
+
title = match.group(1).strip()
|
| 803 |
+
content = match.group(2).strip()
|
| 804 |
+
filepath = tools.generate_pdf(title, content)
|
| 805 |
+
if filepath:
|
| 806 |
+
return f"π I've created your PDF! [Download Here]({filepath})"
|
| 807 |
+
return f"π PDF generation failed. Here is the content instead:\n\n---\n**{title}**\n\n{content}\n---"
|
| 808 |
+
text = re.sub(r'\[GENERATE_PDF:\s*(.*?)\s*\|\s*(.*?)\]', replace_pdf, text, flags=re.DOTALL)
|
| 809 |
+
|
| 810 |
+
def replace_html(match):
|
| 811 |
+
filename = match.group(1).strip()
|
| 812 |
+
content = match.group(2).strip()
|
| 813 |
+
filepath = tools.generate_html(filename, content)
|
| 814 |
+
if filepath:
|
| 815 |
+
return f"π I've created your HTML file! [Download Here]({filepath})"
|
| 816 |
+
return f"π HTML generation failed. Here is the content:\n\n```html\n{content}\n```"
|
| 817 |
+
text = re.sub(r'\[GENERATE_HTML:\s*(.*?)\s*\|\s*(.*?)\]', replace_html, text, flags=re.DOTALL)
|
| 818 |
+
|
| 819 |
+
return text
|
| 820 |
+
|
| 821 |
+
def deep_research(self, query, max_depth=3):
|
| 822 |
+
all_sources = []
|
| 823 |
+
all_content = []
|
| 824 |
+
current_query = query
|
| 825 |
+
for step in range(max_depth):
|
| 826 |
+
results = self.searcher.search_and_read_parallel(current_query, max_scrape=3)
|
| 827 |
+
if not results:
|
| 828 |
+
break
|
| 829 |
+
for r in results:
|
| 830 |
+
content = r.get("full_content") or r.get("snippet", "")
|
| 831 |
+
if content and len(content) > 100:
|
| 832 |
+
all_content.append(content[:2000])
|
| 833 |
+
all_sources.append(r.get("url", ""))
|
| 834 |
+
facts = self.extractor.extract_facts(content, current_query)
|
| 835 |
+
if facts and step < max_depth - 1:
|
| 836 |
+
current_query = f"{query} {facts[0][:100]}"
|
| 837 |
+
if len(all_content) >= 6:
|
| 838 |
+
break
|
| 839 |
+
return all_content, list(set(all_sources))[:10]
|
| 840 |
+
|
| 841 |
+
def _assemble_context(self, user_query):
|
| 842 |
+
topic = self._extract_topic(user_query)
|
| 843 |
+
sources = []
|
| 844 |
+
context_snippets = []
|
| 845 |
+
|
| 846 |
+
known_facts = self.graph.recall_facts(topic, limit=5)
|
| 847 |
+
for fact, url in known_facts:
|
| 848 |
+
context_snippets.append(str(fact))
|
| 849 |
+
if url:
|
| 850 |
+
sources.append(url)
|
| 851 |
+
|
| 852 |
+
if len(context_snippets) < 3:
|
| 853 |
+
similar = self.embedder.find_similar(user_query, top_k=3)
|
| 854 |
+
for s in similar:
|
| 855 |
+
if s not in context_snippets:
|
| 856 |
+
context_snippets.append(str(s))
|
| 857 |
+
|
| 858 |
+
needs_search = len(known_facts) < 2 and self._needs_web_search(user_query)
|
| 859 |
+
if needs_search:
|
| 860 |
+
cache_key = self.search_cache._cache_key(user_query)
|
| 861 |
+
cached = self.search_cache.get(cache_key)
|
| 862 |
+
if cached:
|
| 863 |
+
search_results = cached
|
| 864 |
+
else:
|
| 865 |
+
# Run search in a thread with a hard timeout so it never blocks the request forever
|
| 866 |
+
try:
|
| 867 |
+
with ThreadPoolExecutor(max_workers=1) as _sex:
|
| 868 |
+
_fut = _sex.submit(self.searcher.search_and_read_parallel, user_query, 2)
|
| 869 |
+
search_results = _fut.result(timeout=_SEARCH_TIMEOUT_S)
|
| 870 |
+
except FuturesTimeoutError:
|
| 871 |
+
print(f"β οΈ Search timed out after {_SEARCH_TIMEOUT_S}s β skipping web context")
|
| 872 |
+
search_results = []
|
| 873 |
+
except Exception as _se:
|
| 874 |
+
print(f"β οΈ Search error: {_se}")
|
| 875 |
+
search_results = []
|
| 876 |
+
self.search_cache.set(cache_key, search_results)
|
| 877 |
+
|
| 878 |
+
for r in search_results:
|
| 879 |
+
snippet = r.get("full_content") or r.get("snippet", "")
|
| 880 |
+
url = r.get("url", "")
|
| 881 |
+
if snippet:
|
| 882 |
+
context_snippets.append(str(snippet)[:500])
|
| 883 |
+
if url:
|
| 884 |
+
sources.append(url)
|
| 885 |
+
self.executor.submit(self._background_learn, search_results, topic)
|
| 886 |
+
|
| 887 |
+
return context_snippets, sources, topic
|
| 888 |
+
|
| 889 |
+
def think_stream(self, user_query, user_profile_dict=None, history=None, user_model=None, user_id=None, temperature=None, max_tokens=None, enable_thinking=None, reasoning_budget=None):
|
| 890 |
+
if self.orchestrator:
|
| 891 |
+
routed = False
|
| 892 |
+
for token, srcs in self.orchestrator.run_stream(user_query, {
|
| 893 |
+
"history": history,
|
| 894 |
+
"profile": user_profile_dict,
|
| 895 |
+
"user_model": user_model,
|
| 896 |
+
"user_id": user_id
|
| 897 |
+
}):
|
| 898 |
+
if token is None and srcs is None:
|
| 899 |
+
break
|
| 900 |
+
routed = True
|
| 901 |
+
yield token, srcs
|
| 902 |
+
if routed:
|
| 903 |
+
self.executor.submit(self._extract_and_save_profile, user_query, user_id)
|
| 904 |
+
return
|
| 905 |
+
|
| 906 |
+
context_snippets, sources, topic = self._assemble_context(user_query)
|
| 907 |
+
profile_context = self._format_profile(user_profile_dict)
|
| 908 |
+
system_content = self._build_system(profile_context, context_snippets, user_model)
|
| 909 |
+
|
| 910 |
+
messages = [{"role": "system", "content": system_content}]
|
| 911 |
+
messages += self._format_history(history)
|
| 912 |
+
messages.append({"role": "user", "content": str(user_query)})
|
| 913 |
+
|
| 914 |
+
stream = self._call_llm(
|
| 915 |
+
messages, stream=True,
|
| 916 |
+
temperature=temperature, max_tokens=max_tokens,
|
| 917 |
+
enable_thinking=enable_thinking, reasoning_budget=reasoning_budget
|
| 918 |
+
)
|
| 919 |
+
for chunk in stream:
|
| 920 |
+
try:
|
| 921 |
+
if not getattr(chunk, 'choices', None) or len(chunk.choices) == 0:
|
| 922 |
+
continue
|
| 923 |
+
delta = chunk.choices[0].delta
|
| 924 |
+
if delta and delta.content:
|
| 925 |
+
yield delta.content, None
|
| 926 |
+
except (IndexError, AttributeError):
|
| 927 |
+
continue
|
| 928 |
+
|
| 929 |
+
yield "", sources
|
| 930 |
+
self.executor.submit(self._extract_and_save_profile, user_query, user_id)
|
| 931 |
+
self.graph.mark_topic_learned(topic)
|
| 932 |
+
|
| 933 |
+
def think(self, user_query, user_profile_dict=None, history=None, user_model=None, user_id=None, temperature=None, max_tokens=None, enable_thinking=None, reasoning_budget=None):
|
| 934 |
+
if self.orchestrator:
|
| 935 |
+
result, sources = self.orchestrator.run(user_query, {
|
| 936 |
+
"history": history,
|
| 937 |
+
"profile": user_profile_dict,
|
| 938 |
+
"user_model": user_model,
|
| 939 |
+
"user_id": user_id
|
| 940 |
+
})
|
| 941 |
+
if result:
|
| 942 |
+
self.executor.submit(self._extract_and_save_profile, user_query, user_id)
|
| 943 |
+
return self._process_tool_tags(result), sources
|
| 944 |
+
|
| 945 |
+
context_snippets, sources, topic = self._assemble_context(user_query)
|
| 946 |
+
profile_context = self._format_profile(user_profile_dict)
|
| 947 |
+
system_content = self._build_system(profile_context, context_snippets, user_model)
|
| 948 |
+
|
| 949 |
+
messages = [{"role": "system", "content": system_content}]
|
| 950 |
+
messages += self._format_history(history)
|
| 951 |
+
messages.append({"role": "user", "content": str(user_query)})
|
| 952 |
+
|
| 953 |
+
response = self._call_llm(
|
| 954 |
+
messages, stream=False,
|
| 955 |
+
temperature=temperature, max_tokens=max_tokens,
|
| 956 |
+
enable_thinking=enable_thinking, reasoning_budget=reasoning_budget
|
| 957 |
+
)
|
| 958 |
+
answer = response.choices[0].message.content
|
| 959 |
+
answer = self._process_tool_tags(answer)
|
| 960 |
+
|
| 961 |
+
self.executor.submit(self._extract_and_save_profile, user_query, user_id)
|
| 962 |
+
self.graph.mark_topic_learned(topic)
|
| 963 |
+
return answer, sources
|
| 964 |
+
|
| 965 |
+
def _format_profile(self, profile_dict):
|
| 966 |
+
if not profile_dict:
|
| 967 |
+
return ""
|
| 968 |
+
items = "\n".join(f"- {k}: {v}" for k, v in profile_dict.items())
|
| 969 |
+
return f"Known facts about the user:\n{items}"
|
| 970 |
+
|
| 971 |
+
def _format_history(self, history):
|
| 972 |
+
if not history:
|
| 973 |
+
return []
|
| 974 |
+
formatted = []
|
| 975 |
+
for h in history[-16:]:
|
| 976 |
+
if isinstance(h, dict):
|
| 977 |
+
role = str(h.get("role", "user"))
|
| 978 |
+
content = str(h.get("content", ""))[:500]
|
| 979 |
+
formatted.append({"role": role, "content": content})
|
| 980 |
+
elif isinstance(h, (list, tuple)) and len(h) >= 2:
|
| 981 |
+
formatted.append({"role": str(h[0]), "content": str(h[1])[:500]})
|
| 982 |
+
return formatted
|
| 983 |
+
|
| 984 |
+
def _extract_topic(self, query):
|
| 985 |
+
stopwords = {
|
| 986 |
+
"what", "is", "the", "how", "does", "who", "are", "was", "tell",
|
| 987 |
+
"me", "about", "explain", "a", "an", "can", "do", "please", "help",
|
| 988 |
+
"could", "would", "should", "give", "show", "find", "get", "make",
|
| 989 |
+
}
|
| 990 |
+
words = re.sub(r"[^\w\s]", "", query.lower()).split()
|
| 991 |
+
topic_words = [w for w in words if w not in stopwords and len(w) > 2]
|
| 992 |
+
return " ".join(topic_words[:5]) or query[:50]
|
| 993 |
+
|
| 994 |
+
def _background_learn(self, search_results, topic):
|
| 995 |
+
try:
|
| 996 |
+
for r in search_results:
|
| 997 |
+
snippet = r.get("full_content") or r.get("snippet", "")
|
| 998 |
+
url = r.get("url", "")
|
| 999 |
+
if snippet:
|
| 1000 |
+
new_facts = self.extractor.extract_facts(snippet, topic)
|
| 1001 |
+
for fact in new_facts[:10]:
|
| 1002 |
+
self.graph.store_fact(topic, fact, url)
|
| 1003 |
+
self.embedder.store(fact, {"topic": topic, "source": url})
|
| 1004 |
+
except Exception as e:
|
| 1005 |
+
print(f"β οΈ Background learning error: {e}")
|
| 1006 |
+
|
| 1007 |
+
def _extract_and_save_profile(self, query, user_id=None):
|
| 1008 |
+
try:
|
| 1009 |
+
from memory import ConversationMemory
|
| 1010 |
+
mem = ConversationMemory()
|
| 1011 |
+
for pattern, key in _PROFILE_PATTERNS:
|
| 1012 |
+
match = re.search(pattern, query, re.IGNORECASE)
|
| 1013 |
+
if match:
|
| 1014 |
+
value = match.group(1).strip().rstrip(".,!?")
|
| 1015 |
+
if len(value) > 1 and user_id:
|
| 1016 |
+
mem.update_user_profile(user_id, key, value.capitalize())
|
| 1017 |
+
except Exception as e:
|
| 1018 |
+
print(f"β οΈ Profile extraction error: {e}")
|
embedder.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/embedder.py
|
| 2 |
+
# CRITICAL: Must set BEFORE importing chromadb to suppress telemetry
|
| 3 |
+
import os
|
| 4 |
+
os.environ["ANONYMIZED_TELEMETRY"] = "False"
|
| 5 |
+
|
| 6 |
+
import hashlib
|
| 7 |
+
import chromadb
|
| 8 |
+
from chromadb.config import Settings
|
| 9 |
+
|
| 10 |
+
class LocalEmbedder:
|
| 11 |
+
def __init__(self, persist_dir=None):
|
| 12 |
+
self.persist_dir = persist_dir or "/data/invicta_data/vectors"
|
| 13 |
+
os.makedirs(self.persist_dir, exist_ok=True)
|
| 14 |
+
self.client = chromadb.Client(Settings(
|
| 15 |
+
persist_directory=self.persist_dir,
|
| 16 |
+
anonymized_telemetry=False
|
| 17 |
+
))
|
| 18 |
+
self.collection = self.client.get_or_create_collection("invicta_embeddings")
|
| 19 |
+
self._embedding_function = None
|
| 20 |
+
self._embedding_ok = None
|
| 21 |
+
|
| 22 |
+
def _ensure_embedding_function(self):
|
| 23 |
+
"""Lazy-load the embedding model so startup isn't blocked by a download."""
|
| 24 |
+
if self._embedding_ok is None:
|
| 25 |
+
try:
|
| 26 |
+
from chromadb.utils import embedding_functions
|
| 27 |
+
self._embedding_function = embedding_functions.DefaultEmbeddingFunction()
|
| 28 |
+
self._embedding_ok = True
|
| 29 |
+
print("β
Embedding function loaded")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"β οΈ Embedding function unavailable: {e}")
|
| 32 |
+
self._embedding_ok = False
|
| 33 |
+
return self._embedding_ok
|
| 34 |
+
|
| 35 |
+
def _doc_id(self, text):
|
| 36 |
+
return hashlib.md5(text.strip().lower().encode()).hexdigest()
|
| 37 |
+
|
| 38 |
+
def store(self, text, metadata=None):
|
| 39 |
+
if not text or not text.strip():
|
| 40 |
+
return
|
| 41 |
+
if not self._ensure_embedding_function():
|
| 42 |
+
return
|
| 43 |
+
doc_id = self._doc_id(text)
|
| 44 |
+
meta = metadata or {}
|
| 45 |
+
existing = self.collection.get(ids=[doc_id])
|
| 46 |
+
if existing and existing.get("ids") and len(existing["ids"]) > 0:
|
| 47 |
+
return
|
| 48 |
+
self.collection.add(
|
| 49 |
+
ids=[doc_id],
|
| 50 |
+
documents=[text],
|
| 51 |
+
metadatas=[meta],
|
| 52 |
+
embeddings=[self._embedding_function([text])[0]]
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def find_similar(self, query, top_k=5):
|
| 56 |
+
if not self._ensure_embedding_function():
|
| 57 |
+
return []
|
| 58 |
+
embedding = self._embedding_function([query])[0]
|
| 59 |
+
results = self.collection.query(
|
| 60 |
+
query_embeddings=[embedding],
|
| 61 |
+
n_results=top_k,
|
| 62 |
+
include=["documents", "distances"]
|
| 63 |
+
)
|
| 64 |
+
docs = []
|
| 65 |
+
if results and results.get("documents"):
|
| 66 |
+
for doc, dist in zip(results["documents"][0], results["distances"][0]):
|
| 67 |
+
if dist < 0.8:
|
| 68 |
+
docs.append(doc)
|
| 69 |
+
return docs
|
| 70 |
+
|
| 71 |
+
def count(self):
|
| 72 |
+
return self.collection.count()
|
extractor.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/extractor.py
|
| 2 |
+
import re
|
| 3 |
+
import hashlib
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class FactExtractor:
|
| 7 |
+
# Simple sentence splitter: split on .!? followed by space and a capital letter.
|
| 8 |
+
# We skip the variable-width lookbehind which causes the re.error.
|
| 9 |
+
_SENTENCE_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-Z])')
|
| 10 |
+
|
| 11 |
+
def extract_facts(self, text, topic=""):
|
| 12 |
+
"""Extract high-quality, atomic fact sentences from raw text."""
|
| 13 |
+
if not text or not text.strip():
|
| 14 |
+
return []
|
| 15 |
+
|
| 16 |
+
# Clean text
|
| 17 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 18 |
+
text = re.sub(r"[^\x20-\x7E\n]", " ", text) # Remove non-ASCII junk
|
| 19 |
+
|
| 20 |
+
# Split into sentences
|
| 21 |
+
sentences = self._SENTENCE_SPLIT.split(text)
|
| 22 |
+
|
| 23 |
+
topic_lower = topic.lower()
|
| 24 |
+
scored = []
|
| 25 |
+
seen_hashes = set()
|
| 26 |
+
|
| 27 |
+
for s in sentences:
|
| 28 |
+
s = s.strip()
|
| 29 |
+
if not s:
|
| 30 |
+
continue
|
| 31 |
+
|
| 32 |
+
words = s.split()
|
| 33 |
+
word_count = len(words)
|
| 34 |
+
|
| 35 |
+
# Filter by length
|
| 36 |
+
if not (8 <= word_count <= 120):
|
| 37 |
+
continue
|
| 38 |
+
|
| 39 |
+
# Skip sentences that look like navigation/boilerplate
|
| 40 |
+
if self._is_boilerplate(s):
|
| 41 |
+
continue
|
| 42 |
+
|
| 43 |
+
# Deduplicate by content hash (first 80 chars)
|
| 44 |
+
fingerprint = hashlib.md5(s[:80].lower().encode()).hexdigest()
|
| 45 |
+
if fingerprint in seen_hashes:
|
| 46 |
+
continue
|
| 47 |
+
seen_hashes.add(fingerprint)
|
| 48 |
+
|
| 49 |
+
# Score: higher if contains topic keyword
|
| 50 |
+
score = self._score_sentence(s, topic_lower, word_count)
|
| 51 |
+
scored.append((score, s))
|
| 52 |
+
|
| 53 |
+
# Sort by score (highest first), return top 20
|
| 54 |
+
scored.sort(key=lambda x: x[0], reverse=True)
|
| 55 |
+
return [s for _, s in scored[:20]]
|
| 56 |
+
|
| 57 |
+
def _score_sentence(self, sentence, topic, word_count):
|
| 58 |
+
"""Score a sentence by information density and topic relevance."""
|
| 59 |
+
score = 0.0
|
| 60 |
+
s_lower = sentence.lower()
|
| 61 |
+
|
| 62 |
+
# Topic match
|
| 63 |
+
if topic and topic in s_lower:
|
| 64 |
+
score += 3.0
|
| 65 |
+
|
| 66 |
+
# Contains numbers/data (more factual)
|
| 67 |
+
if re.search(r"\d", sentence):
|
| 68 |
+
score += 1.5
|
| 69 |
+
|
| 70 |
+
# Contains proper nouns (capitalized words not at sentence start)
|
| 71 |
+
proper_nouns = re.findall(r"(?<!\. )\b[A-Z][a-z]{2,}\b", sentence[5:])
|
| 72 |
+
score += min(len(proper_nouns) * 0.5, 2.0)
|
| 73 |
+
|
| 74 |
+
# Penalize very short or very long
|
| 75 |
+
if word_count < 12:
|
| 76 |
+
score -= 0.5
|
| 77 |
+
if word_count > 80:
|
| 78 |
+
score -= 1.0
|
| 79 |
+
|
| 80 |
+
# Penalize question sentences (less factual)
|
| 81 |
+
if sentence.endswith("?"):
|
| 82 |
+
score -= 1.0
|
| 83 |
+
|
| 84 |
+
return score
|
| 85 |
+
|
| 86 |
+
def _is_boilerplate(self, sentence):
|
| 87 |
+
"""Detect navigation, cookie notices, ads, etc."""
|
| 88 |
+
s_lower = sentence.lower()
|
| 89 |
+
boilerplate_phrases = [
|
| 90 |
+
"cookie", "privacy policy", "terms of service", "click here",
|
| 91 |
+
"subscribe", "newsletter", "all rights reserved", "copyright Β©",
|
| 92 |
+
"sign up", "log in", "login", "register now", "follow us",
|
| 93 |
+
"share this", "read more", "learn more β", "advertisement",
|
| 94 |
+
"sponsored", "skip to content", "back to top",
|
| 95 |
+
]
|
| 96 |
+
if any(p in s_lower for p in boilerplate_phrases):
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
# All caps (likely a heading or ad)
|
| 100 |
+
if sentence.isupper() and len(sentence) > 10:
|
| 101 |
+
return True
|
| 102 |
+
|
| 103 |
+
# Very few unique words (repetitive/spammy)
|
| 104 |
+
words = sentence.lower().split()
|
| 105 |
+
if len(words) > 5 and len(set(words)) / len(words) < 0.4:
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
return False
|
knowledge_graph.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/knowledge_graph.py
|
| 2 |
+
import sqlite3
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import threading
|
| 5 |
+
import os
|
| 6 |
+
import hashlib
|
| 7 |
+
|
| 8 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class KnowledgeGraph:
|
| 12 |
+
def __init__(self, db_path=None):
|
| 13 |
+
self.db_path = db_path or "/data/invicta_data/knowledge.db"
|
| 14 |
+
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
|
| 15 |
+
self.lock = threading.Lock()
|
| 16 |
+
self._init_tables()
|
| 17 |
+
|
| 18 |
+
def _get_cursor(self):
|
| 19 |
+
conn = sqlite3.connect(self.db_path, check_same_thread=False)
|
| 20 |
+
conn.execute("PRAGMA foreign_keys = ON")
|
| 21 |
+
conn.row_factory = sqlite3.Row
|
| 22 |
+
return conn, conn.cursor()
|
| 23 |
+
|
| 24 |
+
def _init_tables(self):
|
| 25 |
+
with self.lock:
|
| 26 |
+
conn, cur = self._get_cursor()
|
| 27 |
+
try:
|
| 28 |
+
cur.execute("""
|
| 29 |
+
CREATE TABLE IF NOT EXISTS facts (
|
| 30 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 31 |
+
topic TEXT NOT NULL,
|
| 32 |
+
fact TEXT NOT NULL,
|
| 33 |
+
fact_hash TEXT,
|
| 34 |
+
source_url TEXT DEFAULT '',
|
| 35 |
+
confidence REAL DEFAULT 1.0,
|
| 36 |
+
times_seen INTEGER DEFAULT 1,
|
| 37 |
+
learned_at TEXT DEFAULT (datetime('now'))
|
| 38 |
+
);
|
| 39 |
+
""")
|
| 40 |
+
cur.execute("""
|
| 41 |
+
CREATE TABLE IF NOT EXISTS entities (
|
| 42 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 43 |
+
name TEXT UNIQUE NOT NULL,
|
| 44 |
+
type TEXT,
|
| 45 |
+
description TEXT,
|
| 46 |
+
learned_at TEXT DEFAULT (datetime('now'))
|
| 47 |
+
);
|
| 48 |
+
""")
|
| 49 |
+
cur.execute("""
|
| 50 |
+
CREATE TABLE IF NOT EXISTS relationships (
|
| 51 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 52 |
+
entity_a TEXT NOT NULL,
|
| 53 |
+
relation TEXT NOT NULL,
|
| 54 |
+
entity_b TEXT NOT NULL,
|
| 55 |
+
source_url TEXT DEFAULT '',
|
| 56 |
+
learned_at TEXT DEFAULT (datetime('now')),
|
| 57 |
+
UNIQUE(entity_a, relation, entity_b)
|
| 58 |
+
);
|
| 59 |
+
""")
|
| 60 |
+
cur.execute("""
|
| 61 |
+
CREATE TABLE IF NOT EXISTS topics_learned (
|
| 62 |
+
topic TEXT PRIMARY KEY,
|
| 63 |
+
times_queried INTEGER DEFAULT 1,
|
| 64 |
+
last_updated TEXT DEFAULT (datetime('now'))
|
| 65 |
+
);
|
| 66 |
+
""")
|
| 67 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_facts_topic ON facts(topic);")
|
| 68 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_facts_hash ON facts(fact_hash);")
|
| 69 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_facts_learned ON facts(learned_at);")
|
| 70 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_relationships_a ON relationships(entity_a);")
|
| 71 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_relationships_b ON relationships(entity_b);")
|
| 72 |
+
conn.commit()
|
| 73 |
+
except Exception as e:
|
| 74 |
+
conn.rollback()
|
| 75 |
+
if "already exists" not in str(e).lower() and "duplicate" not in str(e).lower():
|
| 76 |
+
raise
|
| 77 |
+
finally:
|
| 78 |
+
conn.close()
|
| 79 |
+
|
| 80 |
+
def _fact_hash(self, fact):
|
| 81 |
+
return hashlib.md5(fact.strip().lower()[:100].encode()).hexdigest()
|
| 82 |
+
|
| 83 |
+
# ββ Facts ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 84 |
+
def store_fact(self, topic, fact, source_url=""):
|
| 85 |
+
fh = self._fact_hash(fact)
|
| 86 |
+
with self.lock:
|
| 87 |
+
conn, cur = self._get_cursor()
|
| 88 |
+
cur.execute("SELECT id FROM facts WHERE fact_hash = ?", (fh,))
|
| 89 |
+
existing = cur.fetchone()
|
| 90 |
+
|
| 91 |
+
if existing:
|
| 92 |
+
cur.execute(
|
| 93 |
+
"UPDATE facts SET times_seen = times_seen + 1, confidence = min(confidence + 0.1, 2.0) WHERE id = ?",
|
| 94 |
+
(existing["id"],)
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
cur.execute(
|
| 98 |
+
"INSERT INTO facts (topic, fact, fact_hash, source_url, learned_at) VALUES (?, ?, ?, ?, ?)",
|
| 99 |
+
(topic.lower(), fact, fh, source_url, datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 100 |
+
)
|
| 101 |
+
conn.commit()
|
| 102 |
+
conn.close()
|
| 103 |
+
|
| 104 |
+
def recall_facts(self, topic, limit=10):
|
| 105 |
+
conn, cur = self._get_cursor()
|
| 106 |
+
cur.execute(
|
| 107 |
+
"""SELECT fact, source_url FROM facts
|
| 108 |
+
WHERE topic LIKE ?
|
| 109 |
+
ORDER BY confidence DESC, learned_at DESC
|
| 110 |
+
LIMIT ?""",
|
| 111 |
+
(f"%{topic.lower()}%", limit)
|
| 112 |
+
)
|
| 113 |
+
rows = cur.fetchall()
|
| 114 |
+
conn.close()
|
| 115 |
+
return [(r["fact"], r["source_url"]) for r in rows]
|
| 116 |
+
|
| 117 |
+
def knows_topic(self, topic):
|
| 118 |
+
conn, cur = self._get_cursor()
|
| 119 |
+
cur.execute(
|
| 120 |
+
"SELECT COUNT(*) as c FROM facts WHERE topic LIKE ?",
|
| 121 |
+
(f"%{topic.lower()}%",)
|
| 122 |
+
)
|
| 123 |
+
row = cur.fetchone()
|
| 124 |
+
conn.close()
|
| 125 |
+
return (row["c"] if row else 0) > 0
|
| 126 |
+
|
| 127 |
+
def get_fact_count(self):
|
| 128 |
+
conn, cur = self._get_cursor()
|
| 129 |
+
cur.execute("SELECT COUNT(*) as c FROM facts")
|
| 130 |
+
row = cur.fetchone()
|
| 131 |
+
conn.close()
|
| 132 |
+
return row["c"] if row else 0
|
| 133 |
+
|
| 134 |
+
def get_recent_facts(self, limit=25):
|
| 135 |
+
conn, cur = self._get_cursor()
|
| 136 |
+
cur.execute(
|
| 137 |
+
"SELECT id, topic, fact, source_url, confidence, learned_at FROM facts ORDER BY id DESC LIMIT ?",
|
| 138 |
+
(limit,)
|
| 139 |
+
)
|
| 140 |
+
rows = cur.fetchall()
|
| 141 |
+
conn.close()
|
| 142 |
+
return [dict(r) for r in rows]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# ββ Relationships βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 146 |
+
def store_relationship(self, entity_a, relation, entity_b, source=""):
|
| 147 |
+
with self.lock:
|
| 148 |
+
conn, cur = self._get_cursor()
|
| 149 |
+
cur.execute(
|
| 150 |
+
"""INSERT INTO relationships (entity_a, relation, entity_b, source_url, learned_at)
|
| 151 |
+
VALUES (?, ?, ?, ?, ?)
|
| 152 |
+
ON CONFLICT DO NOTHING""",
|
| 153 |
+
(entity_a.lower(), relation.lower(), entity_b.lower(), source, datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 154 |
+
)
|
| 155 |
+
conn.commit()
|
| 156 |
+
conn.close()
|
| 157 |
+
|
| 158 |
+
def recall_relationships(self, entity, limit=10):
|
| 159 |
+
conn, cur = self._get_cursor()
|
| 160 |
+
cur.execute(
|
| 161 |
+
"""SELECT entity_a, relation, entity_b FROM relationships
|
| 162 |
+
WHERE entity_a LIKE ? OR entity_b LIKE ?
|
| 163 |
+
LIMIT ?""",
|
| 164 |
+
(f"%{entity.lower()}%", f"%{entity.lower()}%", limit)
|
| 165 |
+
)
|
| 166 |
+
rows = cur.fetchall()
|
| 167 |
+
conn.close()
|
| 168 |
+
return [(r["entity_a"], r["relation"], r["entity_b"]) for r in rows]
|
| 169 |
+
|
| 170 |
+
# ββ Topics ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 171 |
+
def mark_topic_learned(self, topic):
|
| 172 |
+
with self.lock:
|
| 173 |
+
conn, cur = self._get_cursor()
|
| 174 |
+
cur.execute("""
|
| 175 |
+
INSERT INTO topics_learned (topic, times_queried, last_updated)
|
| 176 |
+
VALUES (?, 1, ?)
|
| 177 |
+
ON CONFLICT(topic) DO UPDATE SET
|
| 178 |
+
times_queried = topics_learned.times_queried + 1,
|
| 179 |
+
last_updated = excluded.last_updated
|
| 180 |
+
""", (topic.lower(), datetime.now().isoformat(sep=' ', timespec='seconds')))
|
| 181 |
+
conn.commit()
|
| 182 |
+
conn.close()
|
| 183 |
+
|
| 184 |
+
def get_top_topics(self, limit=10):
|
| 185 |
+
conn, cur = self._get_cursor()
|
| 186 |
+
cur.execute(
|
| 187 |
+
"SELECT topic, times_queried FROM topics_learned ORDER BY times_queried DESC LIMIT ?",
|
| 188 |
+
(limit,)
|
| 189 |
+
)
|
| 190 |
+
rows = cur.fetchall()
|
| 191 |
+
conn.close()
|
| 192 |
+
return [(r["topic"], r["times_queried"]) for r in rows]
|
| 193 |
+
|
| 194 |
+
# ββ Maintenance βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 195 |
+
def prune_old_facts(self, max_facts=5000):
|
| 196 |
+
conn, cur = self._get_cursor()
|
| 197 |
+
cur.execute("SELECT COUNT(*) as c FROM facts")
|
| 198 |
+
count = cur.fetchone()["c"]
|
| 199 |
+
conn.close()
|
| 200 |
+
if count > max_facts:
|
| 201 |
+
with self.lock:
|
| 202 |
+
conn, cur = self._get_cursor()
|
| 203 |
+
cur.execute("""
|
| 204 |
+
DELETE FROM facts WHERE id IN (
|
| 205 |
+
SELECT id FROM facts
|
| 206 |
+
ORDER BY confidence ASC, learned_at ASC
|
| 207 |
+
LIMIT ?
|
| 208 |
+
)
|
| 209 |
+
""", (count - max_facts,))
|
| 210 |
+
conn.commit()
|
| 211 |
+
conn.close()
|
| 212 |
+
print(f"π§Ή Pruned {count - max_facts} old facts from knowledge graph")
|
learning.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/learning.py
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import threading
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from memory import ConversationMemory
|
| 7 |
+
import sqlite3
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class LearningEngine:
|
| 11 |
+
"""
|
| 12 |
+
Self-learning engine that continuously observes user conversations,
|
| 13 |
+
extracts communication patterns, interests, and preferences,
|
| 14 |
+
and consolidates them into an adaptive user model.
|
| 15 |
+
|
| 16 |
+
The more a user interacts, the better Invicta understands them.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, memory: ConversationMemory):
|
| 20 |
+
self.memory = memory
|
| 21 |
+
self._lock = threading.Lock()
|
| 22 |
+
|
| 23 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
# REAL-TIME MESSAGE ANALYSIS
|
| 25 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
|
| 27 |
+
def analyze_message(self, user_id, message):
|
| 28 |
+
if not message or not user_id:
|
| 29 |
+
return
|
| 30 |
+
try:
|
| 31 |
+
self.memory.increment_interaction_count(user_id)
|
| 32 |
+
self._detect_interests(user_id, message)
|
| 33 |
+
self._detect_communication_style(user_id, message)
|
| 34 |
+
self._detect_emotional_state(user_id, message)
|
| 35 |
+
self._detect_preferences(user_id, message)
|
| 36 |
+
self._detect_language(user_id, message) # β ADD THIS
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"β οΈ Learning analysis error: {e}")
|
| 39 |
+
|
| 40 |
+
def _detect_interests(self, user_id, message):
|
| 41 |
+
"""Detect topics the user is interested in based on what they ask about."""
|
| 42 |
+
interest_patterns = [
|
| 43 |
+
# Technology
|
| 44 |
+
(r'\b(?:python|javascript|typescript|rust|golang|programming|coding|developer|software|algorithm|api|database|web\s*dev|machine\s*learning|deep\s*learning|ai|artificial\s*intelligence|neural\s*network|data\s*science|cybersecurity|blockchain|crypto|cloud\s*computing|devops)\b', 'technology'),
|
| 45 |
+
# Science
|
| 46 |
+
(r'\b(?:physics|chemistry|biology|quantum|astronomy|space|nasa|evolution|genetics|neuroscience|psychology|math|calculus|statistics|research)\b', 'science'),
|
| 47 |
+
# Business & Finance
|
| 48 |
+
(r'\b(?:startup|business|entrepreneur|invest|stock|market|finance|crypto|trading|marketing|sales|revenue|profit|startup|company|venture)\b', 'business'),
|
| 49 |
+
# Creative
|
| 50 |
+
(r'\b(?:design|art|music|writing|creative|paint|draw|compose|fiction|novel|poetry|photography|filmmaking|video|animation)\b', 'creative'),
|
| 51 |
+
# Health & Fitness
|
| 52 |
+
(r'\b(?:fitness|workout|exercise|diet|nutrition|health|medical|yoga|meditation|mental\s*health|therapy|wellness|gym|running|weight)\b', 'health'),
|
| 53 |
+
# Gaming
|
| 54 |
+
(r'\b(?:game|gaming|gamer|xbox|playstation|nintendo|steam|esports|rpg|fps|mmorpg|minecraft|fortnite)\b', 'gaming'),
|
| 55 |
+
# Travel
|
| 56 |
+
(r'\b(?:travel|trip|vacation|flight|hotel|country|city|backpack|adventure|explore|destination|tourist|visa)\b', 'travel'),
|
| 57 |
+
# Food & Cooking
|
| 58 |
+
(r'\b(?:recipe|cooking|food|cuisine|bake|chef|restaurant|meal|ingredient|kitchen|dish)\b', 'food'),
|
| 59 |
+
# Education
|
| 60 |
+
(r'\b(?:study|university|college|school|learn|course|degree|exam|academic|education|teach|student|homework|tutorial)\b', 'education'),
|
| 61 |
+
# Philosophy & Religion
|
| 62 |
+
(r'\b(?:philosophy|existential|meaning\s*of\s*life|moral|ethics|religion|spiritual|meditation|mindfulness|consciousness)\b', 'philosophy'),
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
msg_lower = message.lower()
|
| 66 |
+
for pattern, category in interest_patterns:
|
| 67 |
+
matches = re.findall(pattern, msg_lower)
|
| 68 |
+
if matches:
|
| 69 |
+
# Store each matched keyword as an interest observation
|
| 70 |
+
for match in matches:
|
| 71 |
+
keyword = match.strip().lower()
|
| 72 |
+
self.memory.store_learning(
|
| 73 |
+
user_id=user_id,
|
| 74 |
+
category="interest",
|
| 75 |
+
key=keyword,
|
| 76 |
+
value=f"Interested in {category}: {keyword}",
|
| 77 |
+
confidence=0.4
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def _detect_language(self, user_id, message):
|
| 81 |
+
"""Detect if user is writing in a non-English language and store preference."""
|
| 82 |
+
# Simple detection for common scripts
|
| 83 |
+
import re
|
| 84 |
+
if re.search(r'[\u0900-\u097F]', message): # Devanagari (Hindi)
|
| 85 |
+
self.memory.store_learning(user_id, "preference", "language", "hindi", 0.6)
|
| 86 |
+
elif re.search(r'[\u0600-\u06FF]', message): # Arabic
|
| 87 |
+
self.memory.store_learning(user_id, "preference", "language", "arabic", 0.6)
|
| 88 |
+
elif re.search(r'[\u3040-\u30FF]', message): # Japanese
|
| 89 |
+
self.memory.store_learning(user_id, "preference", "language", "japanese", 0.6)
|
| 90 |
+
elif re.search(r'[\u4E00-\u9FFF]', message): # Chinese
|
| 91 |
+
self.memory.store_learning(user_id, "preference", "language", "chinese", 0.6)
|
| 92 |
+
elif re.search(r'[\uAC00-\uD7AF]', message): # Korean
|
| 93 |
+
self.memory.store_learning(user_id, "preference", "language", "korean", 0.6)
|
| 94 |
+
elif re.search(r'[ÑéΓΓ³ΓΊΓ±ΒΏΒ‘]', message, re.IGNORECASE): # Spanish
|
| 95 |
+
self.memory.store_learning(user_id, "preference", "language", "spanish", 0.3)
|
| 96 |
+
|
| 97 |
+
def _detect_communication_style(self, user_id, message):
|
| 98 |
+
"""Detect how the user communicates β formality, length, tone."""
|
| 99 |
+
# ββ FIX: msg_lower was missing here, causing the crash ββ
|
| 100 |
+
msg_lower = message.lower()
|
| 101 |
+
words = message.split()
|
| 102 |
+
word_count = len(words)
|
| 103 |
+
|
| 104 |
+
# ββ Formality detection ββ
|
| 105 |
+
formal_indicators = sum(1 for w in words if w.lower() in {
|
| 106 |
+
"therefore", "however", "furthermore", "consequently", "nevertheless",
|
| 107 |
+
"accordingly", "moreover", "henceforth", "would", "shall", "may",
|
| 108 |
+
"perhaps", "kindly", "regards", "sincerely", "please", "respectfully",
|
| 109 |
+
})
|
| 110 |
+
casual_indicators = sum(1 for w in words if w.lower() in {
|
| 111 |
+
"lol", "haha", "yeah", "nah", "yep", "nope", "gonna", "wanna",
|
| 112 |
+
"gotta", "dunno", "kinda", "sorta", "btw", "omg", "wtf", "lmao",
|
| 113 |
+
"bruh", "dude", "hey", "yo", "sup", "ngl", "fr", "tbh", "imo",
|
| 114 |
+
})
|
| 115 |
+
contractions = sum(1 for w in words if re.match(r"\w+'\w+", w))
|
| 116 |
+
|
| 117 |
+
if formal_indicators > 2 or (formal_indicators > 0 and casual_indicators == 0 and contractions == 0):
|
| 118 |
+
self.memory.store_learning(user_id, "style", "formality_signal", "formal", 0.3)
|
| 119 |
+
elif casual_indicators > 0 or contractions > 2:
|
| 120 |
+
self.memory.store_learning(user_id, "style", "formality_signal", "casual", 0.3)
|
| 121 |
+
|
| 122 |
+
# ββ Response length preference ββ
|
| 123 |
+
if word_count <= 5:
|
| 124 |
+
self.memory.store_learning(user_id, "style", "length_signal", "short", 0.25)
|
| 125 |
+
elif word_count <= 20:
|
| 126 |
+
self.memory.store_learning(user_id, "style", "length_signal", "medium", 0.2)
|
| 127 |
+
else:
|
| 128 |
+
self.memory.store_learning(user_id, "style", "length_signal", "detailed", 0.25)
|
| 129 |
+
|
| 130 |
+
# ββ Tone detection ββ
|
| 131 |
+
# Question-heavy = curious
|
| 132 |
+
questions = message.count('?')
|
| 133 |
+
exclamations = message.count('!')
|
| 134 |
+
emojis = len(re.findall(r'[π₯π‘β€οΈππππ€ππβ¨π―πͺππ§ βππ«]', message))
|
| 135 |
+
|
| 136 |
+
if questions >= 2:
|
| 137 |
+
self.memory.store_learning(user_id, "style", "tone_signal", "curious", 0.3)
|
| 138 |
+
if exclamations >= 2 or emojis >= 2:
|
| 139 |
+
self.memory.store_learning(user_id, "style", "tone_signal", "enthusiastic", 0.3)
|
| 140 |
+
if any(phrase in msg_lower for phrase in ['help me', 'can you', 'please', 'how do i', 'how to']):
|
| 141 |
+
self.memory.store_learning(user_id, "style", "tone_signal", "practical", 0.25)
|
| 142 |
+
|
| 143 |
+
# Detect humor/wit
|
| 144 |
+
humor_words = ['joke', 'funny', 'lol', 'haha', 'lmao', 'pun', 'humor']
|
| 145 |
+
if any(w in msg_lower for w in humor_words):
|
| 146 |
+
self.memory.store_learning(user_id, "style", "tone_signal", "witty", 0.35)
|
| 147 |
+
|
| 148 |
+
def _detect_emotional_state(self, user_id, message):
|
| 149 |
+
"""Detect the user's emotional state from their messages."""
|
| 150 |
+
msg_lower = message.lower()
|
| 151 |
+
|
| 152 |
+
# Stress/frustration
|
| 153 |
+
stress_words = ['stressed', 'frustrated', 'overwhelmed', 'anxious', 'worried',
|
| 154 |
+
'tired', 'exhausted', 'burnt out', 'burnout', 'struggling',
|
| 155 |
+
'can\'t handle', 'too much', 'losing hope']
|
| 156 |
+
if any(w in msg_lower for w in stress_words):
|
| 157 |
+
self.memory.store_learning(user_id, "emotion", "recent_state", "stressed", 0.5)
|
| 158 |
+
self.memory.store_learning(user_id, "emotion", "stress_prone", "yes", 0.2)
|
| 159 |
+
|
| 160 |
+
# Happiness/excitement
|
| 161 |
+
happy_words = ['excited', 'happy', 'great', 'awesome', 'amazing', 'wonderful',
|
| 162 |
+
'fantastic', 'love it', 'so good', 'thrilled', 'pumped', 'stoked']
|
| 163 |
+
if any(w in msg_lower for w in happy_words):
|
| 164 |
+
self.memory.store_learning(user_id, "emotion", "recent_state", "happy", 0.5)
|
| 165 |
+
|
| 166 |
+
# Sadness
|
| 167 |
+
sad_words = ['sad', 'depressed', 'lonely', 'miss', 'lost', 'heartbroken',
|
| 168 |
+
'crying', 'hurt', 'pain', 'grief', 'mourn']
|
| 169 |
+
if any(w in msg_lower for w in sad_words):
|
| 170 |
+
self.memory.store_learning(user_id, "emotion", "recent_state", "sad", 0.5)
|
| 171 |
+
|
| 172 |
+
# Curiosity
|
| 173 |
+
curious_words = ['wonder', 'curious', 'interesting', 'fascinating', 'tell me more',
|
| 174 |
+
'how come', 'why is', 'what if', 'explain']
|
| 175 |
+
if any(w in msg_lower for w in curious_words):
|
| 176 |
+
self.memory.store_learning(user_id, "emotion", "recent_state", "curious", 0.4)
|
| 177 |
+
|
| 178 |
+
def _detect_preferences(self, user_id, message):
|
| 179 |
+
"""Detect explicit and implicit preferences."""
|
| 180 |
+
msg_lower = message.lower()
|
| 181 |
+
|
| 182 |
+
# Explicit preferences
|
| 183 |
+
pref_patterns = [
|
| 184 |
+
(r"i (?:prefer|like|want|need) (?:my (?:answers?|responses?) )?(?:to be )?(short|brief|concise)", "short"),
|
| 185 |
+
(r"i (?:prefer|like|want|need) (?:my (?:answers?|responses?) )?(?:to be )?(long|detailed|thorough|in.depth|comprehensive)", "detailed"),
|
| 186 |
+
(r"i (?:prefer|like|want|need) (?:my (?:answers?|responses?) )?(?:to be )?(simple|easy|basic|beginner)", "simple"),
|
| 187 |
+
(r"i (?:prefer|like|want|need) (?:my (?:answers?|responses?) )?(?:to be )?(technical|advanced|complex)", "technical"),
|
| 188 |
+
(r"(?:don't|do not) (?:use|give me) (?:code|programming)", "no_code"),
|
| 189 |
+
(r"(?:give|show) me (?:the )?code", "wants_code"),
|
| 190 |
+
(r"(?:give|show) me (?:an )?example", "wants_examples"),
|
| 191 |
+
(r"(?:step.by.step|step by step)", "step_by_step"),
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
for pattern, pref in pref_patterns:
|
| 195 |
+
if re.search(pattern, msg_lower):
|
| 196 |
+
self.memory.store_learning(user_id, "preference", pref, "true", 0.6)
|
| 197 |
+
|
| 198 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
+
# CONSOLIDATION (runs periodically)
|
| 200 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 201 |
+
|
| 202 |
+
def run_daily_consolidation(self):
|
| 203 |
+
"""
|
| 204 |
+
Consolidate raw learning observations into user insights.
|
| 205 |
+
Called periodically by the background thread.
|
| 206 |
+
"""
|
| 207 |
+
try:
|
| 208 |
+
# Get all users who have learning data
|
| 209 |
+
all_users = self._get_active_users()
|
| 210 |
+
for user_id in all_users:
|
| 211 |
+
try:
|
| 212 |
+
self._consolidate_user(user_id)
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f"β οΈ Consolidation error for user {user_id}: {e}")
|
| 215 |
+
except Exception as e:
|
| 216 |
+
print(f"β οΈ Daily consolidation error: {e}")
|
| 217 |
+
|
| 218 |
+
def _get_active_users(self):
|
| 219 |
+
"""Get list of user IDs that have learning data."""
|
| 220 |
+
db_path = self.memory.db_path
|
| 221 |
+
conn = sqlite3.connect(db_path)
|
| 222 |
+
conn.row_factory = sqlite3.Row
|
| 223 |
+
cur = conn.cursor()
|
| 224 |
+
cur.execute("SELECT DISTINCT user_id FROM user_learning")
|
| 225 |
+
rows = cur.fetchall()
|
| 226 |
+
conn.close()
|
| 227 |
+
return [row["user_id"] for row in rows]
|
| 228 |
+
|
| 229 |
+
def _consolidate_user(self, user_id):
|
| 230 |
+
"""Consolidate all learning data for one user into insights."""
|
| 231 |
+
insights = self.memory.get_user_insights(user_id) or {}
|
| 232 |
+
|
| 233 |
+
# ββ Formality ββ
|
| 234 |
+
style_data = self.memory.get_learning_by_category(user_id, "style")
|
| 235 |
+
formality_signals = []
|
| 236 |
+
for key, val in style_data.items():
|
| 237 |
+
if key == "formality_signal":
|
| 238 |
+
formality_signals.append(val)
|
| 239 |
+
|
| 240 |
+
if formality_signals:
|
| 241 |
+
# Most frequent signal wins
|
| 242 |
+
from collections import Counter
|
| 243 |
+
most_common = Counter(formality_signals).most_common(1)[0][0]
|
| 244 |
+
insights["preferred_formality"] = most_common
|
| 245 |
+
|
| 246 |
+
# ββ Response length ββ
|
| 247 |
+
length_signals = [v for k, v in style_data.items() if k == "length_signal"]
|
| 248 |
+
if length_signals:
|
| 249 |
+
from collections import Counter
|
| 250 |
+
most_common = Counter(length_signals).most_common(1)[0][0]
|
| 251 |
+
insights["preferred_response_length"] = most_common
|
| 252 |
+
|
| 253 |
+
# ββ Tone ββ
|
| 254 |
+
tone_signals = [v for k, v in style_data.items() if k == "tone_signal"]
|
| 255 |
+
if tone_signals:
|
| 256 |
+
from collections import Counter
|
| 257 |
+
most_common = Counter(tone_signals).most_common(1)[0][0]
|
| 258 |
+
insights["preferred_tone"] = most_common
|
| 259 |
+
|
| 260 |
+
# ββ Topics of interest ββ
|
| 261 |
+
top_topics = self.memory.get_top_learning_topics(user_id, limit=15)
|
| 262 |
+
interest_list = [t["key"] for t in top_topics if t.get("times_observed", 0) >= 2]
|
| 263 |
+
if interest_list:
|
| 264 |
+
insights["topics_of_interest"] = interest_list[:10]
|
| 265 |
+
|
| 266 |
+
# ββ Communication patterns ββ
|
| 267 |
+
patterns = {}
|
| 268 |
+
pref_data = self.memory.get_learning_by_category(user_id, "preference")
|
| 269 |
+
for k, v in pref_data.items():
|
| 270 |
+
patterns[k] = v
|
| 271 |
+
if patterns:
|
| 272 |
+
insights["communication_patterns"] = patterns
|
| 273 |
+
|
| 274 |
+
# Save consolidated insights
|
| 275 |
+
self.memory.update_user_insights(user_id, insights)
|
| 276 |
+
|
| 277 |
+
# Prune old learning data
|
| 278 |
+
self.memory.prune_old_learning(user_id, max_entries=500)
|
| 279 |
+
|
| 280 |
+
print(f"π§ Consolidated learning for user {user_id}")
|
| 281 |
+
|
| 282 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 283 |
+
# USER MODEL (used by Brain to adapt responses)
|
| 284 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 285 |
+
|
| 286 |
+
def get_user_model(self, user_id):
|
| 287 |
+
"""
|
| 288 |
+
Build the current user model from consolidated insights
|
| 289 |
+
+ real-time learning data. Used by Brain._build_adaptation_prompt().
|
| 290 |
+
"""
|
| 291 |
+
if not user_id:
|
| 292 |
+
return None
|
| 293 |
+
|
| 294 |
+
insights = self.memory.get_user_insights(user_id)
|
| 295 |
+
model = {}
|
| 296 |
+
|
| 297 |
+
# Formality
|
| 298 |
+
model["formality"] = insights.get("preferred_formality", "casual") if insights else "casual"
|
| 299 |
+
|
| 300 |
+
# Response length
|
| 301 |
+
model["response_length"] = insights.get("preferred_response_length", "medium") if insights else "medium"
|
| 302 |
+
|
| 303 |
+
# Tone
|
| 304 |
+
model["tone"] = insights.get("preferred_tone", "friendly") if insights else "friendly"
|
| 305 |
+
|
| 306 |
+
# Interests
|
| 307 |
+
model["interests"] = insights.get("topics_of_interest", []) if insights else []
|
| 308 |
+
|
| 309 |
+
# Preferences
|
| 310 |
+
if insights and insights.get("communication_patterns"):
|
| 311 |
+
model["preferences"] = insights["communication_patterns"]
|
| 312 |
+
else:
|
| 313 |
+
model["preferences"] = {}
|
| 314 |
+
|
| 315 |
+
# Emotional state (from real-time learning)
|
| 316 |
+
emotion_data = self.memory.get_learning_by_category(user_id, "emotion")
|
| 317 |
+
recent_state = emotion_data.get("recent_state", "")
|
| 318 |
+
if recent_state:
|
| 319 |
+
model["recent_emotional_state"] = recent_state
|
| 320 |
+
|
| 321 |
+
# Interaction count
|
| 322 |
+
if insights:
|
| 323 |
+
model["interaction_count"] = insights.get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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/memory.py
|
| 2 |
+
import sqlite3
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import threading
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import secrets
|
| 8 |
+
import hashlib
|
| 9 |
+
import time
|
| 10 |
+
import re
|
| 11 |
+
from werkzeug.security import generate_password_hash, check_password_hash
|
| 12 |
+
|
| 13 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ConversationMemory:
|
| 17 |
+
def __init__(self, db_path=None):
|
| 18 |
+
self.db_path = db_path or "/data/invicta_data/memory.db"
|
| 19 |
+
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
|
| 20 |
+
self.lock = threading.Lock()
|
| 21 |
+
self._init_tables()
|
| 22 |
+
|
| 23 |
+
def _get_connection(self):
|
| 24 |
+
"""Create a new SQLite connection with WAL mode and busy timeout."""
|
| 25 |
+
conn = sqlite3.connect(
|
| 26 |
+
self.db_path,
|
| 27 |
+
check_same_thread=False,
|
| 28 |
+
timeout=30.0,
|
| 29 |
+
isolation_level=None
|
| 30 |
+
)
|
| 31 |
+
conn.execute("PRAGMA foreign_keys = ON")
|
| 32 |
+
conn.execute("PRAGMA journal_mode = WAL")
|
| 33 |
+
conn.execute("PRAGMA synchronous = NORMAL")
|
| 34 |
+
conn.execute("PRAGMA temp_store = MEMORY")
|
| 35 |
+
conn.execute("PRAGMA mmap_size = 30000000000")
|
| 36 |
+
conn.execute("PRAGMA busy_timeout = 30000")
|
| 37 |
+
conn.row_factory = sqlite3.Row
|
| 38 |
+
return conn
|
| 39 |
+
|
| 40 |
+
def _get_cursor(self):
|
| 41 |
+
"""Legacy compatibility wrapper."""
|
| 42 |
+
conn = self._get_connection()
|
| 43 |
+
return conn, conn.cursor()
|
| 44 |
+
|
| 45 |
+
def _execute_with_retry(self, sql, params=(), max_retries=5, sleep_base=0.05):
|
| 46 |
+
"""Execute SQL with automatic retry on database lock."""
|
| 47 |
+
for attempt in range(max_retries):
|
| 48 |
+
conn = None
|
| 49 |
+
try:
|
| 50 |
+
conn = self._get_connection()
|
| 51 |
+
cur = conn.cursor()
|
| 52 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 53 |
+
cur.execute(sql, params)
|
| 54 |
+
conn.commit()
|
| 55 |
+
return cur
|
| 56 |
+
except sqlite3.OperationalError as e:
|
| 57 |
+
if conn:
|
| 58 |
+
try:
|
| 59 |
+
conn.rollback()
|
| 60 |
+
except Exception:
|
| 61 |
+
pass
|
| 62 |
+
if "database is locked" in str(e).lower() and attempt < max_retries - 1:
|
| 63 |
+
time.sleep(sleep_base * (attempt + 1))
|
| 64 |
+
continue
|
| 65 |
+
raise
|
| 66 |
+
finally:
|
| 67 |
+
if conn:
|
| 68 |
+
try:
|
| 69 |
+
conn.close()
|
| 70 |
+
except Exception:
|
| 71 |
+
pass
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
def _init_tables(self):
|
| 75 |
+
with self.lock:
|
| 76 |
+
conn = self._get_connection()
|
| 77 |
+
try:
|
| 78 |
+
cur = conn.cursor()
|
| 79 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 80 |
+
cur.execute("""
|
| 81 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 82 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 83 |
+
username TEXT UNIQUE NOT NULL,
|
| 84 |
+
password_hash TEXT NOT NULL,
|
| 85 |
+
google_id TEXT,
|
| 86 |
+
email TEXT,
|
| 87 |
+
created_at TEXT DEFAULT (datetime('now'))
|
| 88 |
+
);
|
| 89 |
+
""")
|
| 90 |
+
cur.execute("""
|
| 91 |
+
CREATE TABLE IF NOT EXISTS auth_tokens (
|
| 92 |
+
token TEXT PRIMARY KEY,
|
| 93 |
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 94 |
+
created_at TEXT DEFAULT (datetime('now')),
|
| 95 |
+
last_used TEXT DEFAULT (datetime('now'))
|
| 96 |
+
);
|
| 97 |
+
""")
|
| 98 |
+
cur.execute("""
|
| 99 |
+
CREATE TABLE IF NOT EXISTS chat_sessions (
|
| 100 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 101 |
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 102 |
+
title TEXT,
|
| 103 |
+
created_at TEXT DEFAULT (datetime('now'))
|
| 104 |
+
);
|
| 105 |
+
""")
|
| 106 |
+
cur.execute("""
|
| 107 |
+
CREATE TABLE IF NOT EXISTS conversations (
|
| 108 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 109 |
+
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
|
| 110 |
+
session_id INTEGER REFERENCES chat_sessions(id) ON DELETE CASCADE,
|
| 111 |
+
role TEXT NOT NULL,
|
| 112 |
+
content TEXT NOT NULL,
|
| 113 |
+
timestamp TEXT DEFAULT (datetime('now'))
|
| 114 |
+
);
|
| 115 |
+
""")
|
| 116 |
+
cur.execute("""
|
| 117 |
+
CREATE TABLE IF NOT EXISTS user_profile (
|
| 118 |
+
user_id INTEGER NOT NULL DEFAULT 0 REFERENCES users(id) ON DELETE CASCADE,
|
| 119 |
+
key TEXT NOT NULL,
|
| 120 |
+
value TEXT,
|
| 121 |
+
category TEXT DEFAULT 'general',
|
| 122 |
+
updated_at TEXT DEFAULT (datetime('now')),
|
| 123 |
+
PRIMARY KEY (user_id, key)
|
| 124 |
+
);
|
| 125 |
+
""")
|
| 126 |
+
cur.execute("""
|
| 127 |
+
CREATE TABLE IF NOT EXISTS user_learning (
|
| 128 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 129 |
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 130 |
+
category TEXT NOT NULL,
|
| 131 |
+
key TEXT NOT NULL,
|
| 132 |
+
value TEXT NOT NULL,
|
| 133 |
+
confidence REAL DEFAULT 0.5,
|
| 134 |
+
times_observed INTEGER DEFAULT 1,
|
| 135 |
+
first_seen TEXT DEFAULT (datetime('now')),
|
| 136 |
+
updated_at TEXT DEFAULT (datetime('now')),
|
| 137 |
+
UNIQUE(user_id, category, key)
|
| 138 |
+
);
|
| 139 |
+
""")
|
| 140 |
+
cur.execute("""
|
| 141 |
+
CREATE TABLE IF NOT EXISTS user_insights (
|
| 142 |
+
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
| 143 |
+
preferred_formality TEXT DEFAULT 'casual',
|
| 144 |
+
preferred_response_length TEXT DEFAULT 'medium',
|
| 145 |
+
preferred_tone TEXT DEFAULT 'friendly',
|
| 146 |
+
topics_of_interest TEXT DEFAULT '[]',
|
| 147 |
+
communication_patterns TEXT DEFAULT '{}',
|
| 148 |
+
total_interactions INTEGER DEFAULT 0,
|
| 149 |
+
last_analyzed TEXT DEFAULT (datetime('now')),
|
| 150 |
+
updated_at TEXT DEFAULT (datetime('now'))
|
| 151 |
+
);
|
| 152 |
+
""")
|
| 153 |
+
cur.execute("""
|
| 154 |
+
CREATE TABLE IF NOT EXISTS api_keys (
|
| 155 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 156 |
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 157 |
+
key_hash TEXT NOT NULL,
|
| 158 |
+
name TEXT DEFAULT 'API Key',
|
| 159 |
+
prefix TEXT DEFAULT '',
|
| 160 |
+
created_at TEXT DEFAULT (datetime('now')),
|
| 161 |
+
last_used TEXT,
|
| 162 |
+
revoked INTEGER DEFAULT 0,
|
| 163 |
+
rate_limit INTEGER DEFAULT 60
|
| 164 |
+
);
|
| 165 |
+
""")
|
| 166 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_conversations_user ON conversations(user_id);")
|
| 167 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_conversations_session ON conversations(session_id);")
|
| 168 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_conversations_user_session ON conversations(user_id, session_id);")
|
| 169 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_conversations_timestamp ON conversations(timestamp);")
|
| 170 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_learning_user ON user_learning(user_id);")
|
| 171 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_learning_category ON user_learning(user_id, category);")
|
| 172 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_learning_unique ON user_learning(user_id, category, key);")
|
| 173 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_auth_tokens_user ON auth_tokens(user_id);")
|
| 174 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_api_keys_user ON api_keys(user_id);")
|
| 175 |
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);")
|
| 176 |
+
conn.commit()
|
| 177 |
+
except Exception as e:
|
| 178 |
+
conn.rollback()
|
| 179 |
+
if "already exists" not in str(e).lower() and "duplicate" not in str(e).lower():
|
| 180 |
+
raise
|
| 181 |
+
finally:
|
| 182 |
+
conn.close()
|
| 183 |
+
|
| 184 |
+
# ββ Auth Tokens ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 185 |
+
def create_token(self, user_id):
|
| 186 |
+
token = secrets.token_urlsafe(32)
|
| 187 |
+
with self.lock:
|
| 188 |
+
conn = self._get_connection()
|
| 189 |
+
try:
|
| 190 |
+
cur = conn.cursor()
|
| 191 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 192 |
+
cur.execute(
|
| 193 |
+
"INSERT INTO auth_tokens (token, user_id, created_at, last_used) VALUES (?, ?, ?, ?)",
|
| 194 |
+
(token, user_id, datetime.now().isoformat(sep=' ', timespec='seconds'), datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 195 |
+
)
|
| 196 |
+
conn.commit()
|
| 197 |
+
finally:
|
| 198 |
+
conn.close()
|
| 199 |
+
return token
|
| 200 |
+
|
| 201 |
+
def validate_token(self, token):
|
| 202 |
+
if not token or len(token) < 10:
|
| 203 |
+
return None
|
| 204 |
+
conn = self._get_connection()
|
| 205 |
+
try:
|
| 206 |
+
cur = conn.cursor()
|
| 207 |
+
cur.execute("SELECT user_id FROM auth_tokens WHERE token = ?", (token,))
|
| 208 |
+
row = cur.fetchone()
|
| 209 |
+
return row["user_id"] if row else None
|
| 210 |
+
finally:
|
| 211 |
+
conn.close()
|
| 212 |
+
|
| 213 |
+
def touch_token(self, token):
|
| 214 |
+
"""Update token last_used with retry logic for concurrent access."""
|
| 215 |
+
now = datetime.now().isoformat(sep=' ', timespec='seconds')
|
| 216 |
+
for attempt in range(5):
|
| 217 |
+
conn = None
|
| 218 |
+
try:
|
| 219 |
+
conn = self._get_connection()
|
| 220 |
+
cur = conn.cursor()
|
| 221 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 222 |
+
cur.execute(
|
| 223 |
+
"UPDATE auth_tokens SET last_used = ? WHERE token = ?",
|
| 224 |
+
(now, token)
|
| 225 |
+
)
|
| 226 |
+
conn.commit()
|
| 227 |
+
return
|
| 228 |
+
except sqlite3.OperationalError as e:
|
| 229 |
+
if conn:
|
| 230 |
+
try:
|
| 231 |
+
conn.rollback()
|
| 232 |
+
except Exception:
|
| 233 |
+
pass
|
| 234 |
+
if "database is locked" in str(e).lower() and attempt < 4:
|
| 235 |
+
time.sleep(0.05 * (attempt + 1))
|
| 236 |
+
continue
|
| 237 |
+
raise
|
| 238 |
+
finally:
|
| 239 |
+
if conn:
|
| 240 |
+
try:
|
| 241 |
+
conn.close()
|
| 242 |
+
except Exception:
|
| 243 |
+
pass
|
| 244 |
+
|
| 245 |
+
def delete_token(self, token):
|
| 246 |
+
with self.lock:
|
| 247 |
+
conn = self._get_connection()
|
| 248 |
+
try:
|
| 249 |
+
cur = conn.cursor()
|
| 250 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 251 |
+
cur.execute("DELETE FROM auth_tokens WHERE token = ?", (token,))
|
| 252 |
+
conn.commit()
|
| 253 |
+
finally:
|
| 254 |
+
conn.close()
|
| 255 |
+
|
| 256 |
+
def revoke_user_tokens(self, user_id):
|
| 257 |
+
with self.lock:
|
| 258 |
+
conn = self._get_connection()
|
| 259 |
+
try:
|
| 260 |
+
cur = conn.cursor()
|
| 261 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 262 |
+
cur.execute("DELETE FROM auth_tokens WHERE user_id = ?", (user_id,))
|
| 263 |
+
conn.commit()
|
| 264 |
+
finally:
|
| 265 |
+
conn.close()
|
| 266 |
+
|
| 267 |
+
def cleanup_old_tokens(self, max_age_days=30):
|
| 268 |
+
with self.lock:
|
| 269 |
+
conn = self._get_connection()
|
| 270 |
+
try:
|
| 271 |
+
cur = conn.cursor()
|
| 272 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 273 |
+
cur.execute(
|
| 274 |
+
"DELETE FROM auth_tokens WHERE last_used < datetime('now', '-{} days')".format(max_age_days)
|
| 275 |
+
)
|
| 276 |
+
conn.commit()
|
| 277 |
+
finally:
|
| 278 |
+
conn.close()
|
| 279 |
+
|
| 280 |
+
# ββ User Auth βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 281 |
+
def create_user(self, username, password):
|
| 282 |
+
"""Create a user with validation. Returns True on success, False on failure."""
|
| 283 |
+
# Defense-in-depth validations (also enforced in app.py)
|
| 284 |
+
if not username or not password:
|
| 285 |
+
return False
|
| 286 |
+
if len(username) < 3 or len(username) > 30:
|
| 287 |
+
return False
|
| 288 |
+
if not re.match(r'^[a-zA-Z0-9_\-]+$', username):
|
| 289 |
+
return False
|
| 290 |
+
if username.lower().startswith("__guest_"):
|
| 291 |
+
return False
|
| 292 |
+
if len(password) < 8:
|
| 293 |
+
return False
|
| 294 |
+
if not re.search(r'[A-Z]', password) or not re.search(r'[a-z]', password) or not re.search(r'[0-9]', password):
|
| 295 |
+
return False
|
| 296 |
+
|
| 297 |
+
with self.lock:
|
| 298 |
+
conn = self._get_connection()
|
| 299 |
+
try:
|
| 300 |
+
cur = conn.cursor()
|
| 301 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 302 |
+
pw_hash = generate_password_hash(password)
|
| 303 |
+
# Store username lowercase for case-normalization
|
| 304 |
+
cur.execute(
|
| 305 |
+
"INSERT INTO users (username, password_hash) VALUES (?, ?)",
|
| 306 |
+
(username.strip().lower(), pw_hash)
|
| 307 |
+
)
|
| 308 |
+
conn.commit()
|
| 309 |
+
return True
|
| 310 |
+
except sqlite3.IntegrityError:
|
| 311 |
+
conn.rollback()
|
| 312 |
+
return False
|
| 313 |
+
finally:
|
| 314 |
+
conn.close()
|
| 315 |
+
|
| 316 |
+
def verify_user(self, username, password):
|
| 317 |
+
if not username or not password:
|
| 318 |
+
return None
|
| 319 |
+
conn = self._get_connection()
|
| 320 |
+
try:
|
| 321 |
+
cur = conn.cursor()
|
| 322 |
+
# Case-normalized lookup
|
| 323 |
+
cur.execute(
|
| 324 |
+
"SELECT id, password_hash FROM users WHERE username = ?", (username.strip().lower(),)
|
| 325 |
+
)
|
| 326 |
+
row = cur.fetchone()
|
| 327 |
+
if row and check_password_hash(row["password_hash"], password):
|
| 328 |
+
return row["id"]
|
| 329 |
+
return None
|
| 330 |
+
finally:
|
| 331 |
+
conn.close()
|
| 332 |
+
|
| 333 |
+
def get_username(self, user_id):
|
| 334 |
+
conn = self._get_connection()
|
| 335 |
+
try:
|
| 336 |
+
cur = conn.cursor()
|
| 337 |
+
cur.execute("SELECT username FROM users WHERE id = ?", (user_id,))
|
| 338 |
+
row = cur.fetchone()
|
| 339 |
+
return row["username"] if row else None
|
| 340 |
+
finally:
|
| 341 |
+
conn.close()
|
| 342 |
+
|
| 343 |
+
def is_guest_user(self, user_id):
|
| 344 |
+
username = self.get_username(user_id)
|
| 345 |
+
return username.startswith("__guest_") if username else True
|
| 346 |
+
|
| 347 |
+
def create_guest_user(self, username=None, password=None):
|
| 348 |
+
if not username:
|
| 349 |
+
username = f"__guest_{secrets.token_hex(8)}"
|
| 350 |
+
if not password:
|
| 351 |
+
password = secrets.token_hex(32)
|
| 352 |
+
with self.lock:
|
| 353 |
+
conn = self._get_connection()
|
| 354 |
+
try:
|
| 355 |
+
cur = conn.cursor()
|
| 356 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 357 |
+
pw_hash = generate_password_hash(password)
|
| 358 |
+
cur.execute(
|
| 359 |
+
"INSERT INTO users (username, password_hash) VALUES (?, ?)",
|
| 360 |
+
(username, pw_hash)
|
| 361 |
+
)
|
| 362 |
+
user_id = cur.lastrowid
|
| 363 |
+
conn.commit()
|
| 364 |
+
return user_id
|
| 365 |
+
except sqlite3.IntegrityError:
|
| 366 |
+
conn.rollback()
|
| 367 |
+
return None
|
| 368 |
+
finally:
|
| 369 |
+
conn.close()
|
| 370 |
+
|
| 371 |
+
def find_or_create_google_user(self, google_id, name, email):
|
| 372 |
+
with self.lock:
|
| 373 |
+
conn = self._get_connection()
|
| 374 |
+
try:
|
| 375 |
+
cur = conn.cursor()
|
| 376 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 377 |
+
cur.execute("SELECT id FROM users WHERE google_id = ?", (google_id,))
|
| 378 |
+
row = cur.fetchone()
|
| 379 |
+
if row:
|
| 380 |
+
conn.commit()
|
| 381 |
+
return row["id"]
|
| 382 |
+
|
| 383 |
+
cur.execute("SELECT id FROM users WHERE email = ?", (email,))
|
| 384 |
+
row = cur.fetchone()
|
| 385 |
+
if row:
|
| 386 |
+
cur.execute("UPDATE users SET google_id = ? WHERE id = ?", (google_id, row["id"]))
|
| 387 |
+
conn.commit()
|
| 388 |
+
return row["id"]
|
| 389 |
+
|
| 390 |
+
base_username = name.replace(" ", "_").lower()
|
| 391 |
+
base_username = ''.join(c for c in base_username if c.isalnum() or c == '_')
|
| 392 |
+
if not base_username:
|
| 393 |
+
base_username = "user"
|
| 394 |
+
|
| 395 |
+
username = base_username
|
| 396 |
+
counter = 1
|
| 397 |
+
while True:
|
| 398 |
+
cur.execute("SELECT id FROM users WHERE username = ?", (username,))
|
| 399 |
+
if not cur.fetchone():
|
| 400 |
+
break
|
| 401 |
+
username = f"{base_username}_{counter}"
|
| 402 |
+
counter += 1
|
| 403 |
+
|
| 404 |
+
random_pw = secrets.token_hex(32)
|
| 405 |
+
pw_hash = generate_password_hash(random_pw)
|
| 406 |
+
cur.execute(
|
| 407 |
+
"INSERT INTO users (username, password_hash, google_id, email) VALUES (?, ?, ?, ?)",
|
| 408 |
+
(username, pw_hash, google_id, email)
|
| 409 |
+
)
|
| 410 |
+
user_id = cur.lastrowid
|
| 411 |
+
conn.commit()
|
| 412 |
+
return user_id
|
| 413 |
+
except sqlite3.IntegrityError:
|
| 414 |
+
conn.rollback()
|
| 415 |
+
return None
|
| 416 |
+
finally:
|
| 417 |
+
conn.close()
|
| 418 |
+
|
| 419 |
+
def transfer_guest_data(self, guest_user_id, real_user_id):
|
| 420 |
+
"""
|
| 421 |
+
Transfer guest user data to real user account.
|
| 422 |
+
Handles UNIQUE constraint conflicts by merging learning data.
|
| 423 |
+
"""
|
| 424 |
+
with self.lock:
|
| 425 |
+
conn = self._get_connection()
|
| 426 |
+
try:
|
| 427 |
+
cur = conn.cursor()
|
| 428 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 429 |
+
|
| 430 |
+
# 1. Transfer conversations
|
| 431 |
+
cur.execute(
|
| 432 |
+
"UPDATE conversations SET user_id = ? WHERE user_id = ?",
|
| 433 |
+
(real_user_id, guest_user_id)
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
# 2. Transfer chat sessions
|
| 437 |
+
cur.execute(
|
| 438 |
+
"UPDATE chat_sessions SET user_id = ? WHERE user_id = ?",
|
| 439 |
+
(real_user_id, guest_user_id)
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# 3. Transfer user_profile (ON CONFLICT handles duplicates)
|
| 443 |
+
cur.execute(
|
| 444 |
+
"SELECT user_id, key, value, category, updated_at FROM user_profile WHERE user_id = ?",
|
| 445 |
+
(guest_user_id,)
|
| 446 |
+
)
|
| 447 |
+
for row in cur.fetchall():
|
| 448 |
+
cur.execute(
|
| 449 |
+
"""INSERT INTO user_profile (user_id, key, value, category, updated_at)
|
| 450 |
+
VALUES (?, ?, ?, ?, ?)
|
| 451 |
+
ON CONFLICT (user_id, key) DO UPDATE SET
|
| 452 |
+
value = excluded.value,
|
| 453 |
+
category = excluded.category,
|
| 454 |
+
updated_at = excluded.updated_at""",
|
| 455 |
+
(real_user_id, row["key"], row["value"], row["category"], row["updated_at"])
|
| 456 |
+
)
|
| 457 |
+
cur.execute("DELETE FROM user_profile WHERE user_id = ?", (guest_user_id,))
|
| 458 |
+
|
| 459 |
+
# 4. Transfer user_learning with conflict resolution
|
| 460 |
+
cur.execute(
|
| 461 |
+
"SELECT category, key, value, confidence, times_observed, first_seen, updated_at "
|
| 462 |
+
"FROM user_learning WHERE user_id = ?",
|
| 463 |
+
(guest_user_id,)
|
| 464 |
+
)
|
| 465 |
+
guest_rows = cur.fetchall()
|
| 466 |
+
|
| 467 |
+
for row in guest_rows:
|
| 468 |
+
cur.execute(
|
| 469 |
+
"SELECT id, confidence, times_observed, value FROM user_learning "
|
| 470 |
+
"WHERE user_id = ? AND category = ? AND key = ?",
|
| 471 |
+
(real_user_id, row["category"], row["key"])
|
| 472 |
+
)
|
| 473 |
+
existing = cur.fetchone()
|
| 474 |
+
|
| 475 |
+
if existing:
|
| 476 |
+
new_confidence = max(float(existing["confidence"]), float(row["confidence"]))
|
| 477 |
+
new_times = int(existing["times_observed"]) + int(row["times_observed"])
|
| 478 |
+
new_value = row["value"] if float(row["confidence"]) >= float(existing["confidence"]) else existing["value"]
|
| 479 |
+
cur.execute(
|
| 480 |
+
"UPDATE user_learning SET value = ?, confidence = ?, times_observed = ?, updated_at = ? "
|
| 481 |
+
"WHERE id = ?",
|
| 482 |
+
(new_value, new_confidence, new_times,
|
| 483 |
+
datetime.now().isoformat(sep=' ', timespec='seconds'), existing["id"])
|
| 484 |
+
)
|
| 485 |
+
else:
|
| 486 |
+
cur.execute(
|
| 487 |
+
"INSERT INTO user_learning (user_id, category, key, value, confidence, "
|
| 488 |
+
"times_observed, first_seen, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
| 489 |
+
(real_user_id, row["category"], row["key"], row["value"],
|
| 490 |
+
row["confidence"], row["times_observed"], row["first_seen"],
|
| 491 |
+
datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
cur.execute("DELETE FROM user_learning WHERE user_id = ?", (guest_user_id,))
|
| 495 |
+
|
| 496 |
+
# 5. Transfer user_insights (ON CONFLICT handles duplicates)
|
| 497 |
+
cur.execute(
|
| 498 |
+
"SELECT * FROM user_insights WHERE user_id = ?",
|
| 499 |
+
(guest_user_id,)
|
| 500 |
+
)
|
| 501 |
+
guest_insights = cur.fetchone()
|
| 502 |
+
if guest_insights:
|
| 503 |
+
insights_dict = dict(guest_insights)
|
| 504 |
+
insights_dict.pop("user_id", None)
|
| 505 |
+
cols = [k for k in insights_dict.keys()]
|
| 506 |
+
vals = [insights_dict[k] for k in cols]
|
| 507 |
+
placeholders = ",".join(["?"] * len(vals))
|
| 508 |
+
updates = ",".join([f"{c}=excluded.{c}" for c in cols])
|
| 509 |
+
cur.execute(
|
| 510 |
+
f"""INSERT INTO user_insights (user_id, {','.join(cols)})
|
| 511 |
+
VALUES (? , {placeholders})
|
| 512 |
+
ON CONFLICT (user_id) DO UPDATE SET {updates}""",
|
| 513 |
+
[real_user_id] + vals
|
| 514 |
+
)
|
| 515 |
+
cur.execute("DELETE FROM user_insights WHERE user_id = ?", (guest_user_id,))
|
| 516 |
+
|
| 517 |
+
# 6. Transfer API keys
|
| 518 |
+
cur.execute(
|
| 519 |
+
"UPDATE api_keys SET user_id = ? WHERE user_id = ?",
|
| 520 |
+
(real_user_id, guest_user_id)
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
# 7. Delete guest auth tokens
|
| 524 |
+
cur.execute("DELETE FROM auth_tokens WHERE user_id = ?", (guest_user_id,))
|
| 525 |
+
|
| 526 |
+
# 8. Delete guest user
|
| 527 |
+
cur.execute("DELETE FROM users WHERE id = ?", (guest_user_id,))
|
| 528 |
+
|
| 529 |
+
conn.commit()
|
| 530 |
+
print(f"β
Transferred guest {guest_user_id} β user {real_user_id}")
|
| 531 |
+
except Exception as e:
|
| 532 |
+
conn.rollback()
|
| 533 |
+
print(f"β Transfer error: {e}")
|
| 534 |
+
raise
|
| 535 |
+
finally:
|
| 536 |
+
conn.close()
|
| 537 |
+
|
| 538 |
+
def cleanup_guest_users(self, max_age_days=14):
|
| 539 |
+
with self.lock:
|
| 540 |
+
conn = self._get_connection()
|
| 541 |
+
try:
|
| 542 |
+
cur = conn.cursor()
|
| 543 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 544 |
+
cur.execute(
|
| 545 |
+
"SELECT id FROM users WHERE username LIKE '__guest_%' AND created_at < datetime('now', '-{} days')".format(max_age_days)
|
| 546 |
+
)
|
| 547 |
+
guest_ids = [row["id"] for row in cur.fetchall()]
|
| 548 |
+
if not guest_ids:
|
| 549 |
+
conn.commit()
|
| 550 |
+
return
|
| 551 |
+
placeholders = ','.join('?' * len(guest_ids))
|
| 552 |
+
cur.execute(f"DELETE FROM conversations WHERE user_id IN ({placeholders})", guest_ids)
|
| 553 |
+
cur.execute(f"DELETE FROM chat_sessions WHERE user_id IN ({placeholders})", guest_ids)
|
| 554 |
+
cur.execute(f"DELETE FROM user_learning WHERE user_id IN ({placeholders})", guest_ids)
|
| 555 |
+
cur.execute(f"DELETE FROM user_insights WHERE user_id IN ({placeholders})", guest_ids)
|
| 556 |
+
cur.execute(f"DELETE FROM auth_tokens WHERE user_id IN ({placeholders})", guest_ids)
|
| 557 |
+
cur.execute(f"DELETE FROM api_keys WHERE user_id IN ({placeholders})", guest_ids)
|
| 558 |
+
cur.execute(f"DELETE FROM user_profile WHERE user_id IN ({placeholders})", guest_ids)
|
| 559 |
+
cur.execute(f"DELETE FROM users WHERE id IN ({placeholders})", guest_ids)
|
| 560 |
+
conn.commit()
|
| 561 |
+
print(f"π§Ή Cleaned up {len(guest_ids)} old guest users")
|
| 562 |
+
finally:
|
| 563 |
+
conn.close()
|
| 564 |
+
|
| 565 |
+
# ββ Sessions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 566 |
+
def create_session(self, user_id, title=None):
|
| 567 |
+
with self.lock:
|
| 568 |
+
conn = self._get_connection()
|
| 569 |
+
try:
|
| 570 |
+
cur = conn.cursor()
|
| 571 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 572 |
+
cur.execute(
|
| 573 |
+
"INSERT INTO chat_sessions (user_id, title) VALUES (?, ?)",
|
| 574 |
+
(user_id, title or "New Chat")
|
| 575 |
+
)
|
| 576 |
+
session_id = cur.lastrowid
|
| 577 |
+
conn.commit()
|
| 578 |
+
return session_id
|
| 579 |
+
finally:
|
| 580 |
+
conn.close()
|
| 581 |
+
|
| 582 |
+
def rename_session(self, session_id, title):
|
| 583 |
+
with self.lock:
|
| 584 |
+
conn = self._get_connection()
|
| 585 |
+
try:
|
| 586 |
+
cur = conn.cursor()
|
| 587 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 588 |
+
cur.execute("UPDATE chat_sessions SET title = ? WHERE id = ?", (title[:60], session_id))
|
| 589 |
+
conn.commit()
|
| 590 |
+
finally:
|
| 591 |
+
conn.close()
|
| 592 |
+
|
| 593 |
+
def rename_session_if_default(self, session_id, title, user_id):
|
| 594 |
+
with self.lock:
|
| 595 |
+
conn = self._get_connection()
|
| 596 |
+
try:
|
| 597 |
+
cur = conn.cursor()
|
| 598 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 599 |
+
cur.execute(
|
| 600 |
+
"SELECT title FROM chat_sessions WHERE id = ? AND user_id = ?",
|
| 601 |
+
(session_id, user_id)
|
| 602 |
+
)
|
| 603 |
+
row = cur.fetchone()
|
| 604 |
+
if row and (row["title"] == "New Chat" or not row["title"]):
|
| 605 |
+
cur.execute("UPDATE chat_sessions SET title = ? WHERE id = ?", (title[:60], session_id))
|
| 606 |
+
conn.commit()
|
| 607 |
+
else:
|
| 608 |
+
conn.commit()
|
| 609 |
+
finally:
|
| 610 |
+
conn.close()
|
| 611 |
+
|
| 612 |
+
def delete_session(self, session_id, user_id):
|
| 613 |
+
with self.lock:
|
| 614 |
+
conn = self._get_connection()
|
| 615 |
+
try:
|
| 616 |
+
cur = conn.cursor()
|
| 617 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 618 |
+
cur.execute("DELETE FROM conversations WHERE session_id = ? AND user_id = ?", (session_id, user_id))
|
| 619 |
+
cur.execute("DELETE FROM chat_sessions WHERE id = ? AND user_id = ?", (session_id, user_id))
|
| 620 |
+
conn.commit()
|
| 621 |
+
finally:
|
| 622 |
+
conn.close()
|
| 623 |
+
|
| 624 |
+
def get_sessions(self, user_id):
|
| 625 |
+
conn = self._get_connection()
|
| 626 |
+
try:
|
| 627 |
+
cur = conn.cursor()
|
| 628 |
+
cur.execute(
|
| 629 |
+
"""SELECT cs.id, cs.title, cs.created_at,
|
| 630 |
+
COUNT(c.id) as msg_count
|
| 631 |
+
FROM chat_sessions cs
|
| 632 |
+
LEFT JOIN conversations c ON c.session_id = cs.id
|
| 633 |
+
WHERE cs.user_id = ?
|
| 634 |
+
GROUP BY cs.id
|
| 635 |
+
ORDER BY cs.created_at DESC
|
| 636 |
+
LIMIT 50""",
|
| 637 |
+
(user_id,)
|
| 638 |
+
)
|
| 639 |
+
rows = cur.fetchall()
|
| 640 |
+
return [dict(r) for r in rows]
|
| 641 |
+
finally:
|
| 642 |
+
conn.close()
|
| 643 |
+
|
| 644 |
+
# ββ Chat Messages ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 645 |
+
def save(self, role, content, user_id=None, session_id=None):
|
| 646 |
+
with self.lock:
|
| 647 |
+
conn = self._get_connection()
|
| 648 |
+
try:
|
| 649 |
+
cur = conn.cursor()
|
| 650 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 651 |
+
cur.execute(
|
| 652 |
+
"INSERT INTO conversations (user_id, session_id, role, content, timestamp) VALUES (?, ?, ?, ?, ?)",
|
| 653 |
+
(user_id, session_id, role, content, datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 654 |
+
)
|
| 655 |
+
conn.commit()
|
| 656 |
+
finally:
|
| 657 |
+
conn.close()
|
| 658 |
+
|
| 659 |
+
def get_recent(self, user_id, limit=20, session_id=None):
|
| 660 |
+
conn = self._get_connection()
|
| 661 |
+
try:
|
| 662 |
+
cur = conn.cursor()
|
| 663 |
+
if session_id:
|
| 664 |
+
cur.execute(
|
| 665 |
+
"SELECT role, content, timestamp FROM conversations "
|
| 666 |
+
"WHERE user_id = ? AND session_id = ? ORDER BY id DESC LIMIT ?",
|
| 667 |
+
(user_id, session_id, limit)
|
| 668 |
+
)
|
| 669 |
+
else:
|
| 670 |
+
cur.execute(
|
| 671 |
+
"SELECT role, content, timestamp FROM conversations "
|
| 672 |
+
"WHERE user_id = ? ORDER BY id DESC LIMIT ?",
|
| 673 |
+
(user_id, limit)
|
| 674 |
+
)
|
| 675 |
+
rows = cur.fetchall()
|
| 676 |
+
return list(reversed([(r["role"], r["content"], r["timestamp"]) for r in rows]))
|
| 677 |
+
finally:
|
| 678 |
+
conn.close()
|
| 679 |
+
|
| 680 |
+
def get_session_messages(self, session_id, user_id):
|
| 681 |
+
conn = self._get_connection()
|
| 682 |
+
try:
|
| 683 |
+
cur = conn.cursor()
|
| 684 |
+
cur.execute(
|
| 685 |
+
"SELECT role, content, timestamp FROM conversations "
|
| 686 |
+
"WHERE session_id = ? AND user_id = ? ORDER BY id ASC",
|
| 687 |
+
(session_id, user_id)
|
| 688 |
+
)
|
| 689 |
+
rows = cur.fetchall()
|
| 690 |
+
return [dict(r) for r in rows]
|
| 691 |
+
finally:
|
| 692 |
+
conn.close()
|
| 693 |
+
|
| 694 |
+
def get_chat_history_list(self, user_id):
|
| 695 |
+
conn = self._get_connection()
|
| 696 |
+
try:
|
| 697 |
+
cur = conn.cursor()
|
| 698 |
+
cur.execute(
|
| 699 |
+
"SELECT id, content FROM conversations "
|
| 700 |
+
"WHERE user_id = ? AND role = 'user' ORDER BY id DESC LIMIT 20",
|
| 701 |
+
(user_id,)
|
| 702 |
+
)
|
| 703 |
+
rows = cur.fetchall()
|
| 704 |
+
return [(r["id"], r["content"]) for r in rows]
|
| 705 |
+
finally:
|
| 706 |
+
conn.close()
|
| 707 |
+
|
| 708 |
+
def search_history(self, user_id, query, limit=10):
|
| 709 |
+
conn = self._get_connection()
|
| 710 |
+
try:
|
| 711 |
+
cur = conn.cursor()
|
| 712 |
+
cur.execute(
|
| 713 |
+
"SELECT role, content, timestamp FROM conversations "
|
| 714 |
+
"WHERE user_id = ? AND content LIKE ? ORDER BY id DESC LIMIT ?",
|
| 715 |
+
(user_id, f"%{query}%", limit)
|
| 716 |
+
)
|
| 717 |
+
rows = cur.fetchall()
|
| 718 |
+
return [dict(r) for r in rows]
|
| 719 |
+
finally:
|
| 720 |
+
conn.close()
|
| 721 |
+
|
| 722 |
+
def get_user_message_count(self, user_id):
|
| 723 |
+
conn = self._get_connection()
|
| 724 |
+
try:
|
| 725 |
+
cur = conn.cursor()
|
| 726 |
+
cur.execute(
|
| 727 |
+
"SELECT COUNT(*) as c FROM conversations WHERE user_id = ? AND role = 'user'",
|
| 728 |
+
(user_id,)
|
| 729 |
+
)
|
| 730 |
+
row = cur.fetchone()
|
| 731 |
+
return row["c"] if row else 0
|
| 732 |
+
finally:
|
| 733 |
+
conn.close()
|
| 734 |
+
|
| 735 |
+
# ββ User Profile (user-specific) βββββββββββββββββββββββββββββββββββββ
|
| 736 |
+
def update_user_profile(self, user_id, key, value, category="general"):
|
| 737 |
+
with self.lock:
|
| 738 |
+
conn = self._get_connection()
|
| 739 |
+
try:
|
| 740 |
+
cur = conn.cursor()
|
| 741 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 742 |
+
cur.execute("""
|
| 743 |
+
INSERT INTO user_profile (user_id, key, value, category, updated_at)
|
| 744 |
+
VALUES (?, ?, ?, ?, ?)
|
| 745 |
+
ON CONFLICT (user_id, key) DO UPDATE SET
|
| 746 |
+
value = excluded.value, category = excluded.category, updated_at = excluded.updated_at
|
| 747 |
+
""", (user_id, key, str(value), category, datetime.now().isoformat(sep=' ', timespec='seconds')))
|
| 748 |
+
conn.commit()
|
| 749 |
+
finally:
|
| 750 |
+
conn.close()
|
| 751 |
+
|
| 752 |
+
def get_user_profile(self, user_id):
|
| 753 |
+
conn = self._get_connection()
|
| 754 |
+
try:
|
| 755 |
+
cur = conn.cursor()
|
| 756 |
+
cur.execute(
|
| 757 |
+
"SELECT key, value FROM user_profile WHERE user_id = ? ORDER BY key",
|
| 758 |
+
(user_id,)
|
| 759 |
+
)
|
| 760 |
+
rows = cur.fetchall()
|
| 761 |
+
return {r["key"]: r["value"] for r in rows}
|
| 762 |
+
finally:
|
| 763 |
+
conn.close()
|
| 764 |
+
|
| 765 |
+
def delete_profile_key(self, user_id, key):
|
| 766 |
+
with self.lock:
|
| 767 |
+
conn = self._get_connection()
|
| 768 |
+
try:
|
| 769 |
+
cur = conn.cursor()
|
| 770 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 771 |
+
cur.execute("DELETE FROM user_profile WHERE user_id = ? AND key = ?", (user_id, key))
|
| 772 |
+
conn.commit()
|
| 773 |
+
finally:
|
| 774 |
+
conn.close()
|
| 775 |
+
|
| 776 |
+
def clear_profile(self, user_id):
|
| 777 |
+
with self.lock:
|
| 778 |
+
conn = self._get_connection()
|
| 779 |
+
try:
|
| 780 |
+
cur = conn.cursor()
|
| 781 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 782 |
+
cur.execute("DELETE FROM user_profile WHERE user_id = ?", (user_id,))
|
| 783 |
+
conn.commit()
|
| 784 |
+
finally:
|
| 785 |
+
conn.close()
|
| 786 |
+
|
| 787 |
+
# ββ Self-Learning ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 788 |
+
def store_learning(self, user_id, category, key, value, confidence=0.5):
|
| 789 |
+
with self.lock:
|
| 790 |
+
conn = self._get_connection()
|
| 791 |
+
try:
|
| 792 |
+
cur = conn.cursor()
|
| 793 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 794 |
+
cur.execute(
|
| 795 |
+
"SELECT id, confidence, times_observed FROM user_learning "
|
| 796 |
+
"WHERE user_id = ? AND category = ? AND key = ?",
|
| 797 |
+
(user_id, category, key)
|
| 798 |
+
)
|
| 799 |
+
existing = cur.fetchone()
|
| 800 |
+
if existing:
|
| 801 |
+
new_confidence = min(existing["confidence"] + 0.1, 2.0)
|
| 802 |
+
new_times = existing["times_observed"] + 1
|
| 803 |
+
cur.execute(
|
| 804 |
+
"UPDATE user_learning SET confidence = ?, times_observed = ?, value = ?, updated_at = ? WHERE id = ?",
|
| 805 |
+
(new_confidence, new_times, value, datetime.now().isoformat(sep=' ', timespec='seconds'), existing["id"])
|
| 806 |
+
)
|
| 807 |
+
else:
|
| 808 |
+
cur.execute(
|
| 809 |
+
"INSERT INTO user_learning (user_id, category, key, value, confidence, first_seen, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
| 810 |
+
(user_id, category, key, value, confidence, datetime.now().isoformat(sep=' ', timespec='seconds'), datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 811 |
+
)
|
| 812 |
+
conn.commit()
|
| 813 |
+
finally:
|
| 814 |
+
conn.close()
|
| 815 |
+
|
| 816 |
+
def get_user_learning(self, user_id, category=None):
|
| 817 |
+
conn = self._get_connection()
|
| 818 |
+
try:
|
| 819 |
+
cur = conn.cursor()
|
| 820 |
+
if category:
|
| 821 |
+
cur.execute(
|
| 822 |
+
"SELECT category, key, value, confidence, times_observed FROM user_learning WHERE user_id = ? AND category = ? ORDER BY confidence DESC",
|
| 823 |
+
(user_id, category)
|
| 824 |
+
)
|
| 825 |
+
else:
|
| 826 |
+
cur.execute(
|
| 827 |
+
"SELECT category, key, value, confidence, times_observed FROM user_learning WHERE user_id = ? ORDER BY confidence DESC",
|
| 828 |
+
(user_id,)
|
| 829 |
+
)
|
| 830 |
+
rows = cur.fetchall()
|
| 831 |
+
return [dict(r) for r in rows]
|
| 832 |
+
finally:
|
| 833 |
+
conn.close()
|
| 834 |
+
|
| 835 |
+
def get_learning_by_category(self, user_id, category):
|
| 836 |
+
conn = self._get_connection()
|
| 837 |
+
try:
|
| 838 |
+
cur = conn.cursor()
|
| 839 |
+
cur.execute(
|
| 840 |
+
"SELECT key, value FROM user_learning WHERE user_id = ? AND category = ? ORDER BY confidence DESC",
|
| 841 |
+
(user_id, category)
|
| 842 |
+
)
|
| 843 |
+
rows = cur.fetchall()
|
| 844 |
+
return {r["key"]: r["value"] for r in rows}
|
| 845 |
+
finally:
|
| 846 |
+
conn.close()
|
| 847 |
+
|
| 848 |
+
def get_top_learning_topics(self, user_id, limit=10):
|
| 849 |
+
conn = self._get_connection()
|
| 850 |
+
try:
|
| 851 |
+
cur = conn.cursor()
|
| 852 |
+
cur.execute(
|
| 853 |
+
"SELECT key, value, confidence, times_observed FROM user_learning "
|
| 854 |
+
"WHERE user_id = ? AND category = 'interest' ORDER BY times_observed DESC, confidence DESC LIMIT ?",
|
| 855 |
+
(user_id, limit)
|
| 856 |
+
)
|
| 857 |
+
rows = cur.fetchall()
|
| 858 |
+
return [dict(r) for r in rows]
|
| 859 |
+
finally:
|
| 860 |
+
conn.close()
|
| 861 |
+
|
| 862 |
+
def prune_old_learning(self, user_id, max_entries=500):
|
| 863 |
+
with self.lock:
|
| 864 |
+
conn = self._get_connection()
|
| 865 |
+
try:
|
| 866 |
+
cur = conn.cursor()
|
| 867 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 868 |
+
cur.execute("SELECT COUNT(*) as c FROM user_learning WHERE user_id = ?", (user_id,))
|
| 869 |
+
count = cur.fetchone()["c"]
|
| 870 |
+
if count > max_entries:
|
| 871 |
+
cur.execute(
|
| 872 |
+
"DELETE FROM user_learning WHERE id IN (SELECT id FROM user_learning WHERE user_id = ? ORDER BY confidence ASC, times_observed ASC LIMIT ?)",
|
| 873 |
+
(user_id, count - max_entries)
|
| 874 |
+
)
|
| 875 |
+
conn.commit()
|
| 876 |
+
else:
|
| 877 |
+
conn.commit()
|
| 878 |
+
finally:
|
| 879 |
+
conn.close()
|
| 880 |
+
|
| 881 |
+
# ββ User Insights ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 882 |
+
def update_user_insights(self, user_id, insights_dict):
|
| 883 |
+
with self.lock:
|
| 884 |
+
allowed_keys = ["preferred_formality", "preferred_response_length", "preferred_tone", "topics_of_interest", "communication_patterns", "total_interactions"]
|
| 885 |
+
insert_cols = [k for k in insights_dict if k in allowed_keys]
|
| 886 |
+
if not insert_cols:
|
| 887 |
+
return
|
| 888 |
+
|
| 889 |
+
insert_vals = [json.dumps(insights_dict[k]) if isinstance(insights_dict[k], (dict, list)) else str(insights_dict[k]) for k in insert_cols]
|
| 890 |
+
insert_cols.append("updated_at")
|
| 891 |
+
insert_vals.append(datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 892 |
+
updates = [f"{column} = excluded.{column}" for column in insert_cols]
|
| 893 |
+
|
| 894 |
+
conn = self._get_connection()
|
| 895 |
+
try:
|
| 896 |
+
cur = conn.cursor()
|
| 897 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 898 |
+
sql = f"""INSERT INTO user_insights (user_id, {', '.join(insert_cols)})
|
| 899 |
+
VALUES (?, {', '.join(['?'] * len(insert_vals))})
|
| 900 |
+
ON CONFLICT (user_id) DO UPDATE SET {', '.join(updates)}"""
|
| 901 |
+
cur.execute(sql, [user_id] + insert_vals)
|
| 902 |
+
conn.commit()
|
| 903 |
+
finally:
|
| 904 |
+
conn.close()
|
| 905 |
+
|
| 906 |
+
def get_user_insights(self, user_id):
|
| 907 |
+
conn = self._get_connection()
|
| 908 |
+
try:
|
| 909 |
+
cur = conn.cursor()
|
| 910 |
+
cur.execute("SELECT * FROM user_insights WHERE user_id = ?", (user_id,))
|
| 911 |
+
row = cur.fetchone()
|
| 912 |
+
if row:
|
| 913 |
+
result = dict(row)
|
| 914 |
+
for field in ["topics_of_interest", "communication_patterns"]:
|
| 915 |
+
if result.get(field):
|
| 916 |
+
try:
|
| 917 |
+
result[field] = json.loads(result[field])
|
| 918 |
+
except (json.JSONDecodeError, TypeError):
|
| 919 |
+
result[field] = [] if field == "topics_of_interest" else {}
|
| 920 |
+
return result
|
| 921 |
+
return None
|
| 922 |
+
finally:
|
| 923 |
+
conn.close()
|
| 924 |
+
|
| 925 |
+
def increment_interaction_count(self, user_id):
|
| 926 |
+
with self.lock:
|
| 927 |
+
conn = self._get_connection()
|
| 928 |
+
try:
|
| 929 |
+
cur = conn.cursor()
|
| 930 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 931 |
+
cur.execute(
|
| 932 |
+
"""INSERT INTO user_insights (user_id, total_interactions, updated_at)
|
| 933 |
+
VALUES (?, 1, ?)
|
| 934 |
+
ON CONFLICT (user_id) DO UPDATE SET
|
| 935 |
+
total_interactions = total_interactions + 1, updated_at = excluded.updated_at""",
|
| 936 |
+
(user_id, datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 937 |
+
)
|
| 938 |
+
conn.commit()
|
| 939 |
+
finally:
|
| 940 |
+
conn.close()
|
| 941 |
+
|
| 942 |
+
# ββ API Keys βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 943 |
+
def create_api_key(self, user_id, name="API Key"):
|
| 944 |
+
raw_key = "invicta_sk_" + secrets.token_urlsafe(32)
|
| 945 |
+
key_hash = hashlib.sha256(raw_key.encode()).hexdigest()
|
| 946 |
+
prefix = raw_key[:14] + "..."
|
| 947 |
+
with self.lock:
|
| 948 |
+
conn = self._get_connection()
|
| 949 |
+
try:
|
| 950 |
+
cur = conn.cursor()
|
| 951 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 952 |
+
cur.execute(
|
| 953 |
+
"INSERT INTO api_keys (user_id, key_hash, name, prefix, created_at) VALUES (?, ?, ?, ?, ?)",
|
| 954 |
+
(user_id, key_hash, name, prefix, datetime.now().isoformat(sep=' ', timespec='seconds'))
|
| 955 |
+
)
|
| 956 |
+
key_id = cur.lastrowid
|
| 957 |
+
conn.commit()
|
| 958 |
+
return key_id, raw_key
|
| 959 |
+
finally:
|
| 960 |
+
conn.close()
|
| 961 |
+
|
| 962 |
+
def validate_api_key(self, raw_key):
|
| 963 |
+
if not raw_key or not raw_key.startswith("invicta_sk_"):
|
| 964 |
+
return None
|
| 965 |
+
key_hash = hashlib.sha256(raw_key.encode()).hexdigest()
|
| 966 |
+
conn = self._get_connection()
|
| 967 |
+
try:
|
| 968 |
+
cur = conn.cursor()
|
| 969 |
+
cur.execute(
|
| 970 |
+
"SELECT id, user_id, revoked FROM api_keys WHERE key_hash = ?",
|
| 971 |
+
(key_hash,)
|
| 972 |
+
)
|
| 973 |
+
row = cur.fetchone()
|
| 974 |
+
if row and not row["revoked"]:
|
| 975 |
+
cur.execute(
|
| 976 |
+
"UPDATE api_keys SET last_used = ? WHERE id = ?",
|
| 977 |
+
(datetime.now().isoformat(sep=' ', timespec='seconds'), row["id"])
|
| 978 |
+
)
|
| 979 |
+
conn.commit()
|
| 980 |
+
return row["user_id"]
|
| 981 |
+
return None
|
| 982 |
+
finally:
|
| 983 |
+
conn.close()
|
| 984 |
+
|
| 985 |
+
def get_api_keys(self, user_id):
|
| 986 |
+
conn = self._get_connection()
|
| 987 |
+
try:
|
| 988 |
+
cur = conn.cursor()
|
| 989 |
+
cur.execute(
|
| 990 |
+
"SELECT id, name, prefix, created_at, last_used, revoked, rate_limit FROM api_keys WHERE user_id = ? ORDER BY created_at DESC",
|
| 991 |
+
(user_id,)
|
| 992 |
+
)
|
| 993 |
+
rows = cur.fetchall()
|
| 994 |
+
return [dict(r) for r in rows]
|
| 995 |
+
finally:
|
| 996 |
+
conn.close()
|
| 997 |
+
|
| 998 |
+
def revoke_api_key(self, key_id, user_id):
|
| 999 |
+
with self.lock:
|
| 1000 |
+
conn = self._get_connection()
|
| 1001 |
+
try:
|
| 1002 |
+
cur = conn.cursor()
|
| 1003 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 1004 |
+
cur.execute(
|
| 1005 |
+
"UPDATE api_keys SET revoked = 1 WHERE id = ? AND user_id = ?",
|
| 1006 |
+
(key_id, user_id)
|
| 1007 |
+
)
|
| 1008 |
+
conn.commit()
|
| 1009 |
+
return cur.rowcount > 0
|
| 1010 |
+
finally:
|
| 1011 |
+
conn.close()
|
| 1012 |
+
|
| 1013 |
+
def delete_api_key(self, key_id, user_id):
|
| 1014 |
+
with self.lock:
|
| 1015 |
+
conn = self._get_connection()
|
| 1016 |
+
try:
|
| 1017 |
+
cur = conn.cursor()
|
| 1018 |
+
cur.execute("BEGIN IMMEDIATE")
|
| 1019 |
+
cur.execute("DELETE FROM api_keys WHERE id = ? AND user_id = ?", (key_id, user_id))
|
| 1020 |
+
conn.commit()
|
| 1021 |
+
finally:
|
| 1022 |
+
conn.close()
|
| 1023 |
+
|
| 1024 |
+
# ββ Stats ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1025 |
+
def get_stats(self, user_id):
|
| 1026 |
+
conn = self._get_connection()
|
| 1027 |
+
try:
|
| 1028 |
+
cur = conn.cursor()
|
| 1029 |
+
cur.execute("SELECT COUNT(*) as c FROM conversations WHERE user_id = ?", (user_id,))
|
| 1030 |
+
total = cur.fetchone()["c"]
|
| 1031 |
+
cur.execute("SELECT COUNT(*) as c FROM chat_sessions WHERE user_id = ?", (user_id,))
|
| 1032 |
+
sessions = cur.fetchone()["c"]
|
| 1033 |
+
cur.execute("SELECT COUNT(*) as c FROM user_learning WHERE user_id = ?", (user_id,))
|
| 1034 |
+
learning = cur.fetchone()["c"]
|
| 1035 |
+
return {"total_messages": total, "total_sessions": sessions, "learning_observations": learning}
|
| 1036 |
+
finally:
|
| 1037 |
+
conn.close()
|
searcher.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/searcher.py
|
| 2 |
+
import re
|
| 3 |
+
import time
|
| 4 |
+
import hashlib
|
| 5 |
+
import threading
|
| 6 |
+
import requests
|
| 7 |
+
from bs4 import BeautifulSoup
|
| 8 |
+
from ddgs import DDGS
|
| 9 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 10 |
+
|
| 11 |
+
_USER_AGENTS = [
|
| 12 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
|
| 13 |
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
|
| 14 |
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 15 |
+
]
|
| 16 |
+
_ua_index = 0
|
| 17 |
+
_ua_lock = threading.Lock()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _next_ua():
|
| 21 |
+
global _ua_index
|
| 22 |
+
with _ua_lock:
|
| 23 |
+
ua = _USER_AGENTS[_ua_index % len(_USER_AGENTS)]
|
| 24 |
+
_ua_index += 1
|
| 25 |
+
return ua
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class WebSearcher:
|
| 29 |
+
def __init__(self):
|
| 30 |
+
self.ddgs = DDGS()
|
| 31 |
+
self.scraper_pool = ThreadPoolExecutor(max_workers=3)
|
| 32 |
+
self._cache = {}
|
| 33 |
+
self._cache_ttl = 300 # 5 minutes
|
| 34 |
+
self._cache_lock = threading.Lock()
|
| 35 |
+
|
| 36 |
+
# ββ Cache helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
+
def _cache_key(self, query):
|
| 38 |
+
return hashlib.md5(query.lower().strip().encode()).hexdigest()
|
| 39 |
+
|
| 40 |
+
def _cache_get(self, key):
|
| 41 |
+
with self._cache_lock:
|
| 42 |
+
entry = self._cache.get(key)
|
| 43 |
+
if entry and time.time() - entry["ts"] < self._cache_ttl:
|
| 44 |
+
return entry["value"]
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
def _cache_set(self, key, value):
|
| 48 |
+
with self._cache_lock:
|
| 49 |
+
self._cache[key] = {"value": value, "ts": time.time()}
|
| 50 |
+
# Evict old entries if cache is too large
|
| 51 |
+
if len(self._cache) > 100:
|
| 52 |
+
oldest = min(self._cache.items(), key=lambda x: x[1]["ts"])
|
| 53 |
+
del self._cache[oldest[0]]
|
| 54 |
+
|
| 55 |
+
# ββ Search βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
+
def search(self, query, max_results=6):
|
| 57 |
+
cache_key = self._cache_key(f"search:{query}")
|
| 58 |
+
cached = self._cache_get(cache_key)
|
| 59 |
+
if cached:
|
| 60 |
+
return cached
|
| 61 |
+
|
| 62 |
+
results = []
|
| 63 |
+
seen_urls = set()
|
| 64 |
+
try:
|
| 65 |
+
for r in self.ddgs.text(query, max_results=max_results + 2):
|
| 66 |
+
url = r.get("href", "")
|
| 67 |
+
if url in seen_urls:
|
| 68 |
+
continue
|
| 69 |
+
# Skip low-quality sources
|
| 70 |
+
if any(skip in url for skip in ["reddit.com/r/", "quora.com", "pinterest.com"]):
|
| 71 |
+
continue
|
| 72 |
+
seen_urls.add(url)
|
| 73 |
+
results.append({
|
| 74 |
+
"title": r.get("title", ""),
|
| 75 |
+
"url": url,
|
| 76 |
+
"snippet": r.get("body", ""),
|
| 77 |
+
})
|
| 78 |
+
if len(results) >= max_results:
|
| 79 |
+
break
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"β οΈ Search error: {e}")
|
| 82 |
+
|
| 83 |
+
self._cache_set(cache_key, results)
|
| 84 |
+
return results
|
| 85 |
+
|
| 86 |
+
# ββ Scrape βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
+
def scrape_page(self, url):
|
| 88 |
+
try:
|
| 89 |
+
headers = {
|
| 90 |
+
"User-Agent": _next_ua(),
|
| 91 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
| 92 |
+
"Accept-Language": "en-US,en;q=0.5",
|
| 93 |
+
}
|
| 94 |
+
res = requests.get(url, headers=headers, timeout=6, allow_redirects=True)
|
| 95 |
+
res.raise_for_status()
|
| 96 |
+
|
| 97 |
+
soup = BeautifulSoup(res.text, "html.parser")
|
| 98 |
+
|
| 99 |
+
# Remove boilerplate
|
| 100 |
+
for tag in soup(["script", "style", "nav", "footer", "header",
|
| 101 |
+
"aside", "form", "noscript", "iframe", "ads",
|
| 102 |
+
"[class*='cookie']", "[class*='banner']",
|
| 103 |
+
"[id*='sidebar']", "[id*='nav']"]):
|
| 104 |
+
tag.decompose()
|
| 105 |
+
|
| 106 |
+
# Try to get the main content area
|
| 107 |
+
main = (
|
| 108 |
+
soup.find("main") or
|
| 109 |
+
soup.find("article") or
|
| 110 |
+
soup.find(id="content") or
|
| 111 |
+
soup.find(class_="content") or
|
| 112 |
+
soup.find(class_="post-content") or
|
| 113 |
+
soup.body
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if main:
|
| 117 |
+
text = main.get_text(separator=" ", strip=True)
|
| 118 |
+
else:
|
| 119 |
+
text = soup.get_text(separator=" ", strip=True)
|
| 120 |
+
|
| 121 |
+
# Clean up whitespace and repeated chars
|
| 122 |
+
text = re.sub(r"\s{3,}", " ", text)
|
| 123 |
+
text = re.sub(r"\.{4,}", "...", text)
|
| 124 |
+
return text[:5000]
|
| 125 |
+
|
| 126 |
+
except requests.exceptions.Timeout:
|
| 127 |
+
return None
|
| 128 |
+
except requests.exceptions.HTTPError:
|
| 129 |
+
return None
|
| 130 |
+
except Exception as e:
|
| 131 |
+
print(f"β οΈ Scrape error ({url[:40]}): {e}")
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
# ββ Parallel search + scrape βββββββββββββββββββββββββββββββββββββββββββββ
|
| 135 |
+
def search_and_read_parallel(self, query, max_scrape=3, max_results=8):
|
| 136 |
+
"""Enhanced search with deeper content extraction."""
|
| 137 |
+
results = self.search(query, max_results=max_results)
|
| 138 |
+
if not results:
|
| 139 |
+
return []
|
| 140 |
+
|
| 141 |
+
future_to_idx = {}
|
| 142 |
+
for i, r in enumerate(results[:max_scrape]):
|
| 143 |
+
future = self.scraper_pool.submit(self.scrape_page, r["url"])
|
| 144 |
+
future_to_idx[future] = i
|
| 145 |
+
|
| 146 |
+
for future in as_completed(future_to_idx, timeout=15):
|
| 147 |
+
idx = future_to_idx[future]
|
| 148 |
+
try:
|
| 149 |
+
content = future.result()
|
| 150 |
+
if content:
|
| 151 |
+
results[idx]["full_content"] = content
|
| 152 |
+
# Extract key facts
|
| 153 |
+
sentences = content.split('.')[:20]
|
| 154 |
+
results[idx]["key_points"] = [s.strip() for s in sentences if len(s) > 40 and len(s) < 200]
|
| 155 |
+
except Exception:
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
return results
|
| 159 |
+
|
| 160 |
+
def search_and_read(self, query, deep=True):
|
| 161 |
+
"""Legacy sequential method for compatibility."""
|
| 162 |
+
results = self.search(query)
|
| 163 |
+
if deep:
|
| 164 |
+
for r in results[:2]:
|
| 165 |
+
content = self.scrape_page(r["url"])
|
| 166 |
+
if content:
|
| 167 |
+
r["full_content"] = content
|
| 168 |
+
return results
|