mohhhhhit commited on
Commit
ee41e48
·
verified ·
1 Parent(s): da09722

first commit

Browse files
.gitignore ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ *.pyc
8
+
9
+ # Virtual environment
10
+ venv/
11
+ env/
12
+ ENV/
13
+ data/*
14
+ # Environment variables
15
+ .env
16
+ .env.local
17
+
18
+ # IDE
19
+ .vscode/
20
+ .idea/
21
+ *.swp
22
+ *.swo
23
+ *~
24
+ .DS_Store
25
+
26
+ # Logs
27
+ *.log
config.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
3
+ import sys
4
+
5
+ from pathlib import Path
6
+
7
+ from dotenv import load_dotenv
8
+
9
+
10
+
11
+ # Project paths
12
+
13
+ CODE_ROOT = Path(__file__).parent
14
+ if getattr(sys, "frozen", False) or "Program Files" in str(CODE_ROOT) or "ProgramFiles" in str(CODE_ROOT):
15
+ PROJECT_ROOT = Path(os.getenv("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "NotebookPRO"
16
+ else:
17
+ PROJECT_ROOT = CODE_ROOT
18
+
19
+
20
+
21
+ # Load environment variables from backend/.env and project-root/.env.
22
+
23
+ for env_file in [PROJECT_ROOT / ".env", PROJECT_ROOT.parent / ".env"]:
24
+
25
+ if env_file.exists():
26
+
27
+ load_dotenv(env_file, override=False)
28
+
29
+
30
+
31
+ DATA_DIR = PROJECT_ROOT / "data"
32
+
33
+ MODELS_DIR = PROJECT_ROOT / "models"
34
+
35
+ UPLOADS_DIR = DATA_DIR / "uploads"
36
+
37
+ VECTOR_DB_DIR = DATA_DIR / "vector_db"
38
+
39
+ CHATS_DIR = DATA_DIR / "chats"
40
+
41
+
42
+
43
+ # Create directories if they don't exist
44
+
45
+ for dir_path in [DATA_DIR, MODELS_DIR, UPLOADS_DIR, VECTOR_DB_DIR, CHATS_DIR]:
46
+
47
+ dir_path.mkdir(parents=True, exist_ok=True)
48
+
49
+
50
+
51
+ # Model configuration
52
+
53
+ # RAG uses pre-trained models directly - no training required!
54
+
55
+ MODEL_NAME = os.getenv("MODEL_NAME", "microsoft/phi-2") # Pre-trained model
56
+ FOLLOWUP_MODEL = os.getenv("FOLLOWUP_MODEL", "meta/llama-3.3-70b-instruct") # Fast model for follow-ups
57
+
58
+ USE_PRETRAINED = os.getenv("USE_PRETRAINED", "true").lower() == "true" # Use pre-trained by default
59
+
60
+ MODEL_PATH = os.getenv("MODEL_PATH", str(MODELS_DIR / "trained_model")) # Only if fine-tuned
61
+
62
+ EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "BAAI/bge-small-en-v1.5") # For document embeddings
63
+ RERANKER_MODEL = os.getenv("RERANKER_MODEL", "cross-encoder/ms-marco-MiniLM-L-6-v2")
64
+ EMBEDDING_BATCH_SIZE = int(os.getenv("EMBEDDING_BATCH_SIZE", "16"))
65
+ RERANKER_BATCH_SIZE = int(os.getenv("RERANKER_BATCH_SIZE", "8"))
66
+
67
+
68
+
69
+ # API Keys
70
+
71
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
72
+
73
+ HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY", "")
74
+
75
+
76
+
77
+ # Application settings
78
+
79
+ MAX_UPLOAD_SIZE = int(os.getenv("MAX_UPLOAD_SIZE", "200")) # MB
80
+
81
+ TEMPERATURE = float(os.getenv("TEMPERATURE", "0.7"))
82
+
83
+ MAX_TOKENS = int(os.getenv("MAX_TOKENS", "2048"))
84
+
85
+ # Memory behavior when switching spaces
86
+ SPACE_SWITCH_CLEAR_CUDA_CACHE = os.getenv("SPACE_SWITCH_CLEAR_CUDA_CACHE", "true").lower() == "true"
87
+ SPACE_SWITCH_UNLOAD_EMBEDDING_MODEL = os.getenv("SPACE_SWITCH_UNLOAD_EMBEDDING_MODEL", "false").lower() == "true"
88
+
89
+ CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "700"))
90
+
91
+ CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "120"))
92
+
93
+
94
+
95
+ # Use cases
96
+
97
+ USE_CASES = {
98
+
99
+ "explanation": "Provide detailed explanation of concepts",
100
+
101
+ "summary": "Generate concise summary of content",
102
+
103
+ "qa": "Answer questions based on content",
104
+
105
+ "notes": "Create structured study notes"
106
+
107
+ }
108
+
main.py ADDED
@@ -0,0 +1,2097 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI Backend for NotebookPRO
3
+ Handles RAG, LLM, file processing, and chat management
4
+ """
5
+ from fastapi import FastAPI, File, UploadFile, HTTPException, Response
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+ from fastapi.responses import StreamingResponse
8
+ from pydantic import BaseModel
9
+ from typing import List, Optional, Dict, Any
10
+ from pathlib import Path
11
+ import json
12
+ from datetime import datetime
13
+ import uuid
14
+ import sys
15
+ import warnings
16
+ import logging
17
+ import os
18
+ import shutil
19
+ import tempfile
20
+ import zipfile
21
+ import re
22
+ import html
23
+ import time
24
+ from io import BytesIO
25
+ from fastapi.responses import FileResponse
26
+ from starlette.background import BackgroundTask
27
+ import weasyprint
28
+ import markdown
29
+ import latex2mathml.converter
30
+ import ziamath
31
+
32
+ # Suppress warnings
33
+ warnings.filterwarnings('ignore')
34
+ os.environ['PYTHONWARNINGS'] = 'ignore'
35
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
36
+ os.environ['TOKENIZERS_PARALLELISM'] = 'false'
37
+ os.environ.setdefault('OMP_NUM_THREADS', '2')
38
+ os.environ.setdefault('MKL_NUM_THREADS', '2')
39
+ os.environ.setdefault('OPENBLAS_NUM_THREADS', '2')
40
+ os.environ.setdefault('NUMEXPR_NUM_THREADS', '2')
41
+ logging.getLogger().setLevel(logging.ERROR)
42
+
43
+ # Add project root to path
44
+ sys.path.append(str(Path(__file__).parent.parent))
45
+
46
+ import config
47
+ from utils.document_processor import DocumentProcessor
48
+ from utils.vector_db import VectorDatabase
49
+ from utils.hybrid_retriever import HybridRetriever
50
+ from utils.llm_generator import LLMGenerator
51
+ from utils.config_manager import ConfigManager
52
+ from utils.spaces_manager import SpacesManager
53
+ from utils.studio_manager import StudioManager
54
+ from utils.studio_generator import StudioGenerator
55
+ from models.studio_models import (
56
+ NotebookEntry,
57
+ NotebookEntryCreate,
58
+ NotebookEntryUpdate,
59
+ Flashcard,
60
+ FlashcardCreate,
61
+ FlashcardUpdate,
62
+ FlashcardReview,
63
+ FlashcardGenerateRequest,
64
+ MasteryLevel,
65
+ Quiz,
66
+ QuizCreate,
67
+ QuizGenerateRequest,
68
+ QuizSubmission,
69
+ QuizResult,
70
+ QuizHistory,
71
+ )
72
+
73
+ # Initialize FastAPI
74
+ app = FastAPI(title="NotebookPRO API", version="2.0.0")
75
+
76
+ # CORS - Allow Flutter web to connect
77
+ app.add_middleware(
78
+ CORSMiddleware,
79
+ allow_origins=["*"], # In production, specify your Flutter web URL
80
+ allow_credentials=True,
81
+ allow_methods=["*"],
82
+ allow_headers=["*"],
83
+ )
84
+
85
+ # Global instances
86
+ config_manager = ConfigManager()
87
+ spaces_manager = SpacesManager()
88
+ studio_manager = StudioManager()
89
+ studio_generator = None # Will be initialized after LLM
90
+ vector_db = None
91
+ hybrid_retriever = None
92
+ llm_generator = None
93
+ current_space = None
94
+
95
+ # ==================== Pydantic Models ====================
96
+
97
+ class ChatMessage(BaseModel):
98
+ role: str
99
+ content: str
100
+ timestamp: str
101
+ sources: Optional[List[Dict[str, Any]]] = None
102
+ suggested_follow_ups: Optional[List[str]] = None
103
+
104
+ class ChatRequest(BaseModel):
105
+ query: str
106
+ space_id: str
107
+ chat_id: Optional[str] = None
108
+ workflow: str = "chat"
109
+
110
+ class ChatResponse(BaseModel):
111
+ response: str
112
+ sources: List[Dict[str, Any]]
113
+ chat_id: str
114
+ timestamp: str
115
+ ui_notice: Optional[str] = None
116
+ suggested_follow_ups: Optional[List[str]] = None
117
+
118
+ class DeleteMessageRequest(BaseModel):
119
+ timestamp: str
120
+ role: str = "assistant"
121
+ content: Optional[str] = None
122
+ delete_related_user: bool = False
123
+
124
+ class SpaceCreate(BaseModel):
125
+ name: str
126
+
127
+ class SpaceResponse(BaseModel):
128
+ id: str
129
+ name: str
130
+ created_at: str
131
+ file_count: int
132
+
133
+ class ChatInfo(BaseModel):
134
+ id: str
135
+ title: str
136
+ preview: str
137
+ created_at: str
138
+ updated_at: str
139
+ message_count: int
140
+
141
+ class ConfigResponse(BaseModel):
142
+ gemini_api_key: Optional[str]
143
+ nvidia_api_key: Optional[str] = None
144
+ groq_api_key: Optional[str] = None
145
+
146
+ class ConfigUpdate(BaseModel):
147
+ gemini_api_key: Optional[str] = None
148
+ nvidia_api_key: Optional[str] = None
149
+ groq_api_key: Optional[str] = None
150
+
151
+ class ChatToNotebookRequest(BaseModel):
152
+ space_id: str
153
+ question: str
154
+ answer: str
155
+ chat_id: Optional[str] = None
156
+ assistant_timestamp: Optional[str] = None
157
+ tags: List[str] = []
158
+ space_name: Optional[str] = None
159
+
160
+ class ExportAnswerPdfRequest(BaseModel):
161
+ space_id: str
162
+ question: str
163
+ answer: str
164
+ title: Optional[str] = None
165
+
166
+ class QAItem(BaseModel):
167
+ question: str
168
+ answer: str
169
+
170
+ class ExportCombinedAnswersPdfRequest(BaseModel):
171
+ space_id: str
172
+ chat_title: Optional[str] = None
173
+ items: List[QAItem]
174
+
175
+
176
+ class ExportSelectedNotebookPdfRequest(BaseModel):
177
+ space_id: str
178
+ entry_ids: List[str]
179
+ title: Optional[str] = None
180
+
181
+ # ==================== Helper Functions ====================
182
+
183
+ def get_data_dir():
184
+ """Get data directory path"""
185
+ return Path(config.DATA_DIR)
186
+
187
+ def get_space_dir(space_id: str):
188
+ """Get space-specific directory"""
189
+ return get_data_dir() / "spaces" / space_id
190
+
191
+ def load_chats_for_space(space_id: str) -> List[Dict]:
192
+ """Load all chats for a space"""
193
+ chats_file = get_space_dir(space_id) / "chats.json"
194
+ if chats_file.exists():
195
+ with open(chats_file, 'r', encoding='utf-8') as f:
196
+ return json.load(f)
197
+ return []
198
+
199
+ def save_chats_for_space(space_id: str, chats: List[Dict]):
200
+ """Save chats for a space"""
201
+ chats_file = get_space_dir(space_id) / "chats.json"
202
+ chats_file.parent.mkdir(parents=True, exist_ok=True)
203
+ with open(chats_file, 'w', encoding='utf-8') as f:
204
+ json.dump(chats, f, indent=2, ensure_ascii=False)
205
+
206
+ def get_chat_title(messages: List[Dict]) -> str:
207
+ """Generate chat title from first user message"""
208
+ for msg in messages:
209
+ if msg['role'] == 'user':
210
+ content = msg['content'][:50]
211
+ return content + "..." if len(msg['content']) > 50 else content
212
+ return "New Chat"
213
+
214
+
215
+ def _is_nlp_metrics_query(query: str) -> bool:
216
+ """Detect metric-heavy NLP evaluation questions that need broader retrieval."""
217
+ q = (query or "").lower()
218
+ triggers = (
219
+ "bleu",
220
+ "rouge",
221
+ "meteor",
222
+ "bertscore",
223
+ "sequence generation",
224
+ "machine translation",
225
+ "summarization",
226
+ "n-gram",
227
+ "brevity penalty",
228
+ "evaluation metric",
229
+ "nlp metric",
230
+ "transformer",
231
+ )
232
+ return any(t in q for t in triggers)
233
+
234
+
235
+ def _extract_year_from_filename(filename: str) -> Optional[int]:
236
+ """Infer publication year from filename (best-effort)."""
237
+ if not filename:
238
+ return None
239
+
240
+ matches = re.findall(r'(?:19|20)\d{2}', filename)
241
+ if not matches:
242
+ return None
243
+
244
+ try:
245
+ years = [int(y) for y in matches]
246
+ valid_years = [y for y in years if 1900 <= y <= 2100]
247
+ if not valid_years:
248
+ return None
249
+ return max(valid_years)
250
+ except Exception:
251
+ return None
252
+
253
+
254
+ def _resolve_publication_year(meta: Optional[Dict[str, Any]]) -> Optional[int]:
255
+ """Resolve publication year from metadata; fallback to filename inference."""
256
+ if not meta:
257
+ return None
258
+
259
+ raw_year = meta.get('publication_year')
260
+ if raw_year is not None:
261
+ try:
262
+ year = int(raw_year)
263
+ if 1900 <= year <= 2100:
264
+ return year
265
+ except Exception:
266
+ pass
267
+
268
+ filename = str(meta.get('filename', ''))
269
+ return _extract_year_from_filename(filename)
270
+
271
+
272
+ def _build_retrieval_queries(query: str) -> List[str]:
273
+ """Build retrieval query set; add targeted expansions for NLP metric topics."""
274
+ queries = [query]
275
+ if not _is_nlp_metrics_query(query):
276
+ return queries
277
+
278
+ queries.extend([
279
+ f"{query} BLEU brevity penalty BP n-gram precision",
280
+ f"{query} ROUGE-N ROUGE-L longest common subsequence LCS F1 recall precision",
281
+ f"{query} METEOR stemming synonym WordNet exact-match limitation",
282
+ f"{query} BERTScore contextual embeddings semantic similarity deep learning transformer",
283
+ ])
284
+ return queries
285
+
286
+
287
+ def _retrieve_documents_for_query(
288
+ retriever: HybridRetriever,
289
+ query: str,
290
+ n_results: int,
291
+ score_threshold: float,
292
+ ):
293
+ """Retrieve with optional query expansions and merge by max score."""
294
+ retrieval_queries = _build_retrieval_queries(query)
295
+ per_query_n = max(12, n_results // 2) if len(retrieval_queries) > 1 else n_results
296
+ per_query_threshold = max(0.0, score_threshold - 0.01) if len(retrieval_queries) > 1 else score_threshold
297
+
298
+ merged = {}
299
+ for q in retrieval_queries:
300
+ docs, metas, scores = retriever.retrieve(
301
+ query=q,
302
+ n_results=per_query_n,
303
+ score_threshold=per_query_threshold,
304
+ )
305
+ for doc, meta, score in zip(docs, metas, scores):
306
+ current = merged.get(doc)
307
+ score_value = float(score)
308
+ if current is None or score_value > current["score"]:
309
+ merged[doc] = {
310
+ "doc": doc,
311
+ "meta": meta,
312
+ "score": score_value,
313
+ }
314
+
315
+ ranked = sorted(merged.values(), key=lambda item: item["score"], reverse=True)
316
+ selected = ranked[:n_results]
317
+ return (
318
+ [item["doc"] for item in selected],
319
+ [item["meta"] for item in selected],
320
+ [item["score"] for item in selected],
321
+ )
322
+
323
+
324
+ def _sanitize_retrieved_chunk(text: str) -> str:
325
+ """Clean retrieval chunks to remove OCR/table-of-contents numeric noise."""
326
+ if not text:
327
+ return ""
328
+
329
+ cleaned_lines: List[str] = []
330
+ for raw_line in text.splitlines():
331
+ line = raw_line.strip()
332
+ if not line:
333
+ cleaned_lines.append("")
334
+ continue
335
+
336
+ # Drop pathological section-number runs like: 1.1.1.1.1.1...
337
+ if re.search(r'(?:\d+\.){8,}\d*', line):
338
+ continue
339
+
340
+ compact = re.sub(r'\s+', '', line)
341
+ # Drop long punctuation/digit-only lines that come from OCR artifacts.
342
+ if len(compact) >= 40 and re.fullmatch(r'[\d\W_]+', compact):
343
+ continue
344
+
345
+ line = re.sub(r'(?:\d+\.){8,}\d*', ' ', line)
346
+ line = re.sub(r'\s{2,}', ' ', line).strip()
347
+ if line:
348
+ cleaned_lines.append(line)
349
+
350
+ cleaned = "\n".join(cleaned_lines)
351
+ cleaned = re.sub(r'\n{3,}', '\n\n', cleaned).strip()
352
+ return cleaned
353
+
354
+
355
+ def _is_usable_context_chunk(text: str) -> bool:
356
+ """Reject chunks that are mostly numeric garbage after cleanup."""
357
+ if not text or len(text) < 80:
358
+ return False
359
+
360
+ letters = len(re.findall(r'[A-Za-z]', text))
361
+ digits = len(re.findall(r'\d', text))
362
+
363
+ if letters < 35:
364
+ return False
365
+
366
+ # If a chunk is heavily numeric and has little natural language, skip it.
367
+ if digits > 0 and letters < max(80, int(digits * 0.35)):
368
+ return False
369
+
370
+ return True
371
+
372
+
373
+ def _format_sse_event(event: str, payload: Dict[str, Any]) -> str:
374
+ """Format one Server-Sent Event frame."""
375
+ return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n"
376
+
377
+ def ensure_notebooks_for_existing_spaces() -> int:
378
+ """Ensure every existing space has an associated notebook metadata record."""
379
+ created_count = 0
380
+ spaces = spaces_manager.get_all_spaces()
381
+
382
+ for space in spaces:
383
+ space_id = space.get('id')
384
+ if not space_id:
385
+ continue
386
+
387
+ existing_notebook = studio_manager.get_space_notebook(space_id)
388
+ if existing_notebook:
389
+ continue
390
+
391
+ studio_manager.ensure_space_notebook(space_id, space.get('name', space_id))
392
+ created_count += 1
393
+
394
+ return created_count
395
+
396
+ def rebuild_space_index_if_missing(space_id: str, force: bool = False) -> int:
397
+ """Rebuild a space index from uploaded files if the current index is empty."""
398
+ if not vector_db:
399
+ return 0
400
+
401
+ if not force:
402
+ try:
403
+ existing_count = vector_db.get_collection_count()
404
+ if existing_count > 0:
405
+ print(f"[INDEX_REBUILD {space_id}] skip existing_vectors={existing_count}")
406
+ return 0
407
+ except Exception:
408
+ # If count check fails, continue with a best-effort rebuild.
409
+ pass
410
+
411
+ uploads_dir = get_space_dir(space_id) / "uploads"
412
+ if not uploads_dir.exists():
413
+ return 0
414
+
415
+ files = [
416
+ p for p in uploads_dir.iterdir()
417
+ if p.is_file() and p.suffix.lower() in {".pdf", ".docx", ".txt"}
418
+ ]
419
+ if not files:
420
+ print(f"[INDEX_REBUILD {space_id}] skip no_supported_uploads")
421
+ return 0
422
+
423
+ print(f"[INDEX_REBUILD {space_id}] start files={len(files)}")
424
+
425
+ processor = DocumentProcessor()
426
+ texts: List[str] = []
427
+ metadatas: List[Dict[str, Any]] = []
428
+ ids: List[str] = []
429
+
430
+ for file_path in files:
431
+ try:
432
+ print(f"[INDEX_REBUILD {space_id}] processing_file={file_path.name}")
433
+ file_data = processor.process_file(file_path)
434
+ chunk_filename = file_data.get('virtual_filename', file_path.name)
435
+ chunks = processor.chunk_text(
436
+ file_data['content'],
437
+ chunk_size=config.CHUNK_SIZE,
438
+ overlap=config.CHUNK_OVERLAP,
439
+ semantic=True,
440
+ source_filename=chunk_filename,
441
+ )
442
+ total_chunks = len(chunks)
443
+ print(f"[INDEX_REBUILD {space_id}] file_chunks={total_chunks} file={chunk_filename}")
444
+ publication_year = file_data.get('publication_year', '0000')
445
+ for idx, chunk in enumerate(chunks):
446
+ texts.append(chunk)
447
+ metadatas.append({
448
+ 'filename': chunk_filename,
449
+ 'chunk_index': idx,
450
+ 'total_chunks': total_chunks,
451
+ 'source_type': file_data['format'],
452
+ 'publication_year': publication_year,
453
+ })
454
+ ids.append(f"{space_id}_rebuild_{len(ids)}_{uuid.uuid4().hex[:8]}")
455
+ except Exception as e:
456
+ print(f"Index rebuild skipped {file_path.name}: {e}")
457
+
458
+ if not texts:
459
+ print(f"[INDEX_REBUILD {space_id}] skip no_chunks_generated")
460
+ return 0
461
+
462
+ batch_size = 5000
463
+ for i in range(0, len(texts), batch_size):
464
+ end = min(i + batch_size, len(texts))
465
+ print(f"[INDEX_REBUILD {space_id}] batch_add start={i} end={end}")
466
+ vector_db.add_documents(
467
+ texts[i:i + batch_size],
468
+ metadatas[i:i + batch_size],
469
+ ids[i:i + batch_size],
470
+ )
471
+
472
+ print(f"[INDEX_REBUILD {space_id}] done chunks={len(texts)}")
473
+ return len(texts)
474
+
475
+ def initialize_space(space_id: str):
476
+ """Initialize vector DB and components for a space"""
477
+ global vector_db, hybrid_retriever, llm_generator, studio_generator, current_space
478
+
479
+ # Fast path: reuse already initialized components for the active space.
480
+ if current_space == space_id and vector_db is not None and llm_generator is not None:
481
+ return
482
+
483
+ # On space switch, release references and clear caches to reduce stale VRAM pressure.
484
+ switching_space = current_space is not None and current_space != space_id
485
+ if switching_space:
486
+ vector_db = None
487
+ hybrid_retriever = None
488
+ llm_generator = None
489
+ studio_generator = None
490
+ if config.SPACE_SWITCH_CLEAR_CUDA_CACHE:
491
+ VectorDatabase.clear_runtime_caches(
492
+ unload_embedding_model=config.SPACE_SWITCH_UNLOAD_EMBEDDING_MODEL,
493
+ )
494
+
495
+ # Get API keys for Gemini answers and NVIDIA follow-up questions.
496
+ gemini_key = config_manager.get_api_key('gemini')
497
+ nvidia_key = config_manager.get_api_key('nvidia')
498
+ groq_key = config_manager.get_api_key('groq')
499
+
500
+ if not gemini_key and not nvidia_key and not groq_key:
501
+ raise HTTPException(
502
+ status_code=400,
503
+ detail="No API key configured. Please add a Gemini or NVIDIA API key.",
504
+ )
505
+
506
+ # Initialize vector database for this space (space-local persistence path).
507
+ space_dir = get_space_dir(space_id)
508
+ vector_db = VectorDatabase(
509
+ collection_name=f"space_{space_id}",
510
+ persist_directory=str(space_dir / "vector_db"),
511
+ )
512
+
513
+ collection_reset = vector_db.ensure_collection_embedding_compatibility()
514
+ if collection_reset:
515
+ print(f"[INDEX_REBUILD {space_id}] reset_due_to_embedding_dimension_change=1")
516
+
517
+ hybrid_retriever = HybridRetriever(vector_db, alpha=0.6)
518
+
519
+ # Backward-compatibility: rebuild embeddings from uploaded files if index is empty.
520
+ rebuild_space_index_if_missing(space_id)
521
+
522
+ # Initialize LLM generator (Gemini for answers, NVIDIA for follow-ups).
523
+ llm_generator = LLMGenerator(
524
+ provider="gemini",
525
+ gemini_api_key=gemini_key,
526
+ nvidia_api_key=nvidia_key,
527
+ groq_api_key=groq_key,
528
+ )
529
+
530
+ # Initialize studio generator with LLM
531
+ studio_generator = StudioGenerator(llm_generator, studio_manager)
532
+ current_space = space_id
533
+
534
+ @app.on_event("startup")
535
+ async def startup_sync_notebooks():
536
+ """Auto-create missing notebooks for pre-existing spaces when backend starts and preload GPU models."""
537
+ try:
538
+ from utils.vector_db import VectorDatabase
539
+ print("Preloading embedding and reranker models to GPU...")
540
+ VectorDatabase._get_or_create_embedding_model()
541
+ VectorDatabase._get_or_create_reranker()
542
+ print("Models successfully preloaded to GPU.")
543
+ except Exception as e:
544
+ print(f"Failed to preload models: {e}")
545
+
546
+ try:
547
+ created = ensure_notebooks_for_existing_spaces()
548
+ if created > 0:
549
+ print(f"Created {created} missing notebook(s) for existing spaces")
550
+ except Exception as e:
551
+ # Keep server startup resilient even if sync fails.
552
+ print(f"Notebook startup sync failed: {e}")
553
+
554
+ # ==================== API Endpoints ====================
555
+
556
+ @app.get("/")
557
+ async def root():
558
+ """Health check"""
559
+ return {"status": "NotebookPRO API is running", "version": "2.0.0"}
560
+
561
+ @app.get("/api/health")
562
+ async def health_check():
563
+ """Fast health endpoint used by the Flutter app connection checks."""
564
+ return {"status": "ok"}
565
+
566
+ @app.get("/api/config", response_model=ConfigResponse)
567
+ async def get_config():
568
+ """Get current API keys (masked)"""
569
+ gemini_key = config_manager.get_api_key('gemini')
570
+ nvidia_key = config_manager.get_api_key('nvidia')
571
+ groq_key = config_manager.get_api_key('groq')
572
+ masked_gemini_key = "***" + gemini_key[-4:] if gemini_key else None
573
+ masked_nvidia_key = "***" + nvidia_key[-4:] if nvidia_key else None
574
+ masked_groq_key = "***" + groq_key[-4:] if groq_key else None
575
+
576
+ return ConfigResponse(
577
+ gemini_api_key=masked_gemini_key,
578
+ nvidia_api_key=masked_nvidia_key,
579
+ groq_api_key=masked_groq_key,
580
+ )
581
+
582
+ @app.get("/api/system/export")
583
+ async def export_data():
584
+ """Export the entire data directory as a ZIP file."""
585
+ try:
586
+ tmp_dir = Path(tempfile.gettempdir())
587
+ zip_base_path = tmp_dir / f"notebookpro_backup_{int(time.time())}"
588
+
589
+ # This creates notebookpro_backup_xxx.zip
590
+ shutil.make_archive(
591
+ base_name=str(zip_base_path),
592
+ format="zip",
593
+ root_dir=str(get_data_dir())
594
+ )
595
+
596
+ zip_path = str(zip_base_path) + ".zip"
597
+
598
+ return FileResponse(
599
+ path=zip_path,
600
+ filename="notebookpro_backup.zip",
601
+ media_type="application/zip",
602
+ background=BackgroundTask(lambda: os.remove(zip_path))
603
+ )
604
+ except Exception as e:
605
+ raise HTTPException(status_code=500, detail=f"Export failed: {e}")
606
+
607
+ @app.post("/api/system/import")
608
+ async def import_data(file: UploadFile = File(...)):
609
+ """Import a ZIP file and overwrite the data directory."""
610
+ if not file.filename.endswith('.zip'):
611
+ raise HTTPException(status_code=400, detail="Must be a ZIP file")
612
+
613
+ try:
614
+ tmp_dir = Path(tempfile.gettempdir())
615
+ zip_path = tmp_dir / f"notebookpro_import_{int(time.time())}.zip"
616
+
617
+ with open(zip_path, "wb") as buffer:
618
+ shutil.copyfileobj(file.file, buffer)
619
+
620
+ # Verify zip structure minimally
621
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
622
+ # For a basic check, we don't strict-enforce specific files in case of empty states
623
+ pass
624
+
625
+ extract_dir = tmp_dir / f"notebookpro_import_extracted_{int(time.time())}"
626
+ if extract_dir.exists():
627
+ shutil.rmtree(extract_dir)
628
+ extract_dir.mkdir(parents=True)
629
+
630
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
631
+ zip_ref.extractall(extract_dir)
632
+
633
+ # Re-initialize managers to close DB connections if any?
634
+ # Best approach: replace data and ask user to restart.
635
+
636
+ # Replace data directory
637
+ data_dir = get_data_dir()
638
+ for item in extract_dir.iterdir():
639
+ target = data_dir / item.name
640
+ if target.exists():
641
+ if target.is_dir():
642
+ shutil.rmtree(target)
643
+ else:
644
+ target.unlink()
645
+ shutil.move(str(item), str(target))
646
+
647
+ # Clean up
648
+ os.remove(zip_path)
649
+ shutil.rmtree(extract_dir)
650
+
651
+ return {"status": "success", "message": "Data imported successfully. Please restart the backend."}
652
+
653
+ except Exception as e:
654
+ raise HTTPException(status_code=500, detail=f"Import failed: {e}")
655
+
656
+
657
+ @app.post("/api/config")
658
+ async def update_config(config_update: ConfigUpdate):
659
+ """Update API keys"""
660
+ if config_update.gemini_api_key:
661
+ config_manager.set_api_key('gemini', config_update.gemini_api_key)
662
+
663
+ if config_update.nvidia_api_key:
664
+ config_manager.set_api_key('nvidia', config_update.nvidia_api_key)
665
+
666
+ if config_update.groq_api_key:
667
+ config_manager.set_api_key('groq', config_update.groq_api_key)
668
+
669
+ return {"status": "success", "message": "Configuration updated"}
670
+
671
+ @app.get("/api/spaces", response_model=List[SpaceResponse])
672
+ async def get_spaces():
673
+ """Get all spaces"""
674
+ # Self-healing check in case spaces were created externally while server is running.
675
+ ensure_notebooks_for_existing_spaces()
676
+ spaces = spaces_manager.get_all_spaces()
677
+
678
+ result = []
679
+ for space in spaces:
680
+ space_id = space['id']
681
+ space_dir = get_space_dir(space_id)
682
+ processed_file = space_dir / "processed_files.json"
683
+
684
+ file_count = 0
685
+ if processed_file.exists():
686
+ with open(processed_file, 'r', encoding='utf-8-sig') as f:
687
+ file_count = len(json.load(f))
688
+
689
+ result.append(SpaceResponse(
690
+ id=space_id,
691
+ name=space['name'],
692
+ created_at=space['created_at'],
693
+ file_count=file_count
694
+ ))
695
+
696
+ return result
697
+
698
+ @app.post("/api/spaces", response_model=SpaceResponse)
699
+ async def create_space(space_data: SpaceCreate):
700
+ """Create a new space"""
701
+ try:
702
+ space = spaces_manager.create_space(space_data.name)
703
+
704
+ # Create associated notebook metadata with the same name as the space.
705
+ studio_manager.ensure_space_notebook(space['id'], space['name'])
706
+
707
+ return SpaceResponse(
708
+ id=space['id'],
709
+ name=space['name'],
710
+ created_at=space['created_at'],
711
+ file_count=0
712
+ )
713
+ except ValueError as e:
714
+ raise HTTPException(status_code=400, detail=str(e))
715
+
716
+ @app.delete("/api/spaces/{space_id}")
717
+ async def delete_space(space_id: str):
718
+ """Delete a space"""
719
+ try:
720
+ spaces_manager.delete_space(space_id)
721
+
722
+ # Delete space directory
723
+ space_dir = get_space_dir(space_id)
724
+ if space_dir.exists():
725
+ shutil.rmtree(space_dir)
726
+
727
+ return {"status": "success", "message": f"Space {space_id} deleted"}
728
+ except ValueError as e:
729
+ raise HTTPException(status_code=400, detail=str(e))
730
+ except Exception as e:
731
+ raise HTTPException(status_code=500, detail=f"Error deleting space: {str(e)}")
732
+
733
+ @app.get("/api/spaces/{space_id}/chats", response_model=List[ChatInfo])
734
+ async def get_chats(space_id: str):
735
+ """Get all chats for a space"""
736
+ chats = load_chats_for_space(space_id)
737
+
738
+ result = []
739
+ for chat in chats:
740
+ messages = chat.get('messages', [])
741
+ result.append(ChatInfo(
742
+ id=chat['id'],
743
+ title=get_chat_title(messages),
744
+ preview=messages[0]['content'][:100] if messages else "",
745
+ created_at=chat.get('created_at', ''),
746
+ updated_at=chat.get('updated_at', ''),
747
+ message_count=len(messages)
748
+ ))
749
+
750
+ return result
751
+
752
+ @app.get("/api/spaces/{space_id}/chats/{chat_id}")
753
+ async def get_chat(space_id: str, chat_id: str):
754
+ """Get specific chat by ID"""
755
+ chats = load_chats_for_space(space_id)
756
+
757
+ for chat in chats:
758
+ if chat['id'] == chat_id:
759
+ return chat
760
+
761
+ raise HTTPException(status_code=404, detail="Chat not found")
762
+
763
+ @app.delete("/api/spaces/{space_id}/chats/{chat_id}")
764
+ async def delete_chat(space_id: str, chat_id: str):
765
+ """Delete a chat"""
766
+ chats = load_chats_for_space(space_id)
767
+ chats = [c for c in chats if c['id'] != chat_id]
768
+ save_chats_for_space(space_id, chats)
769
+
770
+ return {"status": "success", "message": f"Chat {chat_id} deleted"}
771
+
772
+ @app.post("/api/spaces/{space_id}/chats/{chat_id}/messages/delete")
773
+ async def delete_chat_message(space_id: str, chat_id: str, request: DeleteMessageRequest):
774
+ """Delete a specific message from a chat.
775
+
776
+ Optionally deletes the nearest preceding user message as a Q/A pair.
777
+ """
778
+ chats = load_chats_for_space(space_id)
779
+
780
+ chat = next((c for c in chats if c.get('id') == chat_id), None)
781
+ if chat is None:
782
+ raise HTTPException(status_code=404, detail="Chat not found")
783
+
784
+ messages = chat.get('messages', [])
785
+ removed = False
786
+ target_index = -1
787
+
788
+ # Primary match: role + timestamp (+ optional exact content)
789
+ for idx, msg in enumerate(messages):
790
+ if msg.get('role') != request.role:
791
+ continue
792
+ if msg.get('timestamp') != request.timestamp:
793
+ continue
794
+ if request.content is not None and msg.get('content') != request.content:
795
+ continue
796
+
797
+ target_index = idx
798
+ removed = True
799
+ break
800
+
801
+ # Fallback: role + exact content (handles rare timestamp drift)
802
+ if not removed and request.content is not None:
803
+ for idx in range(len(messages) - 1, -1, -1):
804
+ msg = messages[idx]
805
+ if msg.get('role') == request.role and msg.get('content') == request.content:
806
+ target_index = idx
807
+ removed = True
808
+ break
809
+
810
+ if not removed:
811
+ raise HTTPException(status_code=404, detail="Message not found")
812
+
813
+ indexes_to_remove = {target_index}
814
+
815
+ if request.delete_related_user and target_index > 0:
816
+ for idx in range(target_index - 1, -1, -1):
817
+ if messages[idx].get('role') == 'user':
818
+ indexes_to_remove.add(idx)
819
+ break
820
+
821
+ for idx in sorted(indexes_to_remove, reverse=True):
822
+ if 0 <= idx < len(messages):
823
+ del messages[idx]
824
+
825
+ chat['messages'] = messages
826
+ chat['updated_at'] = datetime.now().isoformat()
827
+ save_chats_for_space(space_id, chats)
828
+
829
+ return {
830
+ "status": "success",
831
+ "message": "Message deleted",
832
+ "remaining_messages": len(messages),
833
+ }
834
+
835
+ @app.post("/api/chat", response_model=ChatResponse)
836
+ async def chat(request: ChatRequest):
837
+ """Process a chat message with RAG"""
838
+ try:
839
+ trace_id = uuid.uuid4().hex[:8]
840
+ t_start = time.perf_counter()
841
+ print(
842
+ f"[CHAT_TIMING {trace_id}] start space={request.space_id} workflow={request.workflow} "
843
+ f"query_len={len((request.query or '').strip())}"
844
+ )
845
+
846
+ # Initialize space if needed
847
+ t_init = time.perf_counter()
848
+ initialize_space(request.space_id)
849
+ print(f"[CHAT_TIMING {trace_id}] init_space_ms={(time.perf_counter() - t_init) * 1000:.1f}")
850
+
851
+ # Reuse per-space retriever to avoid rebuilding BM25 index every request.
852
+ global hybrid_retriever
853
+ if hybrid_retriever is None:
854
+ hybrid_retriever = HybridRetriever(vector_db, alpha=0.6)
855
+ print(f"[CHAT_TIMING {trace_id}] retriever_cache=MISS")
856
+ else:
857
+ print(f"[CHAT_TIMING {trace_id}] retriever_cache=HIT")
858
+
859
+ retrieval_n = int(os.getenv("CHAT_RETRIEVAL_RESULTS", "16"))
860
+ retrieval_n = max(8, min(retrieval_n, 30))
861
+ retrieval_threshold = float(os.getenv("CHAT_RETRIEVAL_THRESHOLD", "0.01"))
862
+ chat_max_tokens = int(os.getenv("CHAT_MAX_TOKENS", "1800"))
863
+ chat_max_tokens = max(700, min(chat_max_tokens, 2600))
864
+
865
+ # Retrieve relevant documents (with targeted query expansion for metric-heavy NLP prompts).
866
+ t_retrieve = time.perf_counter()
867
+ documents, metadatas, scores = _retrieve_documents_for_query(
868
+ retriever=hybrid_retriever,
869
+ query=request.query,
870
+ n_results=retrieval_n,
871
+ score_threshold=retrieval_threshold,
872
+ )
873
+ print(
874
+ f"[CHAT_TIMING {trace_id}] retrieval_ms={(time.perf_counter() - t_retrieve) * 1000:.1f} "
875
+ f"docs={len(documents)} query_expansions={len(_build_retrieval_queries(request.query))}"
876
+ )
877
+
878
+ # Build context from retrieved documents
879
+ t_context = time.perf_counter()
880
+ context_parts = []
881
+ sources = []
882
+ filtered_metadatas = []
883
+ dropped_chunks = 0
884
+ seen_context_fingerprints = set()
885
+
886
+ for doc, meta, score in zip(documents, metadatas, scores):
887
+ cleaned_doc = _sanitize_retrieved_chunk(doc)
888
+ if not _is_usable_context_chunk(cleaned_doc):
889
+ dropped_chunks += 1
890
+ continue
891
+
892
+ fingerprint = re.sub(r'\s+', ' ', cleaned_doc[:320]).lower()
893
+ if fingerprint in seen_context_fingerprints:
894
+ dropped_chunks += 1
895
+ continue
896
+ seen_context_fingerprints.add(fingerprint)
897
+
898
+ # Extract clean filename for source citation
899
+ filename = meta.get('filename', 'Unknown')
900
+ clean_name = filename.replace('.pdf', '').replace('.docx', '').replace('.txt', '')
901
+ publication_year = _resolve_publication_year(meta)
902
+ year_label = str(publication_year) if publication_year else "UNKNOWN"
903
+ source_idx = len(context_parts) + 1
904
+ context_parts.append(f"Source [{source_idx}] [YEAR: {year_label}] ({clean_name}):\n{cleaned_doc}\n")
905
+ filtered_metadatas.append(meta)
906
+ sources.append({
907
+ "content": cleaned_doc[:200] + "..." if len(cleaned_doc) > 200 else cleaned_doc,
908
+ "metadata": meta,
909
+ "score": float(score)
910
+ })
911
+
912
+ print(
913
+ f"[CHAT_TIMING {trace_id}] context_filter kept={len(context_parts)} dropped={dropped_chunks}"
914
+ )
915
+
916
+ if not context_parts:
917
+ return ChatResponse(
918
+ response=(
919
+ "I found related retrieval hits, but they were too noisy to trust for a grounded answer. "
920
+ "Please re-upload a cleaner source file (or a text-based PDF) and try again."
921
+ ),
922
+ sources=[],
923
+ chat_id=request.chat_id or str(uuid.uuid4()),
924
+ timestamp=datetime.now().isoformat(),
925
+ ui_notice="Context chunks were filtered due to low text quality.",
926
+ suggested_follow_ups=[],
927
+ )
928
+
929
+ context = "\n".join(context_parts)
930
+ print(
931
+ f"[CHAT_TIMING {trace_id}] context_ms={(time.perf_counter() - t_context) * 1000:.1f} "
932
+ f"context_chars={len(context)}"
933
+ )
934
+
935
+ # Use the advanced generate_response method which has the new NotebookLM-style prompt
936
+ t_llm = time.perf_counter()
937
+ response = llm_generator.generate_response(
938
+ prompt=request.query,
939
+ context=context,
940
+ use_case=request.workflow if request.workflow in ["summary", "explanation", "qa", "notes"] else "qa",
941
+ metadatas=filtered_metadatas,
942
+ temperature=0.35,
943
+ max_tokens=chat_max_tokens,
944
+ )
945
+ print(
946
+ f"[CHAT_TIMING {trace_id}] llm_ms={(time.perf_counter() - t_llm) * 1000:.1f} "
947
+ f"response_chars={len(response or '')}"
948
+ )
949
+
950
+ t_follow = time.perf_counter()
951
+ suggested_follow_ups = llm_generator.generate_follow_up_questions(
952
+ prompt=request.query,
953
+ context=context,
954
+ answer=response,
955
+ max_questions=3,
956
+ )
957
+ print(
958
+ f"[CHAT_TIMING {trace_id}] followups_ms={(time.perf_counter() - t_follow) * 1000:.1f} "
959
+ f"count={len(suggested_follow_ups)}"
960
+ )
961
+ ui_notice = getattr(llm_generator, 'last_notice', None)
962
+
963
+ # Create or update chat
964
+ chat_id = request.chat_id or str(uuid.uuid4())
965
+ chats = load_chats_for_space(request.space_id)
966
+
967
+ # Find existing chat or create new
968
+ chat = None
969
+ for c in chats:
970
+ if c['id'] == chat_id:
971
+ chat = c
972
+ break
973
+
974
+ if not chat:
975
+ chat = {
976
+ 'id': chat_id,
977
+ 'messages': [],
978
+ 'created_at': datetime.now().isoformat(),
979
+ 'updated_at': datetime.now().isoformat()
980
+ }
981
+ chats.append(chat)
982
+
983
+ # Add messages
984
+ timestamp = datetime.now().isoformat()
985
+ chat['messages'].extend([
986
+ {'role': 'user', 'content': request.query, 'timestamp': timestamp},
987
+ {
988
+ 'role': 'assistant',
989
+ 'content': response,
990
+ 'timestamp': timestamp,
991
+ 'sources': sources,
992
+ 'suggested_follow_ups': suggested_follow_ups,
993
+ }
994
+ ])
995
+ chat['updated_at'] = timestamp
996
+
997
+ # Save chats
998
+ t_save = time.perf_counter()
999
+ save_chats_for_space(request.space_id, chats)
1000
+ print(f"[CHAT_TIMING {trace_id}] save_ms={(time.perf_counter() - t_save) * 1000:.1f}")
1001
+ print(f"[CHAT_TIMING {trace_id}] total_ms={(time.perf_counter() - t_start) * 1000:.1f}")
1002
+
1003
+ return ChatResponse(
1004
+ response=response,
1005
+ sources=sources,
1006
+ chat_id=chat_id,
1007
+ timestamp=timestamp,
1008
+ ui_notice=ui_notice,
1009
+ suggested_follow_ups=suggested_follow_ups,
1010
+ )
1011
+
1012
+ except HTTPException:
1013
+ raise
1014
+ except Exception as e:
1015
+ raise HTTPException(status_code=500, detail=str(e))
1016
+
1017
+
1018
+ @app.post("/api/chat/stream")
1019
+ async def chat_stream(request: ChatRequest):
1020
+ """SSE streaming compatibility endpoint for the Flutter client."""
1021
+ trace_id = "unknown"
1022
+ t_stream = time.perf_counter()
1023
+ try:
1024
+ trace_id = uuid.uuid4().hex[:8]
1025
+ t_stream = time.perf_counter()
1026
+ print(f"[CHAT_STREAM {trace_id}] start space={request.space_id}")
1027
+
1028
+ def event_stream():
1029
+ try:
1030
+ # 1. Initialization & Retrieval
1031
+ initialize_space(request.space_id)
1032
+ global hybrid_retriever
1033
+ if hybrid_retriever is None:
1034
+ hybrid_retriever = HybridRetriever(vector_db, alpha=0.6)
1035
+
1036
+ retrieval_n = int(os.getenv("CHAT_RETRIEVAL_RESULTS", "16"))
1037
+ retrieval_n = max(8, min(retrieval_n, 30))
1038
+ retrieval_threshold = float(os.getenv("CHAT_RETRIEVAL_THRESHOLD", "0.01"))
1039
+ chat_max_tokens = int(os.getenv("CHAT_MAX_TOKENS", "1800"))
1040
+ chat_max_tokens = max(700, min(chat_max_tokens, 2600))
1041
+
1042
+ documents, metadatas, scores = _retrieve_documents_for_query(
1043
+ retriever=hybrid_retriever,
1044
+ query=request.query,
1045
+ n_results=retrieval_n,
1046
+ score_threshold=retrieval_threshold,
1047
+ )
1048
+
1049
+ # 2. Context Building
1050
+ context_parts = []
1051
+ sources = []
1052
+ filtered_metadatas = []
1053
+ seen_context_fingerprints = set()
1054
+
1055
+ for doc, meta, score in zip(documents, metadatas, scores):
1056
+ cleaned_doc = _sanitize_retrieved_chunk(doc)
1057
+ if not _is_usable_context_chunk(cleaned_doc):
1058
+ continue
1059
+
1060
+ fingerprint = re.sub(r'\s+', ' ', cleaned_doc[:320]).lower()
1061
+ if fingerprint in seen_context_fingerprints:
1062
+ continue
1063
+ seen_context_fingerprints.add(fingerprint)
1064
+
1065
+ filename = meta.get('filename', 'Unknown')
1066
+ clean_name = filename.replace('.pdf', '').replace('.docx', '').replace('.txt', '')
1067
+ publication_year = _resolve_publication_year(meta)
1068
+ year_label = str(publication_year) if publication_year else "UNKNOWN"
1069
+ source_idx = len(context_parts) + 1
1070
+
1071
+ context_parts.append(f"Source [{source_idx}] [YEAR: {year_label}] ({clean_name}):\n{cleaned_doc}\n")
1072
+ filtered_metadatas.append(meta)
1073
+ sources.append({
1074
+ "content": cleaned_doc[:200] + "..." if len(cleaned_doc) > 200 else cleaned_doc,
1075
+ "metadata": meta,
1076
+ "score": float(score)
1077
+ })
1078
+
1079
+ chat_id = request.chat_id or str(uuid.uuid4())
1080
+ timestamp = datetime.now().isoformat()
1081
+
1082
+ if not context_parts:
1083
+ yield _format_sse_event("meta", {
1084
+ "chat_id": chat_id,
1085
+ "timestamp": timestamp,
1086
+ "sources": [],
1087
+ "ui_notice": "Context chunks were filtered due to low text quality.",
1088
+ })
1089
+ msg = "I found related retrieval hits, but they were too noisy to trust for a grounded answer. Please re-upload a cleaner source file (or a text-based PDF) and try again."
1090
+ yield _format_sse_event("token", {"delta": msg})
1091
+ yield _format_sse_event("done", {
1092
+ "chat_id": chat_id,
1093
+ "timestamp": timestamp,
1094
+ "response": msg,
1095
+ "sources": [],
1096
+ "ui_notice": "Context chunks were filtered due to low text quality.",
1097
+ "suggested_follow_ups": [],
1098
+ })
1099
+ return
1100
+
1101
+ context = "\n".join(context_parts)
1102
+
1103
+ # 3. Yield Meta (unblocks UI, shows citations)
1104
+ yield _format_sse_event("meta", {
1105
+ "chat_id": chat_id,
1106
+ "timestamp": timestamp,
1107
+ "sources": sources,
1108
+ "ui_notice": getattr(llm_generator, 'last_notice', None),
1109
+ })
1110
+
1111
+ # 4. Stream LLM tokens live
1112
+ full_response = ""
1113
+ generator = llm_generator.generate_stream(
1114
+ prompt=request.query,
1115
+ context=context,
1116
+ use_case=request.workflow if request.workflow in ["summary", "explanation", "qa", "notes"] else "qa",
1117
+ metadatas=filtered_metadatas,
1118
+ temperature=0.35,
1119
+ max_tokens=chat_max_tokens,
1120
+ )
1121
+
1122
+ for chunk in generator:
1123
+ if chunk:
1124
+ full_response += chunk
1125
+ yield _format_sse_event("token", {"delta": chunk})
1126
+
1127
+ # 5. Generate follow-ups and save history
1128
+ suggested_follow_ups = llm_generator.generate_follow_up_questions(
1129
+ prompt=request.query,
1130
+ context=context,
1131
+ answer=full_response,
1132
+ max_questions=3,
1133
+ )
1134
+
1135
+ if suggested_follow_ups:
1136
+ yield _format_sse_event("followups", {
1137
+ "suggested_follow_ups": suggested_follow_ups,
1138
+ })
1139
+
1140
+ chats = load_chats_for_space(request.space_id)
1141
+ chat = next((c for c in chats if c['id'] == chat_id), None)
1142
+ if not chat:
1143
+ chat = {
1144
+ 'id': chat_id,
1145
+ 'messages': [],
1146
+ 'created_at': timestamp,
1147
+ 'updated_at': timestamp
1148
+ }
1149
+ chats.append(chat)
1150
+
1151
+ chat['messages'].extend([
1152
+ {'role': 'user', 'content': request.query, 'timestamp': timestamp},
1153
+ {
1154
+ 'role': 'assistant',
1155
+ 'content': full_response,
1156
+ 'timestamp': timestamp,
1157
+ 'sources': sources,
1158
+ 'suggested_follow_ups': suggested_follow_ups,
1159
+ }
1160
+ ])
1161
+ chat['updated_at'] = timestamp
1162
+ save_chats_for_space(request.space_id, chats)
1163
+
1164
+ # 6. Yield Done
1165
+ yield _format_sse_event("done", {
1166
+ "chat_id": chat_id,
1167
+ "timestamp": timestamp,
1168
+ "response": full_response,
1169
+ "sources": sources,
1170
+ "ui_notice": getattr(llm_generator, 'last_notice', None),
1171
+ "suggested_follow_ups": suggested_follow_ups,
1172
+ })
1173
+
1174
+ except Exception as e:
1175
+ print(f"[CHAT_STREAM ERROR] {trace_id}: {str(e)}")
1176
+ yield _format_sse_event("error", {"message": str(e)})
1177
+
1178
+ return StreamingResponse(
1179
+ event_stream(),
1180
+ media_type="text/event-stream",
1181
+ headers={
1182
+ "Cache-Control": "no-cache",
1183
+ "Connection": "keep-alive",
1184
+ "X-Accel-Buffering": "no",
1185
+ },
1186
+ )
1187
+
1188
+ except Exception as exc:
1189
+ error_message = str(exc)
1190
+ elapsed_ms = (time.perf_counter() - t_stream) * 1000
1191
+ print(f"[CHAT_STREAM {trace_id}] error ms={elapsed_ms:.1f} detail={error_message}")
1192
+
1193
+ def error_stream(message: str = error_message):
1194
+ yield _format_sse_event("error", {"message": message})
1195
+
1196
+ return StreamingResponse(
1197
+ error_stream(),
1198
+ media_type="text/event-stream",
1199
+ status_code=500,
1200
+ )
1201
+
1202
+ @app.post("/api/spaces/{space_id}/upload")
1203
+ async def upload_files(space_id: str, files: List[UploadFile] = File(...)):
1204
+ """Upload and process files for a space"""
1205
+ try:
1206
+ global hybrid_retriever
1207
+ # Initialize space
1208
+ initialize_space(space_id)
1209
+
1210
+ # Save uploaded files temporarily
1211
+ space_dir = get_space_dir(space_id)
1212
+ uploads_dir = space_dir / "uploads"
1213
+ uploads_dir.mkdir(parents=True, exist_ok=True)
1214
+
1215
+ processor = DocumentProcessor()
1216
+ all_chunks = []
1217
+ processed_files = []
1218
+ skipped_files = []
1219
+
1220
+ processed_file_path = space_dir / "processed_files.json"
1221
+ existing_filenames = set()
1222
+ if processed_file_path.exists():
1223
+ with open(processed_file_path, 'r', encoding='utf-8-sig') as f:
1224
+ try:
1225
+ for item in json.load(f):
1226
+ existing_filenames.add(item.get('original_filename', item.get('filename')))
1227
+ except Exception:
1228
+ pass
1229
+
1230
+ for file in files:
1231
+ filename = (file.filename or "unnamed_upload").strip()
1232
+
1233
+ if filename in existing_filenames:
1234
+ print(f"[UPLOAD] skip file={filename} reason=already_exists")
1235
+ skipped_files.append({"filename": filename, "reason": "File already exists in this space"})
1236
+ continue
1237
+
1238
+ # Ensure we read from the start of the upload stream.
1239
+ try:
1240
+ await file.seek(0)
1241
+ except Exception:
1242
+ pass
1243
+
1244
+ content = await file.read()
1245
+ content_size = len(content) if content else 0
1246
+ if content_size == 0:
1247
+ reason = "Upload payload was empty (0 bytes)"
1248
+ skipped_files.append({"filename": filename, "reason": reason})
1249
+ print(f"[UPLOAD] skip file={filename} reason={reason}")
1250
+ continue
1251
+
1252
+ # Save file
1253
+ file_path = uploads_dir / filename
1254
+ with open(file_path, "wb") as f:
1255
+ f.write(content)
1256
+ f.flush()
1257
+ os.fsync(f.fileno())
1258
+
1259
+ try:
1260
+ if file_path.stat().st_size == 0:
1261
+ reason = "File became 0 bytes after write"
1262
+ skipped_files.append({"filename": filename, "reason": reason})
1263
+ print(f"[UPLOAD] skip file={filename} reason={reason}")
1264
+ file_path.unlink(missing_ok=True)
1265
+ continue
1266
+ except Exception:
1267
+ pass
1268
+
1269
+ # Process file and extract content
1270
+ try:
1271
+ print(f"[UPLOAD] Extracting text from newly uploaded file: {filename}")
1272
+ file_data = processor.process_file(file_path)
1273
+ content = file_data['content']
1274
+ chunk_filename = file_data.get('virtual_filename', filename)
1275
+
1276
+ # Chunk the content
1277
+ chunks = processor.chunk_text(
1278
+ content,
1279
+ chunk_size=config.CHUNK_SIZE,
1280
+ overlap=config.CHUNK_OVERLAP,
1281
+ semantic=True,
1282
+ source_filename=chunk_filename,
1283
+ )
1284
+
1285
+ # Format chunks for vector database
1286
+ formatted_chunks = []
1287
+ publication_year = file_data.get('publication_year', '0000')
1288
+ for idx, chunk in enumerate(chunks):
1289
+ formatted_chunks.append({
1290
+ 'content': chunk,
1291
+ 'metadata': {
1292
+ 'filename': chunk_filename,
1293
+ 'chunk_index': idx,
1294
+ 'total_chunks': len(chunks),
1295
+ 'source_type': file_data['format'],
1296
+ 'publication_year': publication_year,
1297
+ }
1298
+ })
1299
+
1300
+ all_chunks.extend(formatted_chunks)
1301
+ processed_files.append({
1302
+ 'filename': chunk_filename,
1303
+ 'original_filename': filename,
1304
+ 'publication_year': publication_year,
1305
+ 'chunks': len(chunks),
1306
+ 'processed_at': datetime.now().isoformat()
1307
+ })
1308
+
1309
+ # Progressively save to processed_files.json so UI can see them immediately
1310
+ try:
1311
+ p_file = space_dir / "processed_files.json"
1312
+ ex = []
1313
+ if p_file.exists():
1314
+ with open(p_file, 'r', encoding='utf-8-sig') as f:
1315
+ ex = json.load(f)
1316
+ # Filter out ones we just added to avoid duplicates if we run this multiple times
1317
+ ex = [x for x in ex if x.get('original_filename') != filename and x.get('filename') != chunk_filename]
1318
+ ex.append(processed_files[-1])
1319
+ with open(p_file, 'w', encoding='utf-8') as f:
1320
+ json.dump(ex, f, indent=2)
1321
+ except Exception as e:
1322
+ print(f"Error saving progressive processed_files.json: {e}")
1323
+
1324
+ except Exception as e:
1325
+ # Log error but continue with other files
1326
+ err = str(e)
1327
+ print(f"Error processing {filename}: {err}")
1328
+ skipped_files.append({"filename": filename, "reason": err})
1329
+ continue
1330
+
1331
+ # Add to vector database in batches to avoid size limits
1332
+ if all_chunks:
1333
+ print(f"[UPLOAD] Finished extracting text. Now embedding {len(all_chunks)} chunks for the new files. This may take a while on CPU...")
1334
+ # Extract texts, metadatas, and generate IDs
1335
+ texts = [chunk['content'] for chunk in all_chunks]
1336
+ metadatas = [chunk['metadata'] for chunk in all_chunks]
1337
+ ids = [f"{space_id}_{idx}_{uuid.uuid4().hex[:8]}" for idx in range(len(all_chunks))]
1338
+
1339
+ # Process in batches of 5000 to avoid ChromaDB batch size limit
1340
+ batch_size = 5000
1341
+ for i in range(0, len(texts), batch_size):
1342
+ batch_texts = texts[i:i + batch_size]
1343
+ batch_metadatas = metadatas[i:i + batch_size]
1344
+ batch_ids = ids[i:i + batch_size]
1345
+
1346
+ vector_db.add_documents(batch_texts, batch_metadatas, batch_ids)
1347
+ print(f"Processed batch {i//batch_size + 1}/{(len(texts)-1)//batch_size + 1}")
1348
+
1349
+ # Refresh retriever cache so BM25 index includes newly uploaded chunks.
1350
+ hybrid_retriever = HybridRetriever(vector_db, alpha=0.6)
1351
+ print(f"[UPLOAD] retriever_cache_refreshed space={space_id} chunks={len(all_chunks)}")
1352
+
1353
+ # Save processed files info — write atomically to avoid corruption
1354
+ processed_file = space_dir / "processed_files.json"
1355
+ existing = []
1356
+ if processed_file.exists():
1357
+ try:
1358
+ with open(processed_file, 'r', encoding='utf-8-sig') as f:
1359
+ existing = json.load(f)
1360
+ except Exception:
1361
+ existing = []
1362
+
1363
+ # Deduplicate to prevent double-adding from the progressive save
1364
+ new_originals = {p.get('original_filename') for p in processed_files}
1365
+ new_virtuals = {p.get('filename') for p in processed_files}
1366
+ existing = [x for x in existing if x.get('original_filename') not in new_originals and x.get('filename') not in new_virtuals]
1367
+
1368
+ existing.extend(processed_files)
1369
+ tmp_file = processed_file.with_suffix('.tmp')
1370
+ with open(tmp_file, 'w', encoding='utf-8') as f:
1371
+ json.dump(existing, f, indent=2, ensure_ascii=False)
1372
+ tmp_file.replace(processed_file) # atomic rename
1373
+
1374
+ print(f"[UPLOAD] Finished successfully! Returning response to UI.")
1375
+
1376
+ return {
1377
+ "status": "success",
1378
+ "files_processed": len(processed_files),
1379
+ "total_chunks": len(all_chunks),
1380
+ "files_skipped": len(skipped_files),
1381
+ "skipped_files": skipped_files,
1382
+ }
1383
+
1384
+ except HTTPException:
1385
+ raise
1386
+ except Exception as e:
1387
+ raise HTTPException(status_code=500, detail=str(e))
1388
+
1389
+ @app.get("/api/spaces/{space_id}/files")
1390
+ async def get_files(space_id: str):
1391
+ """Get processed files for a space"""
1392
+ processed_file = get_space_dir(space_id) / "processed_files.json"
1393
+
1394
+ if processed_file.exists():
1395
+ with open(processed_file, 'r', encoding='utf-8-sig') as f:
1396
+ return json.load(f)
1397
+
1398
+ return []
1399
+
1400
+ @app.delete("/api/spaces/{space_id}/files/{filename}")
1401
+ async def delete_file(space_id: str, filename: str):
1402
+ """Delete a specific file from a space"""
1403
+ try:
1404
+ original_filename = filename
1405
+ processed_file = get_space_dir(space_id) / "processed_files.json"
1406
+ if processed_file.exists():
1407
+ with open(processed_file, 'r', encoding='utf-8-sig') as f:
1408
+ files_data = json.load(f)
1409
+
1410
+ # Support both virtual ([YEAR] name.pdf) and original filename lookups.
1411
+ for item in files_data:
1412
+ if item.get('filename') == filename:
1413
+ original_filename = item.get('original_filename', filename)
1414
+ break
1415
+ if item.get('original_filename') == filename:
1416
+ original_filename = item.get('original_filename', filename)
1417
+ break
1418
+
1419
+ files_data = [
1420
+ f for f in files_data
1421
+ if f.get('filename') != filename and f.get('original_filename') != filename
1422
+ ]
1423
+ with open(processed_file, 'w', encoding='utf-8') as f:
1424
+ json.dump(files_data, f, indent=2, ensure_ascii=False)
1425
+
1426
+ # Remove physical file from uploads directory.
1427
+ file_path = get_space_dir(space_id) / "uploads" / original_filename
1428
+ if file_path.exists():
1429
+ file_path.unlink()
1430
+
1431
+ # Remove associated chunks from vector DB metadata.
1432
+ try:
1433
+ ids_to_delete: List[str] = []
1434
+ candidate_names = {filename, original_filename}
1435
+ try:
1436
+ for candidate in candidate_names:
1437
+ filtered = vector_db.collection.get(where={"filename": candidate})
1438
+ if filtered and filtered.get('ids'):
1439
+ ids_to_delete.extend(filtered.get('ids', []))
1440
+ except Exception:
1441
+ # Fallback path for older Chroma versions where `where` can be inconsistent.
1442
+ all_results = vector_db.collection.get()
1443
+ all_ids = all_results.get('ids', []) if all_results else []
1444
+ all_metas = all_results.get('metadatas', []) if all_results else []
1445
+ for doc_id, metadata in zip(all_ids, all_metas):
1446
+ if metadata and metadata.get('filename') in candidate_names:
1447
+ ids_to_delete.append(doc_id)
1448
+
1449
+ if ids_to_delete:
1450
+ vector_db.collection.delete(ids=list(set(ids_to_delete)))
1451
+ vector_db.client.persist()
1452
+ print(f"Deleted {len(ids_to_delete)} chunks for {filename}")
1453
+ except Exception as e:
1454
+ print(f"Vector cleanup warning for {filename}: {e}")
1455
+
1456
+ return {
1457
+ "status": "success",
1458
+ "message": f"File {filename} deleted"
1459
+ }
1460
+
1461
+ except HTTPException:
1462
+ raise
1463
+ except Exception as e:
1464
+ raise HTTPException(status_code=500, detail=str(e))
1465
+
1466
+
1467
+ import weasyprint
1468
+ import markdown
1469
+ import latex2mathml.converter
1470
+ import re
1471
+ from datetime import datetime
1472
+ import html
1473
+
1474
+ def _render_latex_to_mathml(text: str) -> str:
1475
+ """Find math expressions in text and convert using ziamath."""
1476
+ # Remove citations like [13], **[1, 2]**, etc.
1477
+ text = re.sub(r'\s*(?:\*\*)?\[\d+(?:,\s*\d+)*\](?:\*\*)?', '', text)
1478
+
1479
+ def render_math(m, display_mode):
1480
+ try:
1481
+ math_str = m.group(1).strip()
1482
+ # ziamath handles rendering SVG from latex
1483
+ svg = ziamath.Math.fromlatex(math_str).svg()
1484
+ if display_mode == 'block':
1485
+ return f'<div style="text-align: center; margin: 1em 0;">{svg}</div>'
1486
+ else:
1487
+ return f'<span style="display:inline-block; vertical-align:middle;">{svg}</span>'
1488
+ except Exception as e:
1489
+ print("MATH RENDER ERROR: ", e)
1490
+ return m.group(0)
1491
+
1492
+ # Block math using \[ ... \]
1493
+ text = re.sub(r'\\\[([\s\S]+?)\\\]', lambda m: render_math(m, 'block'), text)
1494
+
1495
+ # Inline math using \( ... \)
1496
+ text = re.sub(r'\\\(([\s\S]+?)\\\)', lambda m: render_math(m, 'inline'), text)
1497
+
1498
+ # Block math using $$
1499
+ text = re.sub(r'\$\$([\s\S]+?)\$\$', lambda m: render_math(m, 'block'), text)
1500
+
1501
+ # Inline math using $
1502
+ text = re.sub(r'\$(?!\$)([\s\S]+?)\$(?!\$)', lambda m: render_math(m, 'inline'), text)
1503
+
1504
+ return text
1505
+
1506
+ def _render_html_page(title: str, body_html: str, space_id: str) -> bytes:
1507
+ """Generates WeasyPrint PDF from HTML."""
1508
+ exported_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
1509
+ html_content = f"""
1510
+ <!DOCTYPE html>
1511
+ <html>
1512
+ <head>
1513
+ <meta charset="utf-8">
1514
+ <title>{html.escape(title)}</title>
1515
+ <style>
1516
+ body {{ font-family: sans-serif; font-size: 11pt; line-height: 1.5; color: #333; }}
1517
+ h1 {{ font-size: 18pt; margin-bottom: 5px; }}
1518
+ .meta {{ font-size: 9pt; color: #666; margin-bottom: 20px; }}
1519
+ h2 {{ font-size: 14pt; margin-top: 15px; margin-bottom: 5px; }}
1520
+ h3 {{ font-size: 12.5pt; margin-top: 10px; margin-bottom: 5px; }}
1521
+ table {{ border-collapse: collapse; width: 100%; margin-bottom: 10px; }}
1522
+ th, td {{ border: 1px solid #ccc; padding: 6px; text-align: left; font-size: 10pt; }}
1523
+ pre {{ background-color: #f5f5f5; padding: 10px; font-size: 9.5pt; overflow-x: auto; }}
1524
+ code {{ font-family: monospace; background-color: #f5f5f5; padding: 2px 4px; }}
1525
+ blockquote {{ border-left: 3px solid #ccc; margin: 0; padding-left: 10px; color: #555; }}
1526
+ math {{ font-family: "Cambria Math", "Latin Modern Math", "STIX Two Math", math, serif; font-size: 1.1em; }}
1527
+ .answer-block {{ margin-bottom: 20px; }}
1528
+ </style>
1529
+ </head>
1530
+ <body>
1531
+ <h1>{html.escape(title)}</h1>
1532
+ <div class="meta">Space: {html.escape(space_id)} <br> Exported at: {exported_at}</div>
1533
+ {body_html}
1534
+ </body>
1535
+ </html>
1536
+ """
1537
+ pdf_bytes = weasyprint.HTML(string=html_content).write_pdf()
1538
+ return pdf_bytes
1539
+
1540
+ def _build_answers_pdf_bytes(title: str, items: list[dict], space_id: str) -> bytes:
1541
+ body_parts = []
1542
+ for item in items:
1543
+ q = item.get('question', '')
1544
+ a = item.get('answer', '')
1545
+
1546
+ q_math = _render_latex_to_mathml(q)
1547
+ a_math = _render_latex_to_mathml(a)
1548
+
1549
+ q_html = markdown.markdown(q_math, extensions=['tables', 'fenced_code'])
1550
+ a_html = markdown.markdown(a_math, extensions=['tables', 'fenced_code'])
1551
+
1552
+ body_parts.append(f"<div class='answer-block'><h2>Question: {q_html}</h2><div class='answer'>{a_html}</div></div><hr>")
1553
+
1554
+ return _render_html_page(title, "".join(body_parts), space_id)
1555
+
1556
+ def _safe_pdf_filename(name: str) -> str:
1557
+ base = (name or 'notebookpro_export').strip().replace(' ', '_')
1558
+ base = re.sub(r'[^A-Za-z0-9_\-]', '', base)
1559
+ if not base:
1560
+ base = 'notebookpro_export'
1561
+ return f"{base}.pdf"
1562
+
1563
+
1564
+ def _apply_inline_format(text: str, attrs: dict) -> str:
1565
+ if not text: return text
1566
+
1567
+ # Preserve leading/trailing whitespace
1568
+ l_space = len(text) - len(text.lstrip(' \t\n'))
1569
+ r_space = len(text) - len(text.rstrip(' \t\n'))
1570
+
1571
+ inner = text.strip(' \t\n')
1572
+ if not inner: return text # If it's all spaces, don't wrap it
1573
+
1574
+ if attrs.get('bold'): inner = f"**{inner}**"
1575
+ if attrs.get('italic'): inner = f"*{inner}*"
1576
+ if attrs.get('strike'): inner = f"~~{inner}~~"
1577
+ if attrs.get('code'): inner = f"`{inner}`"
1578
+ if attrs.get('link'): inner = f"[{inner}]({attrs.get('link')})"
1579
+
1580
+ return text[:l_space] + inner + text[len(text)-r_space:] if r_space > 0 else text[:l_space] + inner
1581
+
1582
+ def _quill_or_plain_to_text(content: str) -> str:
1583
+ """Convert plain text or Quill delta JSON string into Markdown text."""
1584
+ if not content:
1585
+ return ""
1586
+
1587
+ stripped = content.strip()
1588
+ if not stripped:
1589
+ return ""
1590
+
1591
+ try:
1592
+ parsed = json.loads(stripped)
1593
+ ops = []
1594
+ if isinstance(parsed, dict) and isinstance(parsed.get('ops'), list):
1595
+ ops = parsed.get('ops', [])
1596
+ elif isinstance(parsed, list):
1597
+ ops = parsed
1598
+ else:
1599
+ return stripped
1600
+
1601
+ lines = []
1602
+ current_line_ops = []
1603
+
1604
+ for op in ops:
1605
+ if not isinstance(op, dict):
1606
+ continue
1607
+
1608
+ insert_value = op.get('insert')
1609
+ if not isinstance(insert_value, str):
1610
+ continue
1611
+
1612
+ attrs = op.get('attributes', {})
1613
+ parts = insert_value.split('\n')
1614
+
1615
+ for i, part in enumerate(parts):
1616
+ if i > 0:
1617
+ line_md = ""
1618
+ for l_op, l_attrs in current_line_ops:
1619
+ line_md += _apply_inline_format(l_op, l_attrs)
1620
+
1621
+ if attrs.get('header') == 1: line_md = f"# {line_md}"
1622
+ elif attrs.get('header') == 2: line_md = f"## {line_md}"
1623
+ elif attrs.get('header') == 3: line_md = f"### {line_md}"
1624
+ elif attrs.get('header') == 4: line_md = f"#### {line_md}"
1625
+ elif attrs.get('blockquote'): line_md = f"> {line_md}"
1626
+ elif attrs.get('code-block'): line_md = f"```\n{line_md}\n```"
1627
+ elif attrs.get('list') == 'bullet': line_md = f"* {line_md}"
1628
+ elif attrs.get('list') == 'ordered': line_md = f"1. {line_md}"
1629
+
1630
+ lines.append(line_md)
1631
+ current_line_ops = []
1632
+
1633
+ if part:
1634
+ current_line_ops.append((part, attrs))
1635
+
1636
+ if current_line_ops:
1637
+ line_md = ""
1638
+ for l_op, l_attrs in current_line_ops:
1639
+ line_md += _apply_inline_format(l_op, l_attrs)
1640
+ lines.append(line_md)
1641
+
1642
+ text = '\n'.join(lines)
1643
+ text = re.sub(r'\n{3,}', '\n\n', text)
1644
+ return text.strip()
1645
+ except Exception:
1646
+ return stripped
1647
+
1648
+
1649
+ def _extract_chat_qa(text: str) -> Optional[Dict[str, str]]:
1650
+ """Extract chat-style Q/A blocks from plain text."""
1651
+ if not text:
1652
+ return None
1653
+
1654
+ match = re.match(r'^\s*Q:\s*(.*?)\s*\n\s*\n\s*A:\s*(.*)$', text, flags=re.DOTALL | re.IGNORECASE)
1655
+ if not match:
1656
+ return None
1657
+
1658
+ question = (match.group(1) or '').strip()
1659
+ answer = (match.group(2) or '').strip()
1660
+ if not question or not answer:
1661
+ return None
1662
+ return {'question': question, 'answer': answer}
1663
+
1664
+
1665
+ def _normalize_compare_text(value: str) -> str:
1666
+ v = (value or '').lower().strip()
1667
+ v = v.replace('...', ' ')
1668
+ v = re.sub(r'[^a-z0-9\s]', ' ', v)
1669
+ v = re.sub(r'\s+', ' ', v).strip()
1670
+ return v
1671
+
1672
+
1673
+ def _is_same_question_title(title: str, question: str) -> bool:
1674
+ """Fuzzy equality to match truncated titles with full questions."""
1675
+ t = _normalize_compare_text(title)
1676
+ q = _normalize_compare_text(question)
1677
+ if not t or not q:
1678
+ return False
1679
+
1680
+ if t == q:
1681
+ return True
1682
+
1683
+ # Prefix checks for truncated titles.
1684
+ if len(t) >= 18 and q.startswith(t):
1685
+ return True
1686
+ if len(q) >= 18 and t.startswith(q):
1687
+ return True
1688
+
1689
+ # Token-prefix overlap check (first several tokens usually define the question).
1690
+ t_tokens = t.split()
1691
+ q_tokens = q.split()
1692
+ common = min(len(t_tokens), len(q_tokens), 8)
1693
+ if common >= 4 and t_tokens[:common] == q_tokens[:common]:
1694
+ return True
1695
+
1696
+ return False
1697
+
1698
+
1699
+ def _normalize_chat_entry_body(entry: NotebookEntry, body_text: str) -> str:
1700
+ """For chat entries, avoid repeating question in body when title already carries it."""
1701
+ qa = _extract_chat_qa(body_text)
1702
+ if not qa:
1703
+ return body_text
1704
+
1705
+ title = (entry.title or '').strip()
1706
+ question = qa['question'].strip()
1707
+
1708
+ if not title:
1709
+ return f"Question: {qa['question']}\n\nAnswer: {qa['answer']}"
1710
+
1711
+ # If title and question are effectively the same, keep only the answer body.
1712
+ if _is_same_question_title(title, question):
1713
+ return qa['answer']
1714
+
1715
+ return f"Question: {qa['question']}\n\nAnswer: {qa['answer']}"
1716
+
1717
+
1718
+ def _build_notebook_entries_pdf_bytes(title: str, entries: list, space_id: str) -> bytes:
1719
+ body_parts = []
1720
+ for idx, entry in enumerate(entries, 1):
1721
+ body_text = _quill_or_plain_to_text(entry.content)
1722
+ entry_title = entry.title or f"Note {idx}"
1723
+
1724
+ if entry.source_type == 'chat':
1725
+ qa = _extract_chat_qa(body_text)
1726
+ if qa and qa.get('question'):
1727
+ entry_title = qa['question']
1728
+ body_text = _normalize_chat_entry_body(entry, body_text)
1729
+
1730
+ updated = entry.updated_at.strftime('%Y-%m-%d %H:%M') if entry.updated_at else ''
1731
+
1732
+ body_text = _render_latex_to_mathml(body_text)
1733
+ body_html = markdown.markdown(body_text, extensions=['tables', 'fenced_code'])
1734
+
1735
+ updated_str = f"<div class='meta'>Updated: {updated}</div>" if updated else ""
1736
+ body_parts.append(f"<div class='answer-block'><h2>{idx}. {html.escape(entry_title)}</h2>{updated_str}<div>{body_html}</div></div><hr>")
1737
+
1738
+ return _render_html_page(title, "".join(body_parts), space_id)
1739
+
1740
+
1741
+ @app.post("/api/studio/notebook", response_model=NotebookEntry)
1742
+ async def create_notebook_entry(entry_data: NotebookEntryCreate):
1743
+ """Create a new notebook entry"""
1744
+ try:
1745
+ entry = studio_manager.create_notebook_entry(entry_data)
1746
+ return entry
1747
+ except Exception as e:
1748
+ raise HTTPException(status_code=500, detail=str(e))
1749
+
1750
+ @app.get("/api/studio/notebook/space/{space_id}")
1751
+ async def get_space_notebook(space_id: str):
1752
+ """Get or create notebook metadata for a space."""
1753
+ try:
1754
+ space = spaces_manager.get_space(space_id)
1755
+ space_name = space['name'] if space else space_id
1756
+ notebook = studio_manager.ensure_space_notebook(space_id, space_name)
1757
+ return notebook
1758
+ except Exception as e:
1759
+ raise HTTPException(status_code=500, detail=str(e))
1760
+
1761
+ @app.post("/api/studio/notebook/from-chat", response_model=NotebookEntry)
1762
+ async def add_chat_to_notebook(request: ChatToNotebookRequest):
1763
+ """Add a chat question/answer pair into a space notebook."""
1764
+ try:
1765
+ space = spaces_manager.get_space(request.space_id)
1766
+ resolved_space_name = request.space_name or (space['name'] if space else request.space_id)
1767
+
1768
+ entry = studio_manager.create_notebook_entry_from_chat(
1769
+ space_id=request.space_id,
1770
+ question=request.question,
1771
+ answer=request.answer,
1772
+ chat_id=request.chat_id,
1773
+ assistant_timestamp=request.assistant_timestamp,
1774
+ tags=request.tags,
1775
+ space_name=resolved_space_name
1776
+ )
1777
+ return entry
1778
+ except Exception as e:
1779
+ raise HTTPException(status_code=500, detail=str(e))
1780
+
1781
+ @app.get("/api/studio/notebook", response_model=List[NotebookEntry])
1782
+ async def list_notebook_entries(space_id: Optional[str] = None):
1783
+ """List all notebook entries, optionally filtered by space"""
1784
+ try:
1785
+ entries = studio_manager.list_notebook_entries(space_id)
1786
+ return entries
1787
+ except Exception as e:
1788
+ raise HTTPException(status_code=500, detail=str(e))
1789
+
1790
+ @app.get("/api/studio/notebook/{entry_id}", response_model=NotebookEntry)
1791
+ async def get_notebook_entry(entry_id: str):
1792
+ """Get a single notebook entry"""
1793
+ entry = studio_manager.get_notebook_entry(entry_id)
1794
+ if not entry:
1795
+ raise HTTPException(status_code=404, detail="Notebook entry not found")
1796
+ return entry
1797
+
1798
+ @app.put("/api/studio/notebook/{entry_id}", response_model=NotebookEntry)
1799
+ async def update_notebook_entry(entry_id: str, update_data: NotebookEntryUpdate):
1800
+ """Update a notebook entry"""
1801
+ entry = studio_manager.update_notebook_entry(entry_id, update_data)
1802
+ if not entry:
1803
+ raise HTTPException(status_code=404, detail="Notebook entry not found")
1804
+ return entry
1805
+
1806
+ @app.delete("/api/studio/notebook/{entry_id}")
1807
+ async def delete_notebook_entry(entry_id: str):
1808
+ """Delete a notebook entry"""
1809
+ success = studio_manager.delete_notebook_entry(entry_id)
1810
+ if not success:
1811
+ raise HTTPException(status_code=404, detail="Notebook entry not found")
1812
+ return {"status": "success", "message": "Notebook entry deleted"}
1813
+
1814
+
1815
+ @app.post("/api/studio/notebook/export/answer-pdf")
1816
+ async def export_single_answer_pdf(request: ExportAnswerPdfRequest):
1817
+ """Export one Q/A pair as a downloadable PDF."""
1818
+ try:
1819
+ title = request.title or "NotebookPRO Answer Export"
1820
+ pdf_bytes = _build_answers_pdf_bytes(
1821
+ title=title,
1822
+ space_id=request.space_id,
1823
+ items=[{"question": request.question, "answer": request.answer}],
1824
+ )
1825
+ filename = _safe_pdf_filename(title)
1826
+ return Response(
1827
+ content=pdf_bytes,
1828
+ media_type="application/pdf",
1829
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
1830
+ )
1831
+ except Exception as e:
1832
+ raise HTTPException(status_code=500, detail=f"Failed to export answer PDF: {e}")
1833
+
1834
+
1835
+ @app.post("/api/studio/notebook/export/combined-pdf")
1836
+ async def export_combined_answers_pdf(request: ExportCombinedAnswersPdfRequest):
1837
+ """Export all provided Q/A pairs as one combined downloadable PDF."""
1838
+ try:
1839
+ if not request.items:
1840
+ raise HTTPException(status_code=400, detail="No answers provided for export")
1841
+
1842
+ title = request.chat_title or "NotebookPRO Combined Answers"
1843
+ pdf_bytes = _build_answers_pdf_bytes(
1844
+ title=title,
1845
+ space_id=request.space_id,
1846
+ items=[{"question": i.question, "answer": i.answer} for i in request.items],
1847
+ )
1848
+ filename = _safe_pdf_filename(title)
1849
+ return Response(
1850
+ content=pdf_bytes,
1851
+ media_type="application/pdf",
1852
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
1853
+ )
1854
+ except HTTPException:
1855
+ raise
1856
+ except Exception as e:
1857
+ raise HTTPException(status_code=500, detail=f"Failed to export combined PDF: {e}")
1858
+
1859
+
1860
+ @app.get("/api/studio/notebook/export/entry/{entry_id}/pdf")
1861
+ async def export_notebook_entry_pdf(entry_id: str):
1862
+ """Export one notebook entry as a downloadable PDF."""
1863
+ try:
1864
+ entry = studio_manager.get_notebook_entry(entry_id)
1865
+ if not entry:
1866
+ raise HTTPException(status_code=404, detail="Notebook entry not found")
1867
+
1868
+ title = f"Notebook Entry - {entry.title}"
1869
+ pdf_bytes = _build_notebook_entries_pdf_bytes(title, [entry], entry.space_id)
1870
+ filename = _safe_pdf_filename(entry.title or f"entry_{entry.id}")
1871
+ return Response(
1872
+ content=pdf_bytes,
1873
+ media_type="application/pdf",
1874
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
1875
+ )
1876
+ except HTTPException:
1877
+ raise
1878
+ except Exception as e:
1879
+ raise HTTPException(status_code=500, detail=f"Failed to export notebook entry PDF: {e}")
1880
+
1881
+
1882
+ @app.get("/api/studio/notebook/export/space/{space_id}/combined-pdf")
1883
+ async def export_space_notebook_pdf(space_id: str):
1884
+ """Export all notebook entries for a space as a single PDF."""
1885
+ try:
1886
+ entries = studio_manager.list_notebook_entries(space_id=space_id)
1887
+ if not entries:
1888
+ raise HTTPException(status_code=404, detail="No notebook entries found for this space")
1889
+
1890
+ space = spaces_manager.get_space(space_id)
1891
+ space_name = space['name'] if space else space_id
1892
+ title = f"Notebook - {space_name}"
1893
+ pdf_bytes = _build_notebook_entries_pdf_bytes(title, entries, space_id)
1894
+ filename = _safe_pdf_filename(f"{space_name}_notebook")
1895
+ return Response(
1896
+ content=pdf_bytes,
1897
+ media_type="application/pdf",
1898
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
1899
+ )
1900
+ except HTTPException:
1901
+ raise
1902
+ except Exception as e:
1903
+ raise HTTPException(status_code=500, detail=f"Failed to export space notebook PDF: {e}")
1904
+
1905
+
1906
+ @app.post("/api/studio/notebook/export/selected-pdf")
1907
+ async def export_selected_notebook_pdf(request: ExportSelectedNotebookPdfRequest):
1908
+ """Export selected notebook entries for a space as a single combined PDF."""
1909
+ try:
1910
+ if not request.entry_ids:
1911
+ raise HTTPException(status_code=400, detail="No notebook entries selected for export")
1912
+
1913
+ entries = []
1914
+ for entry_id in request.entry_ids:
1915
+ entry = studio_manager.get_notebook_entry(entry_id)
1916
+ if not entry:
1917
+ raise HTTPException(status_code=404, detail=f"Notebook entry not found: {entry_id}")
1918
+ if entry.space_id != request.space_id:
1919
+ raise HTTPException(
1920
+ status_code=400,
1921
+ detail=f"Notebook entry does not belong to this space: {entry_id}",
1922
+ )
1923
+ entries.append(entry)
1924
+
1925
+ if not entries:
1926
+ raise HTTPException(status_code=404, detail="No notebook entries found for export")
1927
+
1928
+ space = spaces_manager.get_space(request.space_id)
1929
+ space_name = space['name'] if space else request.space_id
1930
+ title = request.title or f"Notebook Selection - {space_name}"
1931
+ pdf_bytes = _build_notebook_entries_pdf_bytes(title, entries, request.space_id)
1932
+ filename = _safe_pdf_filename(f"{space_name}_notebook_selected")
1933
+
1934
+ return Response(
1935
+ content=pdf_bytes,
1936
+ media_type="application/pdf",
1937
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
1938
+ )
1939
+ except HTTPException:
1940
+ raise
1941
+ except Exception as e:
1942
+ raise HTTPException(status_code=500, detail=f"Failed to export selected notebook PDF: {e}")
1943
+
1944
+
1945
+ # ===== FLASHCARD ROUTES =====
1946
+
1947
+ @app.post("/api/studio/flashcards", response_model=Flashcard)
1948
+ async def create_flashcard(card_data: FlashcardCreate):
1949
+ """Create a new flashcard"""
1950
+ try:
1951
+ card = studio_manager.create_flashcard(card_data)
1952
+ return card
1953
+ except Exception as e:
1954
+ raise HTTPException(status_code=500, detail=str(e))
1955
+
1956
+ @app.get("/api/studio/flashcards", response_model=List[Flashcard])
1957
+ async def list_flashcards(
1958
+ space_id: Optional[str] = None,
1959
+ mastery: Optional[MasteryLevel] = None
1960
+ ):
1961
+ """List all flashcards, optionally filtered"""
1962
+ try:
1963
+ cards = studio_manager.list_flashcards(space_id, mastery)
1964
+ return cards
1965
+ except Exception as e:
1966
+ raise HTTPException(status_code=500, detail=str(e))
1967
+
1968
+ @app.get("/api/studio/flashcards/{card_id}", response_model=Flashcard)
1969
+ async def get_flashcard(card_id: str):
1970
+ """Get a single flashcard"""
1971
+ card = studio_manager.get_flashcard(card_id)
1972
+ if not card:
1973
+ raise HTTPException(status_code=404, detail="Flashcard not found")
1974
+ return card
1975
+
1976
+ @app.put("/api/studio/flashcards/{card_id}", response_model=Flashcard)
1977
+ async def update_flashcard(card_id: str, update_data: FlashcardUpdate):
1978
+ """Update a flashcard"""
1979
+ card = studio_manager.update_flashcard(card_id, update_data)
1980
+ if not card:
1981
+ raise HTTPException(status_code=404, detail="Flashcard not found")
1982
+ return card
1983
+
1984
+ @app.post("/api/studio/flashcards/{card_id}/review", response_model=Flashcard)
1985
+ async def review_flashcard(card_id: str, review: FlashcardReview):
1986
+ """Record a flashcard review"""
1987
+ card = studio_manager.review_flashcard(card_id, review)
1988
+ if not card:
1989
+ raise HTTPException(status_code=404, detail="Flashcard not found")
1990
+ return card
1991
+
1992
+ @app.delete("/api/studio/flashcards/{card_id}")
1993
+ async def delete_flashcard(card_id: str):
1994
+ """Delete a flashcard"""
1995
+ success = studio_manager.delete_flashcard(card_id)
1996
+ if not success:
1997
+ raise HTTPException(status_code=404, detail="Flashcard not found")
1998
+ return {"status": "success", "message": "Flashcard deleted"}
1999
+
2000
+ @app.post("/api/studio/flashcards/generate", response_model=List[Flashcard])
2001
+ async def generate_flashcards(request: FlashcardGenerateRequest):
2002
+ """Generate flashcards from content using LLM"""
2003
+ global studio_generator
2004
+
2005
+ if not studio_generator:
2006
+ raise HTTPException(status_code=503, detail="LLM not initialized")
2007
+
2008
+ try:
2009
+ cards = await studio_generator.generate_flashcards(request)
2010
+ return cards
2011
+ except Exception as e:
2012
+ raise HTTPException(status_code=500, detail=str(e))
2013
+
2014
+
2015
+ # ===== QUIZ ROUTES =====
2016
+
2017
+ @app.post("/api/studio/quizzes", response_model=Quiz)
2018
+ async def create_quiz(quiz_data: QuizCreate):
2019
+ """Create a new quiz"""
2020
+ try:
2021
+ quiz = studio_manager.create_quiz(quiz_data)
2022
+ return quiz
2023
+ except Exception as e:
2024
+ raise HTTPException(status_code=500, detail=str(e))
2025
+
2026
+ @app.get("/api/studio/quizzes", response_model=List[Quiz])
2027
+ async def list_quizzes(space_id: Optional[str] = None):
2028
+ """List all quizzes, optionally filtered by space"""
2029
+ try:
2030
+ quizzes = studio_manager.list_quizzes(space_id)
2031
+ return quizzes
2032
+ except Exception as e:
2033
+ raise HTTPException(status_code=500, detail=str(e))
2034
+
2035
+ @app.get("/api/studio/quizzes/{quiz_id}", response_model=Quiz)
2036
+ async def get_quiz(quiz_id: str):
2037
+ """Get a quiz by ID"""
2038
+ quiz = studio_manager.get_quiz(quiz_id)
2039
+ if not quiz:
2040
+ raise HTTPException(status_code=404, detail="Quiz not found")
2041
+ return quiz
2042
+
2043
+ @app.delete("/api/studio/quizzes/{quiz_id}")
2044
+ async def delete_quiz(quiz_id: str):
2045
+ """Delete a quiz"""
2046
+ success = studio_manager.delete_quiz(quiz_id)
2047
+ if not success:
2048
+ raise HTTPException(status_code=404, detail="Quiz not found")
2049
+ return {"status": "success", "message": "Quiz deleted"}
2050
+
2051
+ @app.post("/api/studio/quizzes/generate", response_model=Quiz)
2052
+ async def generate_quiz(request: QuizGenerateRequest):
2053
+ """Generate a quiz from content using LLM"""
2054
+ global studio_generator
2055
+
2056
+ if not studio_generator:
2057
+ raise HTTPException(status_code=503, detail="LLM not initialized")
2058
+
2059
+ try:
2060
+ quiz = await studio_generator.generate_quiz(request)
2061
+ if not quiz:
2062
+ raise HTTPException(status_code=500, detail="Failed to generate quiz")
2063
+ return quiz
2064
+ except Exception as e:
2065
+ raise HTTPException(status_code=500, detail=str(e))
2066
+
2067
+ @app.post("/api/studio/quizzes/{quiz_id}/submit", response_model=QuizResult)
2068
+ async def submit_quiz(quiz_id: str, submission: QuizSubmission):
2069
+ """Submit quiz answers and get results"""
2070
+ try:
2071
+ result = studio_manager.submit_quiz(quiz_id, submission.answers)
2072
+ if not result:
2073
+ raise HTTPException(status_code=404, detail="Quiz not found")
2074
+ return result
2075
+ except Exception as e:
2076
+ raise HTTPException(status_code=500, detail=str(e))
2077
+
2078
+ @app.get("/api/studio/quizzes/{quiz_id}/history", response_model=QuizHistory)
2079
+ async def get_quiz_history(quiz_id: str):
2080
+ """Get quiz attempt history"""
2081
+ try:
2082
+ history = studio_manager.get_quiz_history(quiz_id)
2083
+ if not history:
2084
+ raise HTTPException(status_code=404, detail="Quiz not found")
2085
+ return history
2086
+ except Exception as e:
2087
+ raise HTTPException(status_code=500, detail=str(e))
2088
+
2089
+
2090
+ raise HTTPException(status_code=500, detail=f"Error deleting file: {str(e)}")
2091
+
2092
+ # ==================== Run Server ====================
2093
+
2094
+ if __name__ == "__main__":
2095
+ import uvicorn
2096
+ uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
2097
+
models/studio_models.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Studio Models - Notebook, Flashcards, Quiz
3
+ These models represent the core Studio features for NotebookPRO
4
+ """
5
+ from pydantic import BaseModel, Field
6
+ from typing import List, Optional, Dict, Any
7
+ from datetime import datetime
8
+ from enum import Enum
9
+
10
+
11
+ # ============================================================================
12
+ # NOTEBOOK MODELS
13
+ # ============================================================================
14
+
15
+ class NotebookEntry(BaseModel):
16
+ """A single note entry in the notebook"""
17
+ id: str = Field(..., description="Unique identifier for the note")
18
+ space_id: str = Field(..., description="Space this note belongs to")
19
+ title: str = Field(..., description="Title of the note")
20
+ content: str = Field(..., description="Main content/body of the note")
21
+ source_type: str = Field(default="manual", description="Source: manual, chat, generated")
22
+ source_id: Optional[str] = Field(None, description="ID of source (e.g., chat message ID)")
23
+ tags: List[str] = Field(default_factory=list, description="Tags for categorization")
24
+ created_at: datetime = Field(default_factory=datetime.now)
25
+ updated_at: datetime = Field(default_factory=datetime.now)
26
+ metadata: Dict[str, Any] = Field(default_factory=dict)
27
+
28
+
29
+ class NotebookEntryCreate(BaseModel):
30
+ """Request model for creating a notebook entry"""
31
+ space_id: str
32
+ title: str
33
+ content: str
34
+ source_type: str = "manual"
35
+ source_id: Optional[str] = None
36
+ tags: List[str] = []
37
+ metadata: Dict[str, Any] = {}
38
+
39
+
40
+ class NotebookEntryUpdate(BaseModel):
41
+ """Request model for updating a notebook entry"""
42
+ title: Optional[str] = None
43
+ content: Optional[str] = None
44
+ tags: Optional[List[str]] = None
45
+ metadata: Optional[Dict[str, Any]] = None
46
+
47
+
48
+ # ============================================================================
49
+ # FLASHCARD MODELS
50
+ # ============================================================================
51
+
52
+ class DifficultyLevel(str, Enum):
53
+ """Difficulty level for flashcards"""
54
+ EASY = "easy"
55
+ MEDIUM = "medium"
56
+ HARD = "hard"
57
+
58
+
59
+ class MasteryLevel(str, Enum):
60
+ """User's mastery level for a flashcard"""
61
+ NEW = "new"
62
+ LEARNING = "learning"
63
+ REVIEWING = "reviewing"
64
+ MASTERED = "mastered"
65
+
66
+
67
+ class Flashcard(BaseModel):
68
+ """A single flashcard for memorization"""
69
+ id: str = Field(..., description="Unique identifier")
70
+ space_id: str = Field(..., description="Space this flashcard belongs to")
71
+ question: str = Field(..., description="Front of the card (question/prompt)")
72
+ answer: str = Field(..., description="Back of the card (answer/explanation)")
73
+ difficulty: DifficultyLevel = Field(default=DifficultyLevel.MEDIUM)
74
+ topic: Optional[str] = Field(None, description="Topic matching the concept covered")
75
+ mastery: MasteryLevel = Field(default=MasteryLevel.NEW)
76
+ source_type: str = Field(default="manual", description="Source: manual, generated, notebook")
77
+ source_id: Optional[str] = Field(None, description="Source ID (e.g., notebook entry ID)")
78
+ tags: List[str] = Field(default_factory=list)
79
+ review_count: int = Field(default=0, description="Number of times reviewed")
80
+ correct_count: int = Field(default=0, description="Number of times answered correctly")
81
+
82
+ # SM-2 Spaced Repetition Fields
83
+ interval: int = Field(default=0, description="Interval in days before next review")
84
+ repetitions: int = Field(default=0, description="Number of successful consecutive reviews")
85
+ ease_factor: float = Field(default=2.5, description="SM-2 Ease factor")
86
+
87
+ last_reviewed: Optional[datetime] = None
88
+ next_review: Optional[datetime] = None
89
+ created_at: datetime = Field(default_factory=datetime.now)
90
+ metadata: Dict[str, Any] = Field(default_factory=dict)
91
+
92
+
93
+ class FlashcardCreate(BaseModel):
94
+ """Request model for creating a flashcard"""
95
+ space_id: str
96
+ question: str
97
+ answer: str
98
+ difficulty: DifficultyLevel = DifficultyLevel.MEDIUM
99
+ source_type: str = "manual"
100
+ source_id: Optional[str] = None
101
+ tags: List[str] = []
102
+ metadata: Dict[str, Any] = {}
103
+
104
+
105
+ class FlashcardUpdate(BaseModel):
106
+ """Request model for updating a flashcard"""
107
+ question: Optional[str] = None
108
+ answer: Optional[str] = None
109
+ difficulty: Optional[DifficultyLevel] = None
110
+ mastery: Optional[MasteryLevel] = None
111
+ tags: Optional[List[str]] = None
112
+
113
+
114
+ class FlashcardReview(BaseModel):
115
+ """Request model for reviewing a flashcard"""
116
+ quality: int = Field(..., description="0-5 score user gives after seeing answer (0-2 = forgot, 3 = hard, 4 = good, 5 = easy)")
117
+
118
+
119
+ class FlashcardGenerateRequest(BaseModel):
120
+ """Request to generate flashcards from content"""
121
+ space_id: str
122
+ source_type: str = Field(..., description="Source type: notebook, file, text")
123
+ source_ids: Optional[List[str]] = Field(None, description="IDs of notebook entries or files")
124
+ text_content: Optional[str] = Field(None, description="Direct text content to generate from")
125
+ num_cards: int = Field(default=5, description="Number of flashcards to generate")
126
+ difficulty: DifficultyLevel = DifficultyLevel.MEDIUM
127
+
128
+
129
+ # ============================================================================
130
+ # QUIZ MODELS
131
+ # ============================================================================
132
+
133
+ class QuestionType(str, Enum):
134
+ """Type of quiz question"""
135
+ MULTIPLE_CHOICE = "multiple_choice"
136
+ TRUE_FALSE = "true_false"
137
+ SHORT_ANSWER = "short_answer"
138
+
139
+
140
+ class QuizQuestion(BaseModel):
141
+ """A single quiz question"""
142
+ id: str = Field(..., description="Unique identifier")
143
+ question: str = Field(..., description="Question text")
144
+ type: QuestionType = Field(..., description="Question type")
145
+ options: Optional[List[str]] = Field(None, description="Options for multiple choice")
146
+ correct_answer: str = Field(..., description="Correct answer")
147
+ explanation: Optional[str] = Field(None, description="Explanation of the answer")
148
+ points: int = Field(default=1, description="Points for this question")
149
+ difficulty: DifficultyLevel = Field(default=DifficultyLevel.MEDIUM)
150
+
151
+
152
+ class Quiz(BaseModel):
153
+ """A quiz session"""
154
+ id: str = Field(..., description="Unique identifier")
155
+ space_id: str = Field(..., description="Space this quiz belongs to")
156
+ title: str = Field(..., description="Quiz title")
157
+ description: Optional[str] = None
158
+ questions: List[QuizQuestion] = Field(..., description="List of questions")
159
+ source_type: str = Field(default="manual", description="Source: manual, generated, notebook, file")
160
+ source_ids: Optional[List[str]] = None
161
+ created_at: datetime = Field(default_factory=datetime.now)
162
+ metadata: Dict[str, Any] = Field(default_factory=dict)
163
+
164
+
165
+ class QuizCreate(BaseModel):
166
+ """Request model for creating a quiz"""
167
+ space_id: str
168
+ title: str
169
+ description: Optional[str] = None
170
+ questions: List[QuizQuestion] = []
171
+ source_type: str = "manual"
172
+ source_ids: Optional[List[str]] = None
173
+
174
+
175
+ class QuizGenerateRequest(BaseModel):
176
+ """Request to generate a quiz from content"""
177
+ space_id: str
178
+ title: str
179
+ source_type: str = Field(..., description="Source type: notebook, file, text")
180
+ source_ids: Optional[List[str]] = Field(None, description="IDs of notebook entries or files")
181
+ text_content: Optional[str] = Field(None, description="Direct text content")
182
+ num_questions: int = Field(default=5, description="Number of questions")
183
+ question_types: List[QuestionType] = Field(
184
+ default=[QuestionType.MULTIPLE_CHOICE],
185
+ description="Types of questions to include"
186
+ )
187
+ difficulty: DifficultyLevel = DifficultyLevel.MEDIUM
188
+
189
+
190
+ class QuizAnswer(BaseModel):
191
+ """User's answer to a quiz question"""
192
+ question_id: str
193
+ answer: str
194
+ time_spent: Optional[int] = Field(None, description="Time spent in seconds")
195
+
196
+
197
+ class QuizSubmission(BaseModel):
198
+ """User's quiz submission"""
199
+ quiz_id: str
200
+ answers: List[QuizAnswer]
201
+
202
+
203
+ class QuizResult(BaseModel):
204
+ """Result of a quiz submission"""
205
+ quiz_id: str
206
+ submission_id: str = Field(..., description="Unique submission ID")
207
+ total_questions: int
208
+ correct_answers: int
209
+ incorrect_answers: int
210
+ score_percentage: float
211
+ total_points: int
212
+ earned_points: int
213
+ answers: List[Dict[str, Any]] = Field(..., description="Detailed answer results")
214
+ completed_at: datetime = Field(default_factory=datetime.now)
215
+ time_taken: Optional[int] = Field(None, description="Total time in seconds")
216
+
217
+
218
+ class QuizHistory(BaseModel):
219
+ """Quiz attempt history"""
220
+ quiz_id: str
221
+ space_id: str
222
+ quiz_title: str
223
+ results: List[QuizResult] = Field(default_factory=list)
224
+ best_score: float = Field(default=0.0)
225
+ average_score: float = Field(default=0.0)
226
+ attempts_count: int = Field(default=0)
requirements.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu121
2
+
3
+ # FastAPI backend runtime
4
+ fastapi==0.104.1
5
+ uvicorn[standard]==0.24.0
6
+ python-multipart==0.0.6
7
+ pydantic==1.10.13
8
+
9
+ # Environment/config
10
+ python-dotenv==1.0.0
11
+
12
+ # Vector search and retrieval
13
+ chromadb==0.3.21
14
+ sentence-transformers>=3.4.1
15
+ rank-bm25==0.2.2
16
+ numpy==1.26.4
17
+
18
+ # LLM inference/utilities used in backend scripts
19
+ torch==2.5.1+cu121
20
+ transformers>=4.45.0
21
+ openai==1.52.2
22
+ google-generativeai>=0.8.0
23
+
24
+ # File processing and export
25
+ PyPDF2==3.0.1
26
+ pdfplumber==0.10.3
27
+ python-docx==1.1.0
28
+ reportlab==4.2.2
29
+
30
+ ziamath
31
+ ziafont
32
+ weasyprint
33
+ markdown
runtime.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.11.0
utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Utility modules for document processing and vector database operations."""
utils/chat_manager.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chat management utilities for NotebookPRO.
3
+ """
4
+
5
+ import json
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import List, Dict, Optional
9
+ import config
10
+
11
+
12
+ class ChatManager:
13
+ """Manage chat sessions and history."""
14
+
15
+ def __init__(self):
16
+ self.chats_dir = config.CHATS_DIR
17
+ self.chats_dir.mkdir(parents=True, exist_ok=True)
18
+
19
+ def save_chat(self, chat_id: str, messages: List[Dict], space: Optional[str] = None) -> None:
20
+ """
21
+ Save a chat session.
22
+
23
+ Args:
24
+ chat_id: Unique chat identifier
25
+ messages: List of message dictionaries
26
+ space: Optional space/subject name
27
+ """
28
+ chat_data = {
29
+ 'id': chat_id,
30
+ 'messages': messages,
31
+ 'space': space,
32
+ 'created_at': datetime.now().isoformat(),
33
+ 'updated_at': datetime.now().isoformat()
34
+ }
35
+
36
+ chat_file = self.chats_dir / f"{chat_id}.json"
37
+ with open(chat_file, 'w', encoding='utf-8') as f:
38
+ json.dump(chat_data, f, indent=2, ensure_ascii=False)
39
+
40
+ def load_chat(self, chat_id: str) -> Optional[Dict]:
41
+ """
42
+ Load a chat session.
43
+
44
+ Args:
45
+ chat_id: Unique chat identifier
46
+
47
+ Returns:
48
+ Chat data dictionary or None if not found
49
+ """
50
+ chat_file = self.chats_dir / f"{chat_id}.json"
51
+
52
+ if not chat_file.exists():
53
+ return None
54
+
55
+ with open(chat_file, 'r', encoding='utf-8') as f:
56
+ return json.load(f)
57
+
58
+ def list_chats(self, space: Optional[str] = None) -> List[Dict]:
59
+ """
60
+ List all chats, optionally filtered by space.
61
+
62
+ Args:
63
+ space: Optional space filter
64
+
65
+ Returns:
66
+ List of chat metadata dictionaries
67
+ """
68
+ chats = []
69
+
70
+ for chat_file in self.chats_dir.glob("*.json"):
71
+ with open(chat_file, 'r', encoding='utf-8') as f:
72
+ chat_data = json.load(f)
73
+
74
+ if space is None or chat_data.get('space') == space:
75
+ chats.append({
76
+ 'id': chat_data['id'],
77
+ 'space': chat_data.get('space'),
78
+ 'message_count': len(chat_data['messages']),
79
+ 'created_at': chat_data.get('created_at'),
80
+ 'updated_at': chat_data.get('updated_at')
81
+ })
82
+
83
+ # Sort by updated time (most recent first)
84
+ chats.sort(key=lambda x: x.get('updated_at', ''), reverse=True)
85
+
86
+ return chats
87
+
88
+ def delete_chat(self, chat_id: str) -> bool:
89
+ """
90
+ Delete a chat session.
91
+
92
+ Args:
93
+ chat_id: Unique chat identifier
94
+
95
+ Returns:
96
+ True if deleted, False if not found
97
+ """
98
+ chat_file = self.chats_dir / f"{chat_id}.json"
99
+
100
+ if chat_file.exists():
101
+ chat_file.unlink()
102
+ return True
103
+
104
+ return False
105
+
106
+ def get_chat_preview(self, chat_id: str, max_messages: int = 5) -> Optional[List[Dict]]:
107
+ """
108
+ Get a preview of recent messages from a chat.
109
+
110
+ Args:
111
+ chat_id: Unique chat identifier
112
+ max_messages: Maximum number of messages to return
113
+
114
+ Returns:
115
+ List of recent messages or None if chat not found
116
+ """
117
+ chat_data = self.load_chat(chat_id)
118
+
119
+ if chat_data is None:
120
+ return None
121
+
122
+ messages = chat_data['messages']
123
+ return messages[-max_messages:] if len(messages) > max_messages else messages
utils/config_manager.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration manager for persistent settings (API keys, preferences).
3
+ """
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Dict, Optional
9
+ from dotenv import load_dotenv
10
+ import config
11
+
12
+
13
+ class ConfigManager:
14
+ """Manages persistent user configuration."""
15
+
16
+ def __init__(self):
17
+ self.config_file = config.DATA_DIR / "user_config.json"
18
+ self.config_data = self._load_config()
19
+
20
+ def _load_config(self) -> Dict:
21
+ """Load configuration from file."""
22
+ if self.config_file.exists():
23
+ try:
24
+ with open(self.config_file, 'r', encoding='utf-8') as f:
25
+ return json.load(f)
26
+ except Exception:
27
+ return self._default_config()
28
+ return self._default_config()
29
+
30
+ def _default_config(self) -> Dict:
31
+ """Default configuration."""
32
+ return {
33
+ "api_keys": {
34
+ "gemini": "",
35
+ "nvidia": "",
36
+ "groq": ""
37
+ },
38
+ "preferences": {
39
+ "llm_provider": "gemini",
40
+ "temperature": 0.7,
41
+ "workflow": "Auto-Detect"
42
+ },
43
+ "current_space": "General"
44
+ }
45
+
46
+ def save_config(self):
47
+ """Save configuration to file."""
48
+ try:
49
+ with open(self.config_file, 'w', encoding='utf-8') as f:
50
+ json.dump(self.config_data, f, indent=2)
51
+ except Exception as e:
52
+ print(f"Error saving config: {e}")
53
+
54
+ def get_api_key(self, provider: str) -> str:
55
+ """Get API key for provider."""
56
+ stored_key = self.config_data.get("api_keys", {}).get(provider, "")
57
+ if stored_key:
58
+ return stored_key
59
+
60
+ # Fallback to environment variables so users can configure keys in .env.
61
+ # Reloading keeps behavior predictable after .env edits.
62
+ for env_file in [config.PROJECT_ROOT / ".env", config.PROJECT_ROOT.parent / ".env"]:
63
+ if env_file.exists():
64
+ load_dotenv(env_file, override=False)
65
+
66
+ env_var_map = {
67
+ "nvidia": "NVIDIA_API_KEY",
68
+ "gemini": "GEMINI_API_KEY",
69
+ "groq": "GROQ_API_KEY",
70
+ }
71
+ env_var = env_var_map.get(provider, "")
72
+ env_value = os.getenv(env_var, "") if env_var else ""
73
+ if env_value:
74
+ return env_value
75
+
76
+ # Local development fallback: allow keeping the keys in project-root text files.
77
+ if provider == "nvidia":
78
+ key_file = config.PROJECT_ROOT.parent / "nvidia_api.txt"
79
+ if key_file.exists():
80
+ try:
81
+ key = key_file.read_text(encoding='utf-8').strip()
82
+ if key:
83
+ return key
84
+ except Exception:
85
+ pass
86
+ if provider == "gemini":
87
+ key_file = config.PROJECT_ROOT.parent / "gemini_api.txt"
88
+ if key_file.exists():
89
+ try:
90
+ key = key_file.read_text(encoding='utf-8').strip()
91
+ if key:
92
+ return key
93
+ except Exception:
94
+ pass
95
+ if provider == "groq":
96
+ key_file = config.PROJECT_ROOT.parent / "groq_api.txt"
97
+ if key_file.exists():
98
+ try:
99
+ key = key_file.read_text(encoding='utf-8').strip()
100
+ if key:
101
+ return key
102
+ except Exception:
103
+ pass
104
+
105
+ return ""
106
+
107
+ def set_api_key(self, provider: str, api_key: str):
108
+ """Save API key for provider."""
109
+ if "api_keys" not in self.config_data:
110
+ self.config_data["api_keys"] = {}
111
+ self.config_data["api_keys"][provider] = api_key
112
+ self.save_config()
113
+
114
+ def get_preference(self, key: str, default=None):
115
+ """Get user preference."""
116
+ return self.config_data.get("preferences", {}).get(key, default)
117
+
118
+ def set_preference(self, key: str, value):
119
+ """Save user preference."""
120
+ if "preferences" not in self.config_data:
121
+ self.config_data["preferences"] = {}
122
+ self.config_data["preferences"][key] = value
123
+ self.save_config()
124
+
125
+ def get_current_space(self) -> str:
126
+ """Get current workspace."""
127
+ return self.config_data.get("current_space", "General")
128
+
129
+ def set_current_space(self, space_name: str):
130
+ """Set current workspace."""
131
+ self.config_data["current_space"] = space_name
132
+ self.save_config()
utils/document_processor.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import PyPDF2
2
+ import pdfplumber
3
+ from docx import Document
4
+ from pathlib import Path
5
+ from typing import List, Dict, Optional
6
+ import re
7
+ import warnings
8
+ import logging
9
+ import os
10
+
11
+ import config
12
+
13
+ # Suppress PyPDF2 warnings about font descriptors
14
+ warnings.filterwarnings('ignore', category=UserWarning, module='PyPDF2')
15
+ logging.getLogger('PyPDF2').setLevel(logging.ERROR)
16
+
17
+
18
+ def _is_valid_year(year: str) -> bool:
19
+ """Return True for valid 4-digit publication years."""
20
+ return bool(re.fullmatch(r'(?:19|20)\d{2}', (year or '').strip()))
21
+
22
+
23
+ def extract_publication_year(front_matter_text: str) -> str:
24
+ """Extract publication year from front matter using an LLM, with safe fallback."""
25
+ text = (front_matter_text or '').strip()
26
+ if not text:
27
+ return "0000"
28
+
29
+ prompt = (
30
+ "You are a strict metadata extraction pipeline for an academic database. \n"
31
+ "Your only task is to extract the primary publication year from the provided front-matter text of an academic textbook or paper.\n"
32
+ "Instructions:\n"
33
+ "1. Scan the text for copyright dates (©), publication dates, or edition release years.\n"
34
+ "2. If multiple years are present (e.g., previous editions and a current edition), extract the most recent year.\n"
35
+ "3. If no valid year can be found, output '0000'.\n"
36
+ "4. You must output ONLY the 4-digit year. Do not include markdown, JSON formatting, or conversational text.\n"
37
+ "\n"
38
+ "Text to analyze:\n"
39
+ f"{text}"
40
+ )
41
+
42
+ # Fast deterministic regex fallback if no API key/client is available.
43
+ def _regex_fallback() -> str:
44
+ candidates = re.findall(r'(?:19|20)\d{2}', text)
45
+ if not candidates:
46
+ return "0000"
47
+ return str(max(int(c) for c in candidates))
48
+
49
+ try:
50
+ api_key = os.getenv("OPENAI_API_KEY", "") or getattr(config, "OPENAI_API_KEY", "")
51
+ if not api_key:
52
+ return _regex_fallback()
53
+
54
+ try:
55
+ from openai import OpenAI # type: ignore
56
+ except Exception:
57
+ return _regex_fallback()
58
+
59
+ model = os.getenv("OPENAI_METADATA_MODEL", "gpt-4o-mini")
60
+ client = OpenAI(api_key=api_key)
61
+
62
+ response = client.chat.completions.create(
63
+ model=model,
64
+ temperature=0,
65
+ messages=[
66
+ {"role": "user", "content": prompt},
67
+ ],
68
+ max_tokens=8,
69
+ )
70
+
71
+ raw = (response.choices[0].message.content or "").strip()
72
+ match = re.search(r'(?:19|20)\d{2}|0000', raw)
73
+ year = match.group(0) if match else "0000"
74
+ return year if _is_valid_year(year) or year == "0000" else "0000"
75
+ except Exception:
76
+ return _regex_fallback()
77
+
78
+
79
+ class DocumentProcessor:
80
+ """Process various document types and extract text content."""
81
+
82
+ def __init__(self):
83
+ self.supported_formats = ['.pdf', '.txt', '.docx']
84
+
85
+ def process_file(self, file_path: Path) -> Dict[str, any]:
86
+ """
87
+ Process a single file and extract its content.
88
+
89
+ Args:
90
+ file_path: Path to the file
91
+
92
+ Returns:
93
+ Dictionary containing file metadata and content
94
+ """
95
+ suffix = file_path.suffix.lower()
96
+ publication_year = "0000"
97
+ virtual_filename = file_path.name
98
+
99
+ if suffix == '.pdf':
100
+ content = self._extract_pdf(file_path)
101
+
102
+ # Front matter extraction for year detection.
103
+ front_matter = content[:2000]
104
+ detected_year = extract_publication_year(front_matter)
105
+ publication_year = detected_year if _is_valid_year(detected_year) else "0000"
106
+ virtual_filename = f"[{publication_year}] {file_path.name}"
107
+ elif suffix == '.txt':
108
+ content = self._extract_txt(file_path)
109
+ elif suffix == '.docx':
110
+ content = self._extract_docx(file_path)
111
+ else:
112
+ raise ValueError(f"Unsupported file format: {suffix}")
113
+
114
+ return {
115
+ 'filename': file_path.name,
116
+ 'virtual_filename': virtual_filename,
117
+ 'publication_year': publication_year,
118
+ 'path': str(file_path),
119
+ 'content': content,
120
+ 'format': suffix
121
+ }
122
+
123
+ def _extract_pdf(self, file_path: Path) -> str:
124
+ """Extract text from PDF using PyPDF2 with pdfplumber fallback."""
125
+ text = ""
126
+
127
+ # Fast-fail with a clear reason for corrupted/partial uploads.
128
+ try:
129
+ if file_path.stat().st_size == 0:
130
+ raise ValueError(f"PDF is empty (0 bytes): {file_path.name}")
131
+ except OSError:
132
+ pass
133
+
134
+ try:
135
+ # Primary: Use PyPDF2 (much faster, lower memory footprint)
136
+ with warnings.catch_warnings():
137
+ warnings.simplefilter("ignore")
138
+ with open(file_path, 'rb') as file:
139
+ pdf_reader = PyPDF2.PdfReader(file)
140
+ for page in pdf_reader.pages:
141
+ try:
142
+ page_text = page.extract_text()
143
+ if page_text:
144
+ text += page_text + "\n"
145
+ except Exception:
146
+ continue # Skip problematic pages
147
+ except Exception as e:
148
+ # Fallback: Use pdfplumber (better for complex PDFs, but slower)
149
+ text = "" # Reset text
150
+ try:
151
+ with pdfplumber.open(file_path) as pdf:
152
+ for page in pdf.pages:
153
+ page_text = page.extract_text()
154
+ if page_text:
155
+ text += page_text + "\n"
156
+ except Exception as e2:
157
+ raise ValueError(f"Could not extract text from PDF: {file_path.name}")
158
+
159
+ return self._clean_text(text)
160
+
161
+ def _extract_txt(self, file_path: Path) -> str:
162
+ """Extract text from TXT file."""
163
+ try:
164
+ with open(file_path, 'r', encoding='utf-8') as file:
165
+ text = file.read()
166
+ except UnicodeDecodeError:
167
+ with open(file_path, 'r', encoding='latin-1') as file:
168
+ text = file.read()
169
+
170
+ return self._clean_text(text)
171
+
172
+ def _extract_docx(self, file_path: Path) -> str:
173
+ """Extract text from DOCX file."""
174
+ doc = Document(file_path)
175
+ text = "\n".join([paragraph.text for paragraph in doc.paragraphs])
176
+ return self._clean_text(text)
177
+
178
+ def _clean_text(self, text: str) -> str:
179
+ """Clean and normalize text."""
180
+ # Normalize line endings first.
181
+ text = text.replace('\r\n', '\n').replace('\r', '\n')
182
+
183
+ # Keep paragraph boundaries; collapse inner spaces/tabs only.
184
+ text = re.sub(r'[ \t]+', ' ', text)
185
+
186
+ # Keep common punctuation and line breaks, strip noisy symbols.
187
+ text = re.sub(r'[^\w\s.,!?;:()\-\'\"\n/]+', '', text)
188
+
189
+ # Remove excessive blank lines but preserve section structure.
190
+ text = re.sub(r'\n{3,}', '\n\n', text)
191
+ return text.strip()
192
+
193
+ def chunk_text(
194
+ self,
195
+ text: str,
196
+ chunk_size: int = 700,
197
+ overlap: int = 120,
198
+ semantic: bool = True,
199
+ source_filename: Optional[str] = None,
200
+ ) -> List[str]:
201
+ """
202
+ Split text into chunks using recursive character chunking.
203
+ Prefixes each chunk with the document title to preserve global context.
204
+ """
205
+ try:
206
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
207
+ text_splitter = RecursiveCharacterTextSplitter(
208
+ chunk_size=chunk_size,
209
+ chunk_overlap=overlap,
210
+ separators=["\n\n", "\n", ".", "?", "!", " ", ""]
211
+ )
212
+ raw_chunks = text_splitter.split_text(text)
213
+ except ImportError:
214
+ # Fallback to simple chunking if langchain is missing
215
+ raw_chunks = self._simple_chunk(text, chunk_size, overlap)
216
+
217
+ chunks = []
218
+ prefix = f"Source Document: {source_filename}\n---\n" if source_filename else ""
219
+ for rc in raw_chunks:
220
+ chunks.append(prefix + rc.strip())
221
+
222
+ return chunks
223
+
224
+ def _simple_chunk(self, text: str, chunk_size: int = 700, overlap: int = 120) -> List[str]:
225
+ """
226
+ Split text into overlapping chunks (original method).
227
+ """
228
+ chunks = []
229
+ start = 0
230
+ text_length = len(text)
231
+
232
+ while start < text_length:
233
+ end = start + chunk_size
234
+ chunk = text[start:end]
235
+
236
+ # Try to break at sentence boundary
237
+ if end < text_length:
238
+ last_period = chunk.rfind('.')
239
+ last_newline = chunk.rfind('\n')
240
+ break_point = max(last_period, last_newline)
241
+
242
+ if break_point > chunk_size * 0.5: # At least 50% through the chunk
243
+ chunk = chunk[:break_point + 1]
244
+ end = start + break_point + 1
245
+
246
+ chunks.append(chunk.strip())
247
+ start = end - overlap
248
+
249
+ return chunks
utils/hybrid_retriever.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hybrid Retriever: Combines Vector (ChromaDB) + Keyword (BM25) search.
3
+ This is the "secret sauce" that makes NotebookLM so accurate.
4
+ """
5
+
6
+ from typing import List, Dict, Tuple
7
+ from rank_bm25 import BM25Okapi
8
+ import numpy as np
9
+ import re
10
+ import time
11
+
12
+
13
+ class HybridRetriever:
14
+ """
15
+ Combines Dense Retrieval (Embeddings) with Sparse Retrieval (BM25).
16
+
17
+ This is crucial for accuracy:
18
+ - Vector search finds conceptually similar content
19
+ - BM25 finds exact keyword matches (formulas, terms, names)
20
+ """
21
+
22
+ def __init__(self, vector_db, alpha: float = 0.5):
23
+ """
24
+ Initialize hybrid retriever.
25
+
26
+ Args:
27
+ vector_db: VectorDatabase instance
28
+ alpha: Weight balance (0=only BM25, 1=only vector, 0.5=balanced)
29
+ """
30
+ self.vector_db = vector_db
31
+ self.alpha = alpha # Weight for vector search
32
+ self.bm25 = None
33
+ self.bm25_corpus = []
34
+ self.bm25_metadata = []
35
+
36
+ def _tokenize(self, text: str) -> List[str]:
37
+ """Lightweight tokenizer for BM25."""
38
+ return re.findall(r"\w+", text.lower())
39
+
40
+ def ensure_bm25_index(self):
41
+ """Build BM25 index lazily from vector DB when needed."""
42
+ if self.bm25 is not None:
43
+ return
44
+
45
+ t0 = time.perf_counter()
46
+ print("[RETRIEVER] bm25_build_start")
47
+
48
+ documents, metadatas = self.vector_db.get_all_documents()
49
+ if not documents:
50
+ print("[RETRIEVER] bm25_build_skip empty_corpus")
51
+ return
52
+
53
+ self.index_documents(documents, metadatas)
54
+ print(
55
+ f"[RETRIEVER] bm25_build_done ms={(time.perf_counter() - t0) * 1000:.1f} "
56
+ f"docs={len(documents)}"
57
+ )
58
+
59
+ def index_documents(self, documents: List[str], metadatas: List[Dict]):
60
+ """
61
+ Index documents for BM25 keyword search.
62
+
63
+ Args:
64
+ documents: List of document chunks
65
+ metadatas: List of metadata dicts for each chunk
66
+ """
67
+ # Tokenize documents for BM25
68
+ tokenized_corpus = [self._tokenize(doc) for doc in documents]
69
+
70
+ # Create BM25 index
71
+ self.bm25 = BM25Okapi(tokenized_corpus)
72
+ self.bm25_corpus = documents
73
+ self.bm25_metadata = metadatas
74
+
75
+ def retrieve(
76
+ self,
77
+ query: str,
78
+ n_results: int = 20,
79
+ score_threshold: float = 0.0
80
+ ) -> Tuple[List[str], List[Dict], List[float]]:
81
+ """
82
+ Hybrid retrieval: combines vector + keyword search.
83
+
84
+ Args:
85
+ query: User's question
86
+ n_results: Number of chunks to retrieve
87
+ score_threshold: Minimum score threshold
88
+
89
+ Returns:
90
+ Tuple of (documents, metadatas, scores)
91
+ """
92
+ # Preferred path: dense retrieval + cross-encoder reranking in vector DB.
93
+ if hasattr(self.vector_db, 'query_and_rerank'):
94
+ try:
95
+ reranked = self.vector_db.query_and_rerank(
96
+ query_text=query,
97
+ n_retrieve=max(n_results * 2, 20),
98
+ n_final=n_results,
99
+ filter_dict=None,
100
+ )
101
+ docs = reranked.get('documents', [[]])[0]
102
+ metas = reranked.get('metadatas', [[]])[0]
103
+ scores = reranked.get('reranker_scores', [[]])[0]
104
+
105
+ if docs:
106
+ filtered = [
107
+ (d, m, float(s))
108
+ for d, m, s in zip(docs, metas, scores)
109
+ if float(s) >= score_threshold
110
+ ]
111
+ if filtered:
112
+ return (
113
+ [d for d, _, _ in filtered],
114
+ [m for _, m, _ in filtered],
115
+ [s for _, _, s in filtered],
116
+ )
117
+ except Exception as e:
118
+ print(f"[RETRIEVER] rerank_path_fallback reason={e}")
119
+
120
+ self.ensure_bm25_index()
121
+
122
+ if not self.bm25:
123
+ # Fallback to pure vector search if BM25 not initialized
124
+ results = self.vector_db.query(query, n_results=n_results * 2)
125
+ return (
126
+ results['documents'][0] if results['documents'] else [],
127
+ results['metadatas'][0] if results['metadatas'] else [],
128
+ results.get('distances', [[]])[0]
129
+ )
130
+
131
+ # Get more results than needed for reranking.
132
+ # A larger candidate pool helps with multi-book questions.
133
+ fetch_size = max(n_results * 5, 30)
134
+
135
+ # 1. Vector search (semantic similarity)
136
+ vector_results = self.vector_db.query(query, n_results=fetch_size)
137
+ vector_docs = vector_results['documents'][0] if vector_results['documents'] else []
138
+ vector_meta = vector_results['metadatas'][0] if vector_results['metadatas'] else []
139
+ vector_distances = vector_results.get('distances', [[]])[0]
140
+
141
+ # Convert distances to similarity scores (chromadb uses cosine distance)
142
+ vector_scores = [1 / (1 + d) for d in vector_distances]
143
+
144
+ # 2. BM25 search (keyword matching)
145
+ tokenized_query = self._tokenize(query)
146
+ bm25_scores = self.bm25.get_scores(tokenized_query)
147
+
148
+ # Get top BM25 results
149
+ top_bm25_indices = np.argsort(bm25_scores)[::-1][:fetch_size]
150
+
151
+ # 3. Combine results with weighted scoring
152
+ combined_docs = {} # Use dict to deduplicate by content
153
+
154
+ # Add vector results
155
+ for doc, meta, score in zip(vector_docs, vector_meta, vector_scores):
156
+ combined_docs[doc] = {
157
+ 'doc': doc,
158
+ 'meta': meta,
159
+ 'score': self.alpha * score
160
+ }
161
+
162
+ # Add BM25 results (normalize scores to 0-1 range)
163
+ max_bm25_score = max(bm25_scores) if max(bm25_scores) > 0 else 1
164
+ for idx in top_bm25_indices:
165
+ doc = self.bm25_corpus[idx]
166
+ meta = self.bm25_metadata[idx]
167
+ bm25_score = bm25_scores[idx] / max_bm25_score
168
+
169
+ if doc in combined_docs:
170
+ # Average if document found by both methods
171
+ combined_docs[doc]['score'] += (1 - self.alpha) * bm25_score
172
+ else:
173
+ combined_docs[doc] = {
174
+ 'doc': doc,
175
+ 'meta': meta,
176
+ 'score': (1 - self.alpha) * bm25_score
177
+ }
178
+
179
+ # 4. Rank by combined score
180
+ ranked_results = sorted(
181
+ combined_docs.values(),
182
+ key=lambda x: x['score'],
183
+ reverse=True
184
+ )
185
+
186
+ # 5. Filter by threshold
187
+ filtered_results = [
188
+ r for r in ranked_results
189
+ if r['score'] >= score_threshold
190
+ ]
191
+
192
+ # 6. Select with soft per-source caps.
193
+ # Hard one-per-source selection caused shallow, generic answers.
194
+ selected = []
195
+ source_counts = {}
196
+ max_per_source = max(3, n_results // 2)
197
+ for r in filtered_results:
198
+ filename = r['meta'].get('filename', '')
199
+ current = source_counts.get(filename, 0)
200
+ if current < max_per_source:
201
+ selected.append(r)
202
+ source_counts[filename] = current + 1
203
+ if len(selected) >= n_results:
204
+ break
205
+
206
+ if len(selected) < n_results:
207
+ for r in filtered_results:
208
+ if r in selected:
209
+ continue
210
+ selected.append(r)
211
+ if len(selected) >= n_results:
212
+ break
213
+
214
+ # 7. Return in expected format
215
+ documents = [r['doc'] for r in selected]
216
+ metadatas = [r['meta'] for r in selected]
217
+ scores = [r['score'] for r in selected]
218
+
219
+ return documents, metadatas, scores
220
+
221
+ def get_stats(self) -> Dict:
222
+ """Get retriever statistics."""
223
+ return {
224
+ 'bm25_indexed': len(self.bm25_corpus) if self.bm25 else 0,
225
+ 'vector_count': self.vector_db.get_collection_count(),
226
+ 'alpha': self.alpha
227
+ }
utils/legacy_embedding_retrieval.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LEGACY REFERENCE ONLY (DO NOT IMPORT IN RUNTIME)
3
+
4
+ This file keeps the old MiniLM embedding and hybrid chunk retrieval approach for
5
+ historical reference, rollback comparison, or migration audits.
6
+
7
+ Current production path uses:
8
+ - Embedding: BAAI/bge-m3
9
+ - Retrieval: Chroma dense retrieval + BGE reranker
10
+
11
+ This module is intentionally non-usable by runtime and is never imported.
12
+ """
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Dict, List, Optional, Tuple
16
+
17
+
18
+ # Legacy embedding model used before migration
19
+ LEGACY_EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
20
+
21
+ # Legacy chunking defaults previously used in uploads
22
+ LEGACY_CHUNK_SIZE = 900
23
+ LEGACY_CHUNK_OVERLAP = 120
24
+
25
+
26
+ @dataclass
27
+ class LegacyChunkRetrievalSettings:
28
+ """Reference settings from the old retrieval stack."""
29
+
30
+ chunk_size: int = LEGACY_CHUNK_SIZE
31
+ chunk_overlap: int = LEGACY_CHUNK_OVERLAP
32
+ semantic_chunking: bool = True
33
+ retrieval_n: int = 16
34
+ retrieval_threshold: float = 0.01
35
+ hybrid_alpha: float = 0.6
36
+
37
+
38
+ class LegacyVectorDatabaseReference:
39
+ """
40
+ Reference-only placeholder for old vector DB behavior.
41
+
42
+ Legacy behavior summary:
43
+ - sentence-transformers/all-MiniLM-L6-v2 embeddings (384 dimensions)
44
+ - Chroma collection persisted per space
45
+ - query() performed direct dense retrieval without cross-encoder reranking
46
+ """
47
+
48
+ def add_documents(self, texts: List[str], metadatas: List[Dict], ids: List[str]) -> None:
49
+ raise RuntimeError("Legacy reference only. Do not use in production runtime.")
50
+
51
+ def query(self, query_text: str, n_results: int = 20, filter_dict: Optional[Dict] = None) -> Dict:
52
+ raise RuntimeError("Legacy reference only. Do not use in production runtime.")
53
+
54
+
55
+ class LegacyHybridRetrieverReference:
56
+ """
57
+ Reference-only placeholder for old hybrid retrieval path.
58
+
59
+ Legacy behavior summary:
60
+ - Combined Chroma dense retrieval and BM25 sparse retrieval
61
+ - No FlagEmbedding reranker stage
62
+ - Combined scores using alpha weighting and per-source caps
63
+ """
64
+
65
+ def retrieve(
66
+ self,
67
+ query: str,
68
+ n_results: int = 20,
69
+ score_threshold: float = 0.0,
70
+ ) -> Tuple[List[str], List[Dict], List[float]]:
71
+ raise RuntimeError("Legacy reference only. Do not use in production runtime.")
utils/llm_generator.py ADDED
@@ -0,0 +1,1105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gemini-based answer generation with NVIDIA NIM follow-up support.
3
+ This generates grounded responses from retrieved context.
4
+ """
5
+
6
+ import os
7
+ import re
8
+ import time
9
+ from typing import List, Dict, Optional
10
+
11
+ try:
12
+ from openai import OpenAI
13
+ NVIDIA_CLIENT_AVAILABLE = True
14
+ except ImportError:
15
+ NVIDIA_CLIENT_AVAILABLE = False
16
+
17
+ try:
18
+ import google.generativeai as genai
19
+ GEMINI_CLIENT_AVAILABLE = True
20
+ except ImportError:
21
+ GEMINI_CLIENT_AVAILABLE = False
22
+
23
+
24
+ class LLMGenerator:
25
+ """Gemini answer generation with NVIDIA follow-up support."""
26
+
27
+ def __init__(
28
+ self,
29
+ provider: str = "nvidia",
30
+ api_key: Optional[str] = None,
31
+ gemini_api_key: Optional[str] = None,
32
+ nvidia_api_key: Optional[str] = None,
33
+ groq_api_key: Optional[str] = None,
34
+ ):
35
+ del provider
36
+
37
+ self.provider = "gemini"
38
+ self.gemini_client = None
39
+ self.nvidia_client = None
40
+ self.groq_client = None
41
+ self.ready = False
42
+ self.gemini_model_name = os.getenv("GEMINI_MODEL", "gemini-3.5-flash-lite")
43
+ self.nvidia_model_name = os.getenv("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-pro")
44
+ self.api_base_url = os.getenv("NVIDIA_API_BASE_URL", "https://integrate.api.nvidia.com/v1")
45
+ self.groq_model_name = os.getenv("GROQ_FOLLOWUP_MODEL", "openai/gpt-oss-20b")
46
+ self.groq_api_base_url = os.getenv("GROQ_API_BASE_URL", "https://api.groq.com/openai/v1")
47
+ self.enable_thinking = os.getenv("NVIDIA_ENABLE_THINKING", "false").lower() == "true"
48
+ self.end_marker = "<<END_OF_ANSWER>>"
49
+ self.last_notice = None
50
+ self._last_finish_reason = None
51
+
52
+ self.gemini_api_key = gemini_api_key or api_key or os.getenv("GEMINI_API_KEY", "")
53
+ self.nvidia_api_key = nvidia_api_key or os.getenv("NVIDIA_API_KEY", "")
54
+ self.groq_api_key = groq_api_key or os.getenv("GROQ_API_KEY", "")
55
+
56
+ self._initialize_clients()
57
+
58
+ def _initialize_clients(self):
59
+ """Initialize Gemini and NVIDIA clients."""
60
+ self.gemini_client = None
61
+ self.nvidia_client = None
62
+ self.groq_client = None
63
+
64
+ if self.gemini_api_key and GEMINI_CLIENT_AVAILABLE:
65
+ try:
66
+ genai.configure(api_key=self.gemini_api_key)
67
+ self.gemini_client = True
68
+ except Exception as e:
69
+ print(f"Failed to initialize gemini client: {e}")
70
+
71
+ if self.nvidia_api_key and NVIDIA_CLIENT_AVAILABLE:
72
+ try:
73
+ self.nvidia_client = OpenAI(
74
+ base_url=self.api_base_url,
75
+ api_key=self.nvidia_api_key,
76
+ )
77
+ except Exception as e:
78
+ print(f"Failed to initialize nvidia client: {e}")
79
+
80
+ if self.groq_api_key and NVIDIA_CLIENT_AVAILABLE:
81
+ try:
82
+ self.groq_client = OpenAI(
83
+ base_url=self.groq_api_base_url,
84
+ api_key=self.groq_api_key,
85
+ )
86
+ except Exception as e:
87
+ print(f"Failed to initialize groq client: {e}")
88
+
89
+ self.ready = bool(self.gemini_client or self.nvidia_client)
90
+
91
+ def set_api_key(self, api_key: str, provider: str = "gemini"):
92
+ """Update an API key and reinitialize the matching client."""
93
+ if provider == "nvidia":
94
+ self.nvidia_api_key = api_key
95
+ elif provider == "groq":
96
+ self.groq_api_key = api_key
97
+ else:
98
+ self.gemini_api_key = api_key
99
+ self._initialize_clients()
100
+
101
+ def _is_quota_error(self, err: Exception) -> bool:
102
+ msg = str(err).lower()
103
+ return (
104
+ "429" in msg
105
+ or "quota" in msg
106
+ or "rate limit" in msg
107
+ or "resource_exhausted" in msg
108
+ or "insufficient_quota" in msg
109
+ )
110
+
111
+ def _looks_truncated(self, text: str) -> bool:
112
+ """Heuristic check for cut-off model outputs."""
113
+ if not text:
114
+ return False
115
+
116
+ stripped = text.rstrip()
117
+ if len(stripped) < 160:
118
+ return False
119
+
120
+ if self.end_marker in stripped:
121
+ return False
122
+
123
+ if stripped.endswith((".", "!", "?", "]", ")", '"', "'", "```")):
124
+ return (stripped.count("**") % 2 != 0) or (stripped.count("```") % 2 != 0)
125
+
126
+ if stripped[-1].isalnum():
127
+ return True
128
+
129
+ if stripped.count("**") % 2 != 0 or stripped.count("```") % 2 != 0:
130
+ return True
131
+
132
+ dangling_words = (
133
+ " and", " or", " to", " of", " for", " with", " by", " in", " is", " are", " a", " an", " the"
134
+ )
135
+ lowered = stripped.lower()
136
+ return lowered.endswith(dangling_words) or stripped.endswith((":", "-", "*", ",", ";"))
137
+
138
+ def _has_end_marker(self, text: str) -> bool:
139
+ return bool(text) and self.end_marker in text
140
+
141
+ def _split_table_cells(self, line: str) -> List[str]:
142
+ return [c.strip() for c in line.strip().strip('|').split('|')]
143
+
144
+ def _is_markdown_table_separator(self, line: str) -> bool:
145
+ if '|' not in line:
146
+ return False
147
+ cells = self._split_table_cells(line)
148
+ if len(cells) < 2:
149
+ return False
150
+ return all(bool(re.fullmatch(r':?-{3,}:?', c.replace(' ', ''))) for c in cells)
151
+
152
+ def _is_markdown_table_row(self, line: str) -> bool:
153
+ if '|' not in line:
154
+ return False
155
+ cells = self._split_table_cells(line)
156
+ return len(cells) >= 2 and any(c for c in cells)
157
+
158
+ def _normalize_table_row(self, cells: List[str], col_count: int) -> str:
159
+ normalized = [c.strip() for c in cells[:col_count]]
160
+ if len(normalized) < col_count:
161
+ normalized.extend([''] * (col_count - len(normalized)))
162
+ return f"| {' | '.join(normalized)} |"
163
+
164
+ def _expand_compact_table_line(self, line: str) -> List[str]:
165
+ """Expand single-line compact table blobs into one row per line."""
166
+ if line.count('|') < 8 or '| |' not in line:
167
+ return [line]
168
+
169
+ tokens = [t.strip() for t in line.split('|')]
170
+ rows: List[List[str]] = []
171
+ current: List[str] = []
172
+
173
+ for token in tokens:
174
+ if token == '':
175
+ if len(current) >= 2:
176
+ rows.append(current)
177
+ current = []
178
+ continue
179
+ current.append(token)
180
+
181
+ if len(current) >= 2:
182
+ rows.append(current)
183
+
184
+ if len(rows) < 2:
185
+ return [line]
186
+
187
+ col_count = max(len(r) for r in rows)
188
+ return [self._normalize_table_row(r, col_count) for r in rows]
189
+
190
+ def _repair_markdown_tables(self, text: str) -> str:
191
+ """Repair malformed markdown tables (missing separator or compact inline rows)."""
192
+ if not text or '|' not in text:
193
+ return text
194
+
195
+ expanded_lines: List[str] = []
196
+ for raw_line in text.splitlines():
197
+ stripped = raw_line.strip()
198
+ if not stripped:
199
+ expanded_lines.append('')
200
+ continue
201
+ expanded_lines.extend(self._expand_compact_table_line(stripped))
202
+
203
+ repaired: List[str] = []
204
+ i = 0
205
+ while i < len(expanded_lines):
206
+ line = expanded_lines[i].strip()
207
+
208
+ if not self._is_markdown_table_row(line):
209
+ repaired.append(line)
210
+ i += 1
211
+ continue
212
+
213
+ block: List[str] = []
214
+ while i < len(expanded_lines):
215
+ probe = expanded_lines[i].strip()
216
+ if not probe:
217
+ break
218
+ if not (self._is_markdown_table_row(probe) or self._is_markdown_table_separator(probe)):
219
+ break
220
+ block.append(probe)
221
+ i += 1
222
+
223
+ if (
224
+ len(block) >= 2
225
+ and self._is_markdown_table_row(block[0])
226
+ and not self._is_markdown_table_separator(block[1])
227
+ and self._is_markdown_table_row(block[1])
228
+ ):
229
+ col_count = max(2, len(self._split_table_cells(block[0])))
230
+ separator = f"| {' | '.join(['---'] * col_count)} |"
231
+ block.insert(1, separator)
232
+
233
+ repaired.extend(block)
234
+ if i < len(expanded_lines) and expanded_lines[i].strip() == '':
235
+ repaired.append('')
236
+ i += 1
237
+
238
+ return '\n'.join(repaired)
239
+
240
+ def _normalize_math_delimiters(self, text: str) -> str:
241
+ """Normalize model math delimiters for Flutter markdown math parser."""
242
+ if not text:
243
+ return ""
244
+
245
+ normalized = re.sub(
246
+ r'\\\[([\s\S]*?)\\\]',
247
+ lambda m: f"$${m.group(1).strip()}$$",
248
+ text,
249
+ flags=re.DOTALL,
250
+ )
251
+ normalized = re.sub(
252
+ r'\\\(([^\n]*?)\\\)',
253
+ lambda m: f"${m.group(1).strip()}$",
254
+ normalized,
255
+ )
256
+
257
+ normalized = re.sub(r'\$\$\s+', '$$', normalized)
258
+ normalized = re.sub(r'\s+\$\$', '$$', normalized)
259
+ normalized = re.sub(r'\$\s+', '$', normalized)
260
+ normalized = re.sub(r'\s+\$', '$', normalized)
261
+ return normalized
262
+
263
+ def _normalize_formula_equations(self, text: str) -> str:
264
+ """Wrap plain-text metric equations in LaTeX delimiters when missing."""
265
+ if not text:
266
+ return ""
267
+
268
+ metric_eq = re.compile(
269
+ r'\b(MAE|RMSE|MAPE|MASE|MSE|R2|R\^2|BLEU|METEOR|BERTScore|ROUGE(?:-[A-Za-z0-9]+)?)\s*=\s*([^$\n]+?)(?=(?:\s*(?:,?\s*where\b|[.;]|$)))',
270
+ flags=re.IGNORECASE,
271
+ )
272
+ formula_label = re.compile(
273
+ r'(?i)(\bformula\s*:\s*)([^$\n]*?=[^$\n]+?)(?=(?:\s*(?:[.;]|$)))'
274
+ )
275
+
276
+ out_lines: List[str] = []
277
+ for raw_line in text.splitlines():
278
+ line = raw_line
279
+ if '$' in line or '|' in line:
280
+ out_lines.append(line)
281
+ continue
282
+
283
+ # Repair common missing space artifacts around acronyms (e.g., asMAE, whereN).
284
+ line = re.sub(r'([a-z])([A-Z]{2,})', r'\1 \2', line)
285
+
286
+ def _wrap_formula_label(match: re.Match) -> str:
287
+ prefix = match.group(1)
288
+ expr = match.group(2).strip()
289
+ return f"{prefix}${expr}$"
290
+
291
+ line = formula_label.sub(_wrap_formula_label, line)
292
+
293
+ def _wrap_metric_eq(match: re.Match) -> str:
294
+ expr = f"{match.group(1)} = {match.group(2).strip()}"
295
+ return f"${expr}$"
296
+
297
+ line = metric_eq.sub(_wrap_metric_eq, line)
298
+ out_lines.append(line)
299
+
300
+ return "\n".join(out_lines)
301
+
302
+ def _sanitize_final_response(self, text: str) -> str:
303
+ if not text:
304
+ return ""
305
+ cleaned = text.replace(self.end_marker, "").strip()
306
+ cleaned = self._normalize_math_delimiters(cleaned)
307
+ cleaned = self._normalize_formula_equations(cleaned)
308
+ # Strip optional reasoning wrappers if the model emits chain-of-thought blocks.
309
+ cleaned = re.sub(r'<think>[\s\S]*?</think>', '', cleaned, flags=re.IGNORECASE)
310
+ cleaned = re.sub(r'<\|begin_of_thought\|>[\s\S]*?<\|end_of_thought\|>', '', cleaned, flags=re.IGNORECASE)
311
+ cleaned_lines = []
312
+ for raw_line in cleaned.splitlines():
313
+ line = raw_line.strip()
314
+ if not line:
315
+ cleaned_lines.append("")
316
+ continue
317
+
318
+ # Guardrail against OCR-like numbering artifacts leaking into UI output.
319
+ if re.search(r'(?:\d+\.){8,}\d*', line):
320
+ continue
321
+
322
+ compact = re.sub(r'\s+', '', line)
323
+ if len(compact) >= 40 and re.fullmatch(r'[\d\W_]+', compact):
324
+ continue
325
+
326
+ cleaned_lines.append(line)
327
+
328
+ cleaned = "\n".join(cleaned_lines)
329
+ cleaned = re.sub(r'\n{3,}', '\n\n', cleaned).strip()
330
+ cleaned = self._repair_markdown_tables(cleaned)
331
+ return cleaned
332
+
333
+ def _strip_academic_note_section(self, text: str) -> str:
334
+ """Remove trailing Academic Note sections from assistant output."""
335
+ if not text:
336
+ return ""
337
+
338
+ marker = "### Academic Note:"
339
+ idx = text.find(marker)
340
+ if idx == -1:
341
+ return text.strip()
342
+ return text[:idx].strip()
343
+
344
+ def _infer_academic_depth_mode(self, prompt: str, use_case: str) -> bool:
345
+ """Detect questions that should receive rigorous, exam-grade treatment."""
346
+ if use_case not in {"qa", "explanation", "notes"}:
347
+ return False
348
+
349
+ lower = (prompt or "").lower()
350
+ triggers = (
351
+ "evaluate", "evaluation", "compare", "contrast", "analyze", "analysis",
352
+ "justify", "derive", "mathematical", "formula", "metric", "metrics",
353
+ "bleu", "rouge", "meteor", "bertscore", "nlp", "transformer",
354
+ "limitations", "assumptions", "deep learning", "exam", "academic",
355
+ )
356
+ return any(t in lower for t in triggers)
357
+
358
+ def _build_quality_checklist(self, prompt: str, use_case: str) -> str:
359
+ """Return additional instruction block to improve academic completeness."""
360
+ if not self._infer_academic_depth_mode(prompt, use_case):
361
+ return ""
362
+
363
+ checklist = (
364
+ "\n**Academic Completeness Checklist (apply when evidence exists in context):**\n"
365
+ "1. Include core mechanism details, not just definitions.\n"
366
+ "2. Include at least one relevant equation, formula component, or scoring term when present.\n"
367
+ "3. State known limitations/failure cases and why they matter.\n"
368
+ "4. Mention important variants/versions (for example, subtypes or related metrics) when supported by context.\n"
369
+ "5. Briefly contrast with modern alternatives if context includes them.\n"
370
+ "6. Synthesize evidence from multiple source snippets when available.\n"
371
+ "7. Keep structure clear: definition -> mechanics -> limitations -> modern view -> takeaway.\n"
372
+ "8. Render all equations in LaTeX ($...$ inline, $$...$$ block), never plain-text formulas.\n"
373
+ "Note: If a checklist item is not supported by the provided context, explicitly say that.\n"
374
+ )
375
+
376
+ lower = (prompt or "").lower()
377
+ if "bleu" in lower or "rouge" in lower or "summarization" in lower or "translation" in lower:
378
+ checklist += (
379
+ "\n**NLP Metric Focus (for BLEU/ROUGE-style questions):**\n"
380
+ "- For BLEU: explicitly check for and mention **Brevity Penalty (BP)** when present in context.\n"
381
+ "- For ROUGE: avoid reducing it to recall only; mention precision/recall/F1 behavior when supported.\n"
382
+ "- Mention key ROUGE variants such as **ROUGE-N** and **ROUGE-L (LCS)** if found in context.\n"
383
+ "- If context includes modern semantic metrics (for example **BERTScore**), include them as current practice.\n"
384
+ "- If any of the above are missing in context, explicitly note that limitation instead of guessing.\n"
385
+ )
386
+
387
+ return checklist
388
+
389
+ def _needs_depth_boost(self, prompt: str, response: str, use_case: str) -> bool:
390
+ """Detect shallow first-pass answers for academically demanding questions."""
391
+ if not self._infer_academic_depth_mode(prompt, use_case):
392
+ return False
393
+
394
+ word_count = len((response or "").split())
395
+ if use_case == "qa":
396
+ return word_count < 240
397
+ return word_count < 210
398
+
399
+ def _expand_shallow_response(
400
+ self,
401
+ system_prompt: str,
402
+ prompt: str,
403
+ context: str,
404
+ partial_response: str,
405
+ temperature: float,
406
+ max_tokens: int,
407
+ use_case: str,
408
+ ) -> str:
409
+ """Run one targeted expansion pass to improve rigor without changing grounding."""
410
+ quality_checklist = self._build_quality_checklist(prompt, use_case)
411
+ expansion_instruction = (
412
+ "The previous answer is correct but too shallow for an advanced academic response. "
413
+ "Expand it using ONLY the provided context, keeping all citation rules.\n\n"
414
+ f"Question: {prompt}\n\n"
415
+ f"Context:\n{context}\n\n"
416
+ "Current answer:\n"
417
+ f"{partial_response}\n\n"
418
+ "Now produce a richer version with stronger mechanics, limitations, and comparisons where supported by context.\n"
419
+ "Ensure equations are consistently rendered in LaTeX using $...$ and $$...$$.\n"
420
+ "Target depth: around 300-550 words for QA-style prompts when context supports it.\n"
421
+ f"{quality_checklist}\n"
422
+ ""
423
+ )
424
+
425
+ expansion_tokens = max(900, min(1800, max_tokens))
426
+
427
+ try:
428
+ return self._generate_nvidia(
429
+ system_prompt,
430
+ expansion_instruction,
431
+ temperature=max(0.2, min(temperature, 0.45)),
432
+ max_tokens=expansion_tokens,
433
+ thinking=True,
434
+ )
435
+ except Exception:
436
+ return ""
437
+
438
+ def _finish_reason_indicates_cutoff(self) -> bool:
439
+ """Check whether model stop reason indicates truncation due token limits."""
440
+ if self._last_finish_reason is None:
441
+ return False
442
+
443
+ reason = str(self._last_finish_reason).lower()
444
+ return (
445
+ "max_tokens" in reason
446
+ or "max token" in reason
447
+ or "length" in reason
448
+ or "token_limit" in reason
449
+ )
450
+
451
+ def _continue_truncated_response(
452
+ self,
453
+ system_prompt: str,
454
+ prompt: str,
455
+ context: str,
456
+ partial_response: str,
457
+ temperature: float,
458
+ max_tokens: int,
459
+ ) -> str:
460
+ """Request one continuation pass when the first answer looks incomplete."""
461
+ continuation_instruction = (
462
+ "Your previous answer was cut off. Continue exactly from where it stopped. "
463
+ "Do not repeat any completed sections. Keep the same structure and citation style.\n\n"
464
+ f"Original question: {prompt}\n\n"
465
+ f"Context:\n{context}\n\n"
466
+ "Partial answer already generated:\n"
467
+ f"{partial_response}\n\n"
468
+ "Now provide only the missing continuation and end with the exact marker "
469
+ f"{self.end_marker}."
470
+ )
471
+
472
+ continuation_tokens = max(600, min(1400, max_tokens // 2))
473
+
474
+ try:
475
+ return self._generate_gemini(
476
+ system_prompt,
477
+ continuation_instruction,
478
+ temperature=max(0.2, min(temperature, 0.5)),
479
+ max_tokens=continuation_tokens,
480
+ )
481
+ except Exception:
482
+ return ""
483
+
484
+ def generate_response(
485
+ self,
486
+ prompt: str,
487
+ context: str = "",
488
+ use_case: str = "explanation",
489
+ metadatas: List[Dict] = None,
490
+ temperature: float = 0.7,
491
+ max_tokens: int = 1500,
492
+ **kwargs
493
+ ) -> str:
494
+ """Generate response using Gemini with source grounding."""
495
+ del kwargs
496
+
497
+ if not self.ready:
498
+ return (
499
+ "LLM not configured. Please add a Gemini or NVIDIA API key in settings.\n\n"
500
+ "Get a Gemini key: https://aistudio.google.com/app/apikey"
501
+ )
502
+
503
+ if not context:
504
+ return (
505
+ "I don't have enough information from your uploaded documents to answer this question. "
506
+ "Please upload relevant study materials first."
507
+ )
508
+
509
+ system_prompt = self._build_system_prompt(use_case)
510
+ user_message = self._build_user_message(
511
+ prompt,
512
+ context,
513
+ metadatas,
514
+ use_case=use_case,
515
+ )
516
+
517
+ self.last_notice = None
518
+ self._last_finish_reason = None
519
+
520
+ try:
521
+ if self.gemini_client:
522
+ response = self._generate_gemini(
523
+ system_prompt,
524
+ user_message,
525
+ temperature,
526
+ max_tokens,
527
+ )
528
+ elif self.nvidia_client:
529
+ response = self._generate_nvidia(
530
+ system_prompt,
531
+ user_message,
532
+ temperature,
533
+ max_tokens,
534
+ thinking=False,
535
+ )
536
+ else:
537
+ raise RuntimeError("No configured generation client")
538
+
539
+ for _ in range(3):
540
+ if self._has_end_marker(response):
541
+ break
542
+
543
+ if not (
544
+ self._finish_reason_indicates_cutoff()
545
+ or self._looks_truncated(response)
546
+ ):
547
+ break
548
+
549
+ continuation = self._continue_truncated_response(
550
+ system_prompt=system_prompt,
551
+ prompt=prompt,
552
+ context=context,
553
+ partial_response=response,
554
+ temperature=temperature,
555
+ max_tokens=max_tokens,
556
+ )
557
+ if continuation:
558
+ print("[LLM_TIMING] continuation_pass=1")
559
+ response = response.rstrip() + "\n" + continuation.lstrip()
560
+ else:
561
+ break
562
+
563
+ final_response = self._sanitize_final_response(response)
564
+ final_response = self._strip_academic_note_section(final_response)
565
+
566
+ if self._needs_depth_boost(prompt, final_response, use_case):
567
+ clean_partial_response = self._strip_academic_note_section(final_response)
568
+
569
+ expanded = self._expand_shallow_response(
570
+ system_prompt=system_prompt,
571
+ prompt=prompt,
572
+ context=context,
573
+ partial_response=clean_partial_response,
574
+ temperature=temperature,
575
+ max_tokens=max_tokens,
576
+ use_case=use_case,
577
+ )
578
+ if expanded:
579
+ print("[LLM_TIMING] depth_boost=1")
580
+ final_response = self._sanitize_final_response(expanded)
581
+ final_response = self._strip_academic_note_section(final_response)
582
+
583
+ return final_response
584
+
585
+ except Exception as e:
586
+ return (
587
+ "Error generating response: Gemini request failed.\n\n"
588
+ f"Details: {str(e)}"
589
+ )
590
+
591
+ def generate_follow_up_questions(
592
+ self,
593
+ prompt: str,
594
+ context: str,
595
+ answer: str,
596
+ max_questions: int = 3,
597
+ ) -> List[str]:
598
+ """Generate short, actionable follow-up questions for the chat UI."""
599
+ if not self.nvidia_client or not context or not answer:
600
+ return []
601
+
602
+ max_questions = max(1, min(max_questions, 5))
603
+
604
+ system_prompt = (
605
+ "You generate concise suggested follow-up questions for an academic chat app. "
606
+ "Return only questions, one per line, no numbering, no bullets, no explanations."
607
+ )
608
+ user_message = (
609
+ f"Original question:\n{prompt}\n\n"
610
+ f"Assistant answer:\n{answer}\n\n"
611
+ f"Generate {max_questions} follow-up questions that the student would logically "
612
+ "ask NEXT, covering concepts NOT already explained in the answer "
613
+ "above. Do NOT rephrase or re-ask anything that was already "
614
+ "addressed in the answer. Focus on: deeper mechanics, related "
615
+ "concepts, or practical implementation details that were mentioned "
616
+ "but not elaborated on.\n\n"
617
+ f"Context:\n{context}"
618
+ )
619
+
620
+ def parse_questions(raw_output: str) -> List[str]:
621
+ cleaned = self._sanitize_final_response(raw_output)
622
+ lines = [line.strip() for line in cleaned.splitlines() if line.strip()]
623
+ suggestions: List[str] = []
624
+ seen = set()
625
+
626
+ for line in lines:
627
+ q = re.sub(r'^\s*(?:[-*]|\d+[.)])\s*', '', line).strip()
628
+ q = q.strip('"').strip("'").strip()
629
+ if not q:
630
+ continue
631
+ if not q.endswith('?'):
632
+ q = f"{q}?"
633
+ if len(q) < 12 or len(q) > 180:
634
+ continue
635
+
636
+ key = q.lower()
637
+ if key in seen:
638
+ continue
639
+ seen.add(key)
640
+ suggestions.append(q)
641
+
642
+ if len(suggestions) >= max_questions:
643
+ break
644
+
645
+ return suggestions
646
+
647
+ def request_questions(client, model_name: str, provider: str) -> List[str]:
648
+ if not client:
649
+ return []
650
+ try:
651
+ raw_output = self._generate_openai_compatible(
652
+ client=client,
653
+ system_prompt=system_prompt,
654
+ user_message=user_message,
655
+ temperature=0.3,
656
+ max_tokens=220,
657
+ model_name=model_name,
658
+ provider=provider,
659
+ )
660
+ return parse_questions(raw_output)
661
+ except Exception as e:
662
+ print(f"Error in {provider} follow-up generation: {e}")
663
+ return []
664
+
665
+ suggestions = request_questions(
666
+ self.nvidia_client,
667
+ os.getenv("FOLLOWUP_MODEL", " "),
668
+ "nvidia",
669
+ )
670
+ if suggestions:
671
+ return suggestions
672
+
673
+ print("[LLM_TIMING] followup_fallback=groq")
674
+ return request_questions(self.groq_client, self.groq_model_name, "groq")
675
+
676
+ def _generate_gemini(
677
+ self,
678
+ system_prompt: str,
679
+ user_message: str,
680
+ temperature: float,
681
+ max_tokens: int,
682
+ model_name: Optional[str] = None,
683
+ ) -> str:
684
+ """Generate using Gemini API."""
685
+ if not self.gemini_api_key or not GEMINI_CLIENT_AVAILABLE:
686
+ raise RuntimeError("Gemini client is not configured")
687
+
688
+ active_model = model_name or self.gemini_model_name
689
+ t0 = time.perf_counter()
690
+ print(
691
+ f"[LLM_TIMING] request_start model={active_model} provider=gemini "
692
+ f"max_tokens={max_tokens} temperature={temperature} prompt_chars={len(user_message)}"
693
+ )
694
+
695
+ genai.configure(api_key=self.gemini_api_key)
696
+ model = genai.GenerativeModel(model_name=active_model)
697
+ response = model.generate_content(
698
+ f"{system_prompt}\n\n{user_message}",
699
+ generation_config={
700
+ "temperature": temperature,
701
+ "top_p": 0.7,
702
+ "max_output_tokens": max_tokens,
703
+ },
704
+ )
705
+
706
+ content = getattr(response, "text", "") or ""
707
+ print(
708
+ f"[LLM_TIMING] request_done ms={(time.perf_counter() - t0) * 1000:.1f} "
709
+ f"response_chars={len(content or '')}"
710
+ )
711
+
712
+ return content or ""
713
+
714
+ def generate_stream(
715
+ self,
716
+ prompt: str,
717
+ context: str = "",
718
+ use_case: str = "explanation",
719
+ metadatas: List[Dict] = None,
720
+ temperature: float = 0.7,
721
+ max_tokens: int = 1500,
722
+ **kwargs
723
+ ):
724
+ """Generate response using Gemini or NVIDIA with source grounding via live streaming."""
725
+ del kwargs
726
+
727
+ if not self.ready:
728
+ yield (
729
+ "LLM not configured. Please add a Gemini or NVIDIA API key in settings.\n\n"
730
+ "Get a Gemini key: https://aistudio.google.com/app/apikey"
731
+ )
732
+ return
733
+
734
+ if not context:
735
+ yield (
736
+ "I don't have enough information from your uploaded documents to answer this question. "
737
+ "Please upload relevant study materials first."
738
+ )
739
+ return
740
+
741
+ system_prompt = self._build_system_prompt(use_case)
742
+ user_message = self._build_user_message(
743
+ prompt,
744
+ context,
745
+ metadatas,
746
+ use_case=use_case,
747
+ )
748
+
749
+ self.last_notice = None
750
+ self._last_finish_reason = None
751
+
752
+ if self.gemini_client:
753
+ yield from self._generate_gemini_stream(
754
+ system_prompt,
755
+ user_message,
756
+ temperature,
757
+ max_tokens,
758
+ )
759
+ elif self.nvidia_client:
760
+ yield from self._generate_nvidia_stream(
761
+ system_prompt,
762
+ user_message,
763
+ temperature,
764
+ max_tokens,
765
+ thinking=False,
766
+ )
767
+ else:
768
+ raise RuntimeError("No configured generation client")
769
+
770
+ def _generate_gemini_stream(
771
+ self,
772
+ system_prompt: str,
773
+ user_message: str,
774
+ temperature: float,
775
+ max_tokens: int,
776
+ model_name: Optional[str] = None,
777
+ ):
778
+ """Generate using Gemini API with streaming."""
779
+ if not self.gemini_api_key or not GEMINI_CLIENT_AVAILABLE:
780
+ raise RuntimeError("Gemini client is not configured")
781
+
782
+ active_model = model_name or self.gemini_model_name
783
+ t0 = time.perf_counter()
784
+ print(
785
+ f"[LLM_TIMING] request_stream_start model={active_model} provider=gemini "
786
+ f"max_tokens={max_tokens} temperature={temperature} prompt_chars={len(user_message)}"
787
+ )
788
+
789
+ genai.configure(api_key=self.gemini_api_key)
790
+ model = genai.GenerativeModel(model_name=active_model)
791
+
792
+ try:
793
+ response = model.generate_content(
794
+ f"{system_prompt}\n\n{user_message}",
795
+ generation_config={
796
+ "temperature": temperature,
797
+ "top_p": 0.7,
798
+ "max_output_tokens": max_tokens,
799
+ },
800
+ stream=True
801
+ )
802
+
803
+ for chunk in response:
804
+ if chunk.text:
805
+ yield chunk.text
806
+ except Exception as e:
807
+ print(f"[LLM_ERROR] Gemini stream failed: {e}")
808
+ yield f"\n\n[Generation Error: {str(e)}]"
809
+
810
+ print(f"[LLM_TIMING] stream_done ms={(time.perf_counter() - t0) * 1000:.1f}")
811
+
812
+ def _generate_nvidia_stream(
813
+ self,
814
+ system_prompt: str,
815
+ user_message: str,
816
+ temperature: float,
817
+ max_tokens: int,
818
+ model_name: Optional[str] = None,
819
+ thinking: bool = True,
820
+ ):
821
+ """Generate using NVIDIA NIM OpenAI-compatible API with streaming."""
822
+ if not self.nvidia_client:
823
+ raise RuntimeError("NVIDIA client is not configured")
824
+
825
+ active_model = model_name or self.nvidia_model_name
826
+ t0 = time.perf_counter()
827
+ print(
828
+ f"[LLM_TIMING] request_stream_start model={active_model} thinking={bool(thinking)} "
829
+ f"max_tokens={max_tokens} temperature={temperature} prompt_chars={len(user_message)}"
830
+ )
831
+
832
+ extra_body = {}
833
+ if "deepseek" in active_model.lower():
834
+ extra_body["chat_template_kwargs"] = {"thinking": bool(thinking)}
835
+
836
+ try:
837
+ response = self.nvidia_client.chat.completions.create(
838
+ model=active_model,
839
+ messages=[
840
+ {"role": "system", "content": system_prompt},
841
+ {"role": "user", "content": user_message},
842
+ ],
843
+ temperature=temperature,
844
+ max_tokens=max_tokens,
845
+ top_p=0.7,
846
+ extra_body=extra_body,
847
+ stream=True
848
+ )
849
+
850
+ for chunk in response:
851
+ if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
852
+ yield chunk.choices[0].delta.content
853
+ except Exception as e:
854
+ print(f"[LLM_ERROR] NVIDIA stream failed: {e}")
855
+ yield f"\n\n[Generation Error: {str(e)}]"
856
+
857
+ print(f"[LLM_TIMING] stream_done ms={(time.perf_counter() - t0) * 1000:.1f}")
858
+
859
+ def _build_system_prompt(self, use_case: str) -> str:
860
+ """Build specialized system prompt based on use case."""
861
+ base_prompt = (
862
+ "You are the expert generation engine for NotebookPRO, an advanced academic study system for Master-level data science and NLP coursework. "
863
+ "Your goal is to synthesize retrieved textbook excerpts into rigorous, mathematically sound, comprehensive study material.\n\n"
864
+ "STRICT GROUNDING: You MUST ONLY use information present inside the provided context. "
865
+ "Do NOT use outside knowledge and do NOT hallucinate. Every technical claim must be traceable to context.\n\n"
866
+ "TEMPORAL ARBITRATION & SYNTHESIS: Context chunks are labeled as Source [i] [YEAR: YYYY] (filename). "
867
+ "You must analyze year tags. If multiple sources conflict or show conceptual evolution, do NOT blindly merge. "
868
+ "Prioritize the most recent year as modern standard/state-of-the-art, and frame older sources as foundational/historical context.\n\n"
869
+ "ACADEMIC RIGOR: Avoid superficial summaries. "
870
+ "Explain mechanisms, formulas, penalties, architectural details, limitations, and failure modes when present. "
871
+ "Explicitly contrast legacy approaches with modern ones when context supports it.\n\n"
872
+ "REQUIRED OUTPUT STRUCTURE:\n"
873
+ "- Use clear markdown headings with ### for major sections.\n"
874
+ "- Use bulleted breakdowns with bold key terms (for example, * **Mechanism:** ...).\n"
875
+ "- Render formulas in LaTeX using $...$ for inline math and $$...$$ for block math.\n"
876
+ "- Do not use \\(...\\) or \\[...\\] delimiters.\n"
877
+ "- Keep formula notation consistent throughout the answer (do not mix plain-text and LaTeX equations).\n"
878
+ "- For tabular values, always use valid markdown tables: header row, separator row (---), then body rows.\n"
879
+ "- Keep explanations dense, structured, and exam-ready.\n"
880
+ "- Do not add UI-style extras such as 'Suggested Follow-Up Questions' inside the answer body.\n"
881
+ "- NEVER use phrases like 'based on the context', 'the text mentions', 'the provided excerpt states', or 'the sources lack'. Speak with absolute academic authority as if YOU are the textbook.\n"
882
+ "- If advanced requested detail is missing from context, DO NOT mention the limitation. Just answer what you can.\n\n"
883
+ )
884
+
885
+ if use_case == "explanation":
886
+ base_prompt += (
887
+ "**Your task:** Explain the concept in detail, in a clear, step-by-step manner suitable for advanced students.\n"
888
+ "- Start with a clear definition, but immediately follow up with deep, comprehensive details.\n"
889
+ "- Break down the core mechanics, formulas, and components extensively.\n"
890
+ "- Use multiple paragraphs and structured bullet points where necessary.\n"
891
+ "- Aim for substantial depth (typically 250-500 words) to ensure the concept is fully explored.\n"
892
+ "- Add a 'Key Takeaway' section at the end if appropriate.\n"
893
+ )
894
+ elif use_case == "summary":
895
+ base_prompt += (
896
+ "**Your task:** Create a highly structured summary.\n"
897
+ "- Start with a brief high-level overview (2 sentences max).\n"
898
+ "- Use '### Key Themes' and list the main points as bulleted items.\n"
899
+ "- Keep each point concise but factually dense.\n"
900
+ )
901
+ elif use_case == "qa":
902
+ base_prompt += (
903
+ "**Your task:** Answer the question directly and comprehensively.\n"
904
+ "- Provide the direct answer immediately in the first sentence.\n"
905
+ "- Build a deep explanation using multiple complementary points from the context, not just one short paragraph.\n"
906
+ "- When the question asks 'why', include mechanisms, business impact, risks, and implementation implications if present in context.\n"
907
+ "- Synthesize across multiple sources and explicitly contrast or connect them when applicable.\n"
908
+ "- Use numbered lists or bullet points to provide supporting details from the context.\n"
909
+ "- Use **bold** for key facts, numbers, and formulas.\n"
910
+ "- Aim for substantial depth (typically 250-500 words) unless the context is very limited.\n"
911
+ )
912
+ elif use_case == "notes":
913
+ base_prompt += (
914
+ "**Your task:** Create comprehensive, structured study notes.\n"
915
+ "- Use clear section headers (###).\n"
916
+ "- Organize information hierarchically (using nested bullet points).\n"
917
+ "- Explicitly highlight **Definitions**, **Formulas**, and **Important Dates/Names**.\n"
918
+ )
919
+
920
+ base_prompt += (
921
+ "\n**Citation Rules:**\n"
922
+ "- You MUST cite your source at the end of every major claim or paragraph using numbered brackets like **[1]**, **[2]** based on the Source number provided in the context.\n"
923
+ "- If a claim comes from multiple sources, use **[1, 2]**.\n"
924
+ "- Citations must be numeric only: **[n]** or **[n, m]**.\n"
925
+ "- NEVER include year, filename, or the word 'Source' in citation text.\n"
926
+ "- Do NOT make up information - stick strictly to the provided context.\n"
927
+ )
928
+
929
+ return base_prompt
930
+
931
+ def _build_user_message(
932
+ self,
933
+ prompt: str,
934
+ context: str,
935
+ metadatas: List[Dict] = None,
936
+ use_case: str = "qa",
937
+ ) -> str:
938
+ """Build user message with context and question."""
939
+ sources = []
940
+ if metadatas:
941
+ for meta in metadatas:
942
+ filename = meta.get("filename", "Unknown")
943
+ clean_name = filename.replace(".pdf", "").replace(".docx", "").replace(".txt", "")
944
+ if clean_name not in sources:
945
+ sources.append(clean_name)
946
+
947
+ message = "**Available Sources (USE ONLY THESE):**\n"
948
+ for source in sources[:5]:
949
+ message += f"- {source}\n"
950
+
951
+ quality_checklist = self._build_quality_checklist(prompt, use_case=use_case)
952
+
953
+ message += f"\n**===== START OF CONTEXT (ANSWER ONLY FROM THIS) =====**\n\n{context}\n\n"
954
+ message += "**===== END OF CONTEXT =====**\n\n"
955
+ message += f"**Student's Question:** {prompt}\n\n"
956
+ message += (
957
+ "**Instructions:** Answer ONLY using the context between the markers above. "
958
+ "If the context doesn't contain the answer, say you don't have that information. "
959
+ "Cite sources in brackets."
960
+ )
961
+ if quality_checklist:
962
+ message += f"\n{quality_checklist}"
963
+
964
+ return message
965
+
966
+ def _generate_nvidia(
967
+ self,
968
+ system_prompt: str,
969
+ user_message: str,
970
+ temperature: float,
971
+ max_tokens: int,
972
+ model_name: Optional[str] = None,
973
+ thinking: bool = True,
974
+ ) -> str:
975
+ """Generate using NVIDIA NIM OpenAI-compatible API."""
976
+ if not self.nvidia_client:
977
+ raise RuntimeError("NVIDIA client is not configured")
978
+
979
+ active_model = model_name or self.nvidia_model_name
980
+ t0 = time.perf_counter()
981
+ print(
982
+ f"[LLM_TIMING] request_start model={active_model} thinking={bool(thinking)} "
983
+ f"max_tokens={max_tokens} temperature={temperature} prompt_chars={len(user_message)}"
984
+ )
985
+ # Only deepseek models on Nvidia NIM support the thinking toggle param natively
986
+ extra_body = {}
987
+ if "deepseek" in active_model.lower():
988
+ extra_body["chat_template_kwargs"] = {"thinking": bool(thinking)}
989
+
990
+ response = self.nvidia_client.chat.completions.create(
991
+ model=active_model,
992
+ messages=[
993
+ {"role": "system", "content": system_prompt},
994
+ {"role": "user", "content": user_message},
995
+ ],
996
+ temperature=temperature,
997
+ top_p=0.7,
998
+ max_tokens=max_tokens,
999
+ extra_body=extra_body if extra_body else None,
1000
+ stream=False,
1001
+ )
1002
+
1003
+ try:
1004
+ self._last_finish_reason = response.choices[0].finish_reason if response.choices else None
1005
+ except Exception:
1006
+ self._last_finish_reason = None
1007
+
1008
+ if not response.choices:
1009
+ return ""
1010
+
1011
+ message = response.choices[0].message
1012
+ content = getattr(message, "content", "")
1013
+ if isinstance(content, list):
1014
+ # Some OpenAI-compatible SDKs can return segmented content.
1015
+ chunks = []
1016
+ for part in content:
1017
+ if isinstance(part, dict):
1018
+ text = part.get("text") or part.get("content") or ""
1019
+ if text:
1020
+ chunks.append(str(text))
1021
+ content = "".join(chunks)
1022
+
1023
+ print(
1024
+ f"[LLM_TIMING] request_done ms={(time.perf_counter() - t0) * 1000:.1f} "
1025
+ f"finish_reason={self._last_finish_reason} response_chars={len(content or '')}"
1026
+ )
1027
+
1028
+ return content or ""
1029
+
1030
+ def _generate_openai_compatible(
1031
+ self,
1032
+ client,
1033
+ system_prompt: str,
1034
+ user_message: str,
1035
+ temperature: float,
1036
+ max_tokens: int,
1037
+ model_name: str,
1038
+ provider: str,
1039
+ ) -> str:
1040
+ """Generate short outputs through an OpenAI-compatible provider."""
1041
+ t0 = time.perf_counter()
1042
+ print(
1043
+ f"[LLM_TIMING] request_start model={model_name} provider={provider} "
1044
+ f"max_tokens={max_tokens} temperature={temperature} prompt_chars={len(user_message)}"
1045
+ )
1046
+ request_kwargs = {
1047
+ "model": model_name,
1048
+ "messages": [
1049
+ {"role": "system", "content": system_prompt},
1050
+ {"role": "user", "content": user_message},
1051
+ ],
1052
+ "temperature": temperature,
1053
+ "top_p": 0.7,
1054
+ "max_tokens": max_tokens,
1055
+ "stream": False,
1056
+ }
1057
+ if provider == "groq":
1058
+ request_kwargs["reasoning_effort"] = "low"
1059
+
1060
+ response = client.chat.completions.create(
1061
+ **request_kwargs,
1062
+ )
1063
+ if not response.choices:
1064
+ return ""
1065
+
1066
+ content = getattr(response.choices[0].message, "content", "") or ""
1067
+ print(
1068
+ f"[LLM_TIMING] request_done ms={(time.perf_counter() - t0) * 1000:.1f} "
1069
+ f"provider={provider} response_chars={len(content)}"
1070
+ )
1071
+ return content
1072
+
1073
+ def is_ready(self) -> bool:
1074
+ """Check if LLM is ready to generate."""
1075
+ return self.ready
1076
+
1077
+ def get_provider(self) -> str:
1078
+ """Get current provider name."""
1079
+ return f"Gemini {self.gemini_model_name}"
1080
+
1081
+ def generate(self, prompt: str, temperature: float = 0.3, max_tokens: int = 1500) -> str:
1082
+ """Simple wrapper for backend compatibility."""
1083
+ if not self.ready:
1084
+ return (
1085
+ "LLM not configured. Please add your Gemini API key.\n\n"
1086
+ "Get a key: https://aistudio.google.com/app/apikey"
1087
+ )
1088
+
1089
+ try:
1090
+ if self.gemini_client:
1091
+ return self._generate_gemini(
1092
+ system_prompt="You are a helpful AI assistant.",
1093
+ user_message=prompt,
1094
+ temperature=temperature,
1095
+ max_tokens=max_tokens,
1096
+ )
1097
+ return self._generate_nvidia(
1098
+ system_prompt="You are a helpful AI assistant.",
1099
+ user_message=prompt,
1100
+ temperature=temperature,
1101
+ max_tokens=max_tokens,
1102
+ thinking=False,
1103
+ )
1104
+ except Exception as e:
1105
+ return f"Error generating response: {str(e)}"
utils/model_inference.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
3
+ from typing import List, Dict, Optional
4
+ import config
5
+
6
+
7
+ class ModelInference:
8
+ """Handle model loading and inference for text generation."""
9
+
10
+ def __init__(self, model_name: str = None, use_4bit: bool = True):
11
+ """
12
+ Initialize the model for inference.
13
+ RAG Mode: Uses pre-trained model directly (no training needed!).
14
+
15
+ Args:
16
+ model_name: Name or path of the model (uses pre-trained by default)
17
+ use_4bit: Whether to use 4-bit quantization for efficiency
18
+ """
19
+ # Use pre-trained model if specified, otherwise check for fine-tuned model
20
+ if config.USE_PRETRAINED or not Path(config.MODEL_PATH).exists():
21
+ self.model_name = model_name or config.MODEL_NAME
22
+ else:
23
+ self.model_name = model_name or config.MODEL_PATH
24
+
25
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
26
+
27
+ print(f"Loading model: {self.model_name}")
28
+ print(f"Device: {self.device}")
29
+
30
+ # Configure quantization for efficiency
31
+ if use_4bit and self.device == "cuda":
32
+ bnb_config = BitsAndBytesConfig(
33
+ load_in_4bit=True,
34
+ bnb_4bit_quant_type="nf4",
35
+ bnb_4bit_compute_dtype=torch.float16,
36
+ bnb_4bit_use_double_quant=True,
37
+ )
38
+ self.model = AutoModelForCausalLM.from_pretrained(
39
+ self.model_name,
40
+ quantization_config=bnb_config,
41
+ device_map="auto",
42
+ trust_remote_code=True
43
+ )
44
+ else:
45
+ self.model = AutoModelForCausalLM.from_pretrained(
46
+ self.model_name,
47
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
48
+ device_map="auto" if self.device == "cuda" else None,
49
+ trust_remote_code=True
50
+ )
51
+
52
+ self.tokenizer = AutoTokenizer.from_pretrained(
53
+ self.model_name,
54
+ trust_remote_code=True
55
+ )
56
+
57
+ if self.tokenizer.pad_token is None:
58
+ self.tokenizer.pad_token = self.tokenizer.eos_token
59
+
60
+ self.model.eval()
61
+
62
+ def generate_response(
63
+ self,
64
+ prompt: str,
65
+ context: str = "",
66
+ use_case: str = "explanation",
67
+ temperature: float = None,
68
+ max_tokens: int = None
69
+ ) -> str:
70
+ """
71
+ Generate a response based on the prompt and context.
72
+
73
+ Args:
74
+ prompt: User query
75
+ context: Retrieved context from documents
76
+ use_case: Type of response (explanation, summary, qa, notes)
77
+ temperature: Sampling temperature
78
+ max_tokens: Maximum number of tokens to generate
79
+
80
+ Returns:
81
+ Generated text response
82
+ """
83
+ temperature = temperature or config.TEMPERATURE
84
+ max_tokens = max_tokens or config.MAX_TOKENS
85
+
86
+ # Create system prompt based on use case
87
+ system_prompts = {
88
+ "explanation": "You are an expert tutor. Provide detailed, clear explanations of concepts based on the given context.",
89
+ "summary": "You are a summarization expert. Create concise, well-structured summaries of the provided content.",
90
+ "qa": "You are a knowledgeable assistant. Answer questions accurately based on the given context.",
91
+ "notes": "You are a study notes specialist. Create well-organized, structured study notes from the content."
92
+ }
93
+
94
+ system_prompt = system_prompts.get(use_case, system_prompts["explanation"])
95
+
96
+ # Format the full prompt
97
+ full_prompt = self._format_prompt(system_prompt, context, prompt)
98
+
99
+ # Tokenize
100
+ inputs = self.tokenizer(
101
+ full_prompt,
102
+ return_tensors="pt",
103
+ truncation=True,
104
+ max_length=2048
105
+ ).to(self.device)
106
+
107
+ # Generate
108
+ with torch.no_grad():
109
+ outputs = self.model.generate(
110
+ **inputs,
111
+ max_new_tokens=max_tokens,
112
+ temperature=temperature,
113
+ do_sample=True,
114
+ top_p=0.95,
115
+ top_k=50,
116
+ repetition_penalty=1.1,
117
+ pad_token_id=self.tokenizer.pad_token_id,
118
+ eos_token_id=self.tokenizer.eos_token_id
119
+ )
120
+
121
+ # Decode
122
+ response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
123
+
124
+ # Extract only the new generated text
125
+ response = response[len(full_prompt):].strip()
126
+
127
+ return response
128
+
129
+ def _format_prompt(self, system_prompt: str, context: str, query: str) -> str:
130
+ """Format the prompt with system instructions, context, and query."""
131
+ prompt = f"{system_prompt}\n\n"
132
+
133
+ if context:
134
+ prompt += f"Context from your study materials:\n{context}\n\n"
135
+
136
+ prompt += f"Query: {query}\n\nResponse:"
137
+
138
+ return prompt
139
+
140
+ def batch_generate(self, prompts: List[str], **kwargs) -> List[str]:
141
+ """
142
+ Generate responses for multiple prompts.
143
+
144
+ Args:
145
+ prompts: List of prompts
146
+ **kwargs: Additional arguments for generate_response
147
+
148
+ Returns:
149
+ List of generated responses
150
+ """
151
+ responses = []
152
+ for prompt in prompts:
153
+ response = self.generate_response(prompt, **kwargs)
154
+ responses.append(response)
155
+
156
+ return responses
utils/simple_generator.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NotebookLM-style response generator with professional formatting.
3
+ """
4
+
5
+ from typing import List, Dict
6
+ import config
7
+ import re
8
+
9
+
10
+ class SimpleGenerator:
11
+ """Lightweight generator with NotebookLM-quality formatting."""
12
+
13
+ def __init__(self):
14
+ self.ready = True
15
+
16
+ def _clean_and_format_text(self, text: str) -> str:
17
+ """Clean and format text with proper spacing like NotebookLM."""
18
+ # Fix spacing after punctuation
19
+ text = re.sub(r'([.!?])([A-Z])', r'\1 \2', text)
20
+ # Remove multiple spaces
21
+ text = re.sub(r'\s+', ' ', text)
22
+ # Add proper line breaks after sentences
23
+ text = re.sub(r'([.!?])\s+', r'\1\n\n', text)
24
+ return text.strip()
25
+
26
+ def _extract_key_terms(self, text: str) -> List[str]:
27
+ """Extract key terms that should be bolded."""
28
+ # Look for capitalized terms, technical terms
29
+ terms = []
30
+
31
+ # Find terms in quotes
32
+ quoted = re.findall(r'"([^"]+)"', text)
33
+ terms.extend(quoted)
34
+
35
+ # Find repeated important words (appear 2+ times)
36
+ words = re.findall(r'\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b', text)
37
+ word_count = {}
38
+ for word in words:
39
+ word_count[word] = word_count.get(word, 0) + 1
40
+
41
+ # Add words that appear multiple times
42
+ terms.extend([w for w, count in word_count.items() if count >= 2])
43
+
44
+ return list(set(terms))
45
+
46
+ def _apply_bold_formatting(self, text: str) -> str:
47
+ """Apply bold formatting to key terms like NotebookLM."""
48
+ key_terms = self._extract_key_terms(text)
49
+
50
+ # Bold key terms
51
+ for term in key_terms:
52
+ if len(term) > 3: # Skip very short terms
53
+ text = re.sub(rf'\b({re.escape(term)})\b', r'**\1**', text, count=1)
54
+
55
+ # Bold specific patterns
56
+ # Numbers with context
57
+ text = re.sub(r'\b(\d+)\s+(observations?|years?|months?|quarters?)', r'**\1 \2**', text)
58
+
59
+ return text
60
+
61
+ def _create_structured_response(self, context: str, query: str) -> str:
62
+ """Create a NotebookLM-style structured response."""
63
+ # Split into paragraphs
64
+ paragraphs = [p.strip() for p in context.split('\n\n') if len(p.strip()) > 50]
65
+
66
+ # Remove duplicates
67
+ unique_paras = []
68
+ seen = set()
69
+ for para in paragraphs:
70
+ para_key = para.lower()[:150]
71
+ if para_key not in seen:
72
+ unique_paras.append(para)
73
+ seen.add(para_key)
74
+ if len(unique_paras) >= 5:
75
+ break
76
+
77
+ if not unique_paras:
78
+ return context[:1000]
79
+
80
+ # Build NotebookLM-style response
81
+ response = ""
82
+
83
+ # Main explanation (first paragraph - cleaned and formatted)
84
+ main_para = self._clean_and_format_text(unique_paras[0])
85
+ main_para = self._apply_bold_formatting(main_para)
86
+ response += main_para + "\n\n"
87
+
88
+ # Add structured details if more content available
89
+ if len(unique_paras) > 1:
90
+ response += "### Key Points:\n\n"
91
+
92
+ for i, para in enumerate(unique_paras[1:4], 1):
93
+ # Extract first 2-3 sentences
94
+ sentences = [s.strip() for s in para.split('.') if len(s.strip()) > 20]
95
+ if sentences:
96
+ detail = self._clean_and_format_text('. '.join(sentences[:2]) + '.')
97
+ detail = self._apply_bold_formatting(detail)
98
+ response += f"{i}. {detail}\n\n"
99
+
100
+ return response.strip()
101
+
102
+ def generate_response(
103
+ self,
104
+ prompt: str,
105
+ context: str = "",
106
+ use_case: str = "explanation",
107
+ metadatas: List[Dict] = None,
108
+ **kwargs
109
+ ) -> str:
110
+ """
111
+ Generate a NotebookLM-quality response with strict citations.
112
+
113
+ Args:
114
+ prompt: User query
115
+ context: Retrieved context from documents
116
+ use_case: Type of response (explanation, summary, qa,notes)
117
+ metadatas: Metadata for each context chunk (for citations)
118
+
119
+ Returns:
120
+ Professional formatted response with inline citations
121
+ """
122
+ if not context:
123
+ return (
124
+ "I don't have enough information from your uploaded documents to answer this question. "
125
+ "Please upload relevant study materials first, or try rephrasing your question."
126
+ )
127
+
128
+ # Use specialized prompts based on use case
129
+ if use_case == "summary":
130
+ response = self._create_summary_with_citations(context, prompt, metadatas)
131
+ elif use_case == "notes":
132
+ response = self._create_notes_with_citations(context, prompt, metadatas)
133
+ elif use_case == "qa":
134
+ response = self._create_qa_with_citations(context, prompt, metadatas)
135
+ else: # Default to explanation
136
+ response = self._create_structured_response_with_citations(context, prompt, metadatas)
137
+
138
+ return response
139
+
140
+ def _create_structured_response_with_citations(
141
+ self,
142
+ context: str,
143
+ query: str,
144
+ metadatas: List[Dict] = None
145
+ ) -> str:
146
+ """Create NotebookLM-style response with inline citations."""
147
+ # Split into paragraphs
148
+ paragraphs = [p.strip() for p in context.split('\n\n') if len(p.strip()) > 50]
149
+
150
+ # Remove duplicates
151
+ unique_paras = []
152
+ seen = set()
153
+ for para in paragraphs:
154
+ para_key = para.lower()[:150]
155
+ if para_key not in seen:
156
+ unique_paras.append(para)
157
+ seen.add(para_key)
158
+ if len(unique_paras) >= 5:
159
+ break
160
+
161
+ if not unique_paras:
162
+ return context[:1000]
163
+
164
+ # Build response with citations
165
+ response = ""
166
+
167
+ # Main explanation (first paragraph - cleaned and formatted)
168
+ main_para = self._clean_and_format_text(unique_paras[0])
169
+ main_para = self._apply_bold_formatting(main_para)
170
+
171
+ # Add citation to end of main paragraph
172
+ cite_text = self._get_citation(0, metadatas) if metadatas else ""
173
+ response += main_para + cite_text + "\n\n"
174
+
175
+ # Add structured details if more content available
176
+ if len(unique_paras) > 1:
177
+ response += "### Key Points:\n\n"
178
+
179
+ for i, para in enumerate(unique_paras[1:4], 1):
180
+ # Extract first 2-3 sentences
181
+ sentences = [s.strip() for s in para.split('.') if len(s.strip()) > 20]
182
+ if sentences:
183
+ detail = self._clean_and_format_text('. '.join(sentences[:2]) + '.')
184
+ detail = self._apply_bold_formatting(detail)
185
+
186
+ # Add citation
187
+ cite_text = self._get_citation(i, metadatas) if metadatas and i < len(metadatas) else ""
188
+ response += f"{i}. {detail}{cite_text}\n\n"
189
+
190
+ return response.strip()
191
+
192
+ def _get_citation(self, index: int, metadatas: List[Dict] = None) -> str:
193
+ """Generate inline citation from metadata."""
194
+ if not metadatas or index >= len(metadatas):
195
+ return ""
196
+
197
+ meta = metadatas[index]
198
+ filename = meta.get('filename', 'Unknown')
199
+
200
+ # Remove file extension for cleaner citation
201
+ clean_name = filename.replace('.pdf', '').replace('.docx', '').replace('.txt', '')
202
+
203
+ return f" **[{clean_name}]**"
204
+
205
+ def _create_summary_with_citations(
206
+ self,
207
+ context: str,
208
+ query: str,
209
+ metadatas: List[Dict] = None
210
+ ) -> str:
211
+ """Create a summary with citations."""
212
+ sentences = []
213
+ seen = set()
214
+ for s in context.split('.'):
215
+ s_clean = s.strip()
216
+ if len(s_clean) > 40 and s_clean.lower() not in seen:
217
+ sentences.append(s_clean)
218
+ seen.add(s_clean.lower())
219
+ if len(sentences) >= 6:
220
+ break
221
+
222
+ if not sentences:
223
+ return context[:800]
224
+
225
+ response = "## Summary\n\n"
226
+ for i, point in enumerate(sentences, 1):
227
+ cite = self._get_citation(i-1, metadatas) if metadatas else ""
228
+ response += f"{i}. {point}.{cite}\n\n"
229
+
230
+ return response.strip()
231
+
232
+ def _create_qa_with_citations(
233
+ self,
234
+ context: str,
235
+ query: str,
236
+ metadatas: List[Dict] = None
237
+ ) -> str:
238
+ """Answer with strict source grounding."""
239
+ paragraphs = [p.strip() for p in context.split('\n\n') if len(p.strip()) > 50]
240
+
241
+ if not paragraphs:
242
+ sentences = [s.strip() + '.' for s in context.split('.') if len(s.strip()) > 30]
243
+ response = ' '.join(sentences[:6])
244
+ cite = self._get_citation(0, metadatas) if metadatas else ""
245
+ return response + cite
246
+
247
+ # Remove duplicates
248
+ unique_paras = []
249
+ seen = set()
250
+ for para in paragraphs:
251
+ para_key = para.lower()[:150]
252
+ if para_key not in seen:
253
+ unique_paras.append(para)
254
+ seen.add(para_key)
255
+ if len(unique_paras) >= 3:
256
+ break
257
+
258
+ # Fix spacing and add citations
259
+ response = unique_paras[0] if unique_paras else context[:800]
260
+ response = re.sub(r'([.!?])([A-Z])', r'\1 \2', response)
261
+ cite = self._get_citation(0, metadatas) if metadatas else ""
262
+ response += cite
263
+
264
+ # Add supporting details if available
265
+ if len(unique_paras) > 1:
266
+ second_para = re.sub(r'([.!?])([A-Z])', r'\1 \2', unique_paras[1])
267
+ cite2 = self._get_citation(1, metadatas) if metadatas and len(metadatas) > 1 else ""
268
+ response += "\n\n" + second_para + cite2
269
+
270
+ return response.strip()
271
+
272
+ def _create_notes_with_citations(
273
+ self,
274
+ context: str,
275
+ query: str,
276
+ metadatas: List[Dict] = None
277
+ ) -> str:
278
+ """Create study notes with source attribution."""
279
+ sections = [s.strip() for s in context.split('\n\n') if len(s.strip()) > 40]
280
+
281
+ # Remove duplicates
282
+ unique_sections = []
283
+ seen = set()
284
+ for section in sections:
285
+ section_key = section.lower()[:100]
286
+ if section_key not in seen:
287
+ unique_sections.append(section)
288
+ seen.add(section_key)
289
+ if len(unique_sections) >= 6:
290
+ break
291
+
292
+ if not unique_sections:
293
+ return context[:1000]
294
+
295
+ response = "## Study Notes\n\n"
296
+
297
+ for i, section in enumerate(unique_sections, 1):
298
+ sentences = [s.strip() for s in section.split('.') if len(s.strip()) > 20]
299
+
300
+ if sentences:
301
+ heading = sentences[0]
302
+ cite = self._get_citation(i-1, metadatas) if metadatas else ""
303
+ response += f"### {i}. {heading}{cite}\n\n"
304
+
305
+ for sent in sentences[1:3]:
306
+ response += f"- {sent}\n"
307
+ response += "\n"
308
+
309
+ return response.strip()
310
+
311
+ def _create_summary(self, context: str, query: str) -> str:
312
+ """Create a clean summary from retrieved context."""
313
+ # Extract key sentences - remove duplicates
314
+ sentences = []
315
+ seen = set()
316
+ for s in context.split('.'):
317
+ s_clean = s.strip()
318
+ # Remove duplicates and filter short/low-quality sentences
319
+ if len(s_clean) > 40 and s_clean.lower() not in seen:
320
+ sentences.append(s_clean)
321
+ seen.add(s_clean.lower())
322
+ if len(sentences) >= 6:
323
+ break
324
+
325
+ if not sentences:
326
+ return context[:800]
327
+
328
+ response = "## Summary\n\n"
329
+ for i, point in enumerate(sentences, 1):
330
+ response += f"{i}. {point}.\n\n"
331
+
332
+ return response.strip()
333
+
334
+ def _create_explanation(self, context: str, query: str) -> str:
335
+ """Create a well-formatted explanation from retrieved context."""
336
+ # Remove duplicate paragraphs
337
+ paragraphs = []
338
+ seen = set()
339
+ for para in context.split('\n\n'):
340
+ para_clean = para.strip()
341
+ # Keep unique, substantial paragraphs
342
+ if len(para_clean) > 50:
343
+ para_lower = para_clean.lower()[:200] # Check first 200 chars for duplicates
344
+ if para_lower not in seen:
345
+ paragraphs.append(para_clean)
346
+ seen.add(para_lower)
347
+
348
+ if not paragraphs:
349
+ # Fallback: split by sentence
350
+ sentences = [s.strip() + '.' for s in context.split('.') if len(s.strip()) > 30]
351
+ return ' '.join(sentences[:8])
352
+
353
+ # Build clean, formatted response with proper spacing
354
+ response = ""
355
+
356
+ # Add first paragraph as main explanation (ensure spacing between sentences)
357
+ first_para = paragraphs[0]
358
+ # Add space after punctuation if missing
359
+ import re
360
+ first_para = re.sub(r'([.!?])([A-Z])', r'\1 \2', first_para)
361
+ response += first_para
362
+
363
+ # Add additional details if available
364
+ if len(paragraphs) > 1:
365
+ response += "\n\n### Key Points:\n\n"
366
+ for i, para in enumerate(paragraphs[1:4], 1): # Max 3 additional points
367
+ # Extract first sentence as bullet
368
+ sentences = [s.strip() for s in para.split('.') if len(s.strip()) > 20]
369
+ if sentences:
370
+ response += f"• {sentences[0]}.\n"
371
+ if len(sentences) > 1 and len(sentences[1]) > 20:
372
+ response += f" {sentences[1]}.\n"
373
+ response += "\n"
374
+
375
+ return response.strip()
376
+
377
+ def _create_qa(self, context: str, query: str) -> str:
378
+ """Answer a question with clean formatting."""
379
+ # Find most relevant paragraphs
380
+ paragraphs = [p.strip() for p in context.split('\n\n') if len(p.strip()) > 50]
381
+
382
+ if not paragraphs:
383
+ sentences = [s.strip() + '.' for s in context.split('.') if len(s.strip()) > 30]
384
+ return ' '.join(sentences[:6])
385
+
386
+ # Remove duplicates
387
+ unique_paras = []
388
+ seen = set()
389
+ for para in paragraphs:
390
+ para_key = para.lower()[:150]
391
+ if para_key not in seen:
392
+ unique_paras.append(para)
393
+ seen.add(para_key)
394
+ if len(unique_paras) >= 3:
395
+ break
396
+
397
+ # Fix spacing in response
398
+ import re
399
+ response = unique_paras[0] if unique_paras else context[:800]
400
+ response = re.sub(r'([.!?])([A-Z])', r'\1 \2', response)
401
+
402
+ # Add supporting details if available
403
+ if len(unique_paras) > 1:
404
+ second_para = re.sub(r'([.!?])([A-Z])', r'\1 \2', unique_paras[1])
405
+ response += "\n\n" + second_para
406
+
407
+ return response.strip()
408
+
409
+ def _create_notes(self, context: str, query: str) -> str:
410
+ """Create well-structured study notes."""
411
+ # Split and clean sections
412
+ sections = [s.strip() for s in context.split('\n\n') if len(s.strip()) > 40]
413
+
414
+ # Remove duplicates
415
+ unique_sections = []
416
+ seen = set()
417
+ for section in sections:
418
+ section_key = section.lower()[:100]
419
+ if section_key not in seen:
420
+ unique_sections.append(section)
421
+ seen.add(section_key)
422
+ if len(unique_sections) >= 6:
423
+ break
424
+
425
+ if not unique_sections:
426
+ return context[:1000]
427
+
428
+ response = "## Study Notes\n\n"
429
+
430
+ for i, section in enumerate(unique_sections, 1):
431
+ # Extract key information
432
+ sentences = [s.strip() for s in section.split('.') if len(s.strip()) > 20]
433
+
434
+ if sentences:
435
+ # Use first sentence as heading
436
+ heading = sentences[0]
437
+ response += f"### {i}. {heading}\n\n"
438
+
439
+ # Add bullet points for remaining content
440
+ for sent in sentences[1:3]: # Max 2 additional sentences
441
+ response += f"- {sent}\n"
442
+ response += "\n"
443
+
444
+ return response.strip()
utils/spaces_manager.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Spaces (Workspaces) manager for organizing chats and files by subject.
3
+ Each space has its own vector DB and chat history.
4
+ """
5
+
6
+ import json
7
+ from pathlib import Path
8
+ from typing import List, Dict, Optional
9
+ from datetime import datetime
10
+ import config
11
+
12
+
13
+ class SpacesManager:
14
+ """Manages workspaces (Spaces) for organizing study materials by subject."""
15
+
16
+ def __init__(self):
17
+ self.spaces_file = config.DATA_DIR / "spaces.json"
18
+ self.spaces_data = self._load_spaces()
19
+
20
+ def _load_spaces(self) -> Dict:
21
+ """Load spaces from file."""
22
+ if self.spaces_file.exists():
23
+ try:
24
+ with open(self.spaces_file, 'r', encoding='utf-8') as f:
25
+ return json.load(f)
26
+ except Exception:
27
+ return self._create_default_spaces()
28
+ return self._create_default_spaces()
29
+
30
+ def _create_default_spaces(self) -> Dict:
31
+ """Create default spaces structure."""
32
+ return {
33
+ "spaces": [
34
+ {
35
+ "id": "general",
36
+ "name": "General",
37
+ "description": "General study materials",
38
+ "created_at": datetime.now().isoformat(),
39
+ "file_count": 0,
40
+ "chat_count": 0
41
+ }
42
+ ]
43
+ }
44
+
45
+ def save_spaces(self):
46
+ """Save spaces to file."""
47
+ try:
48
+ with open(self.spaces_file, 'w', encoding='utf-8') as f:
49
+ json.dump(self.spaces_data, f, indent=2)
50
+ except Exception as e:
51
+ print(f"Error saving spaces: {e}")
52
+
53
+ def get_all_spaces(self) -> List[Dict]:
54
+ """Get all spaces."""
55
+ return self.spaces_data.get("spaces", [])
56
+
57
+ def get_space(self, space_id: str) -> Optional[Dict]:
58
+ """Get specific space by ID."""
59
+ for space in self.spaces_data.get("spaces", []):
60
+ if space["id"] == space_id:
61
+ return space
62
+ return None
63
+
64
+ def create_space(self, name: str, description: str = "") -> Dict:
65
+ """Create a new space."""
66
+ space_id = name.lower().replace(" ", "_")
67
+
68
+ # Check if space already exists
69
+ if self.get_space(space_id):
70
+ raise ValueError(f"Space '{name}' already exists")
71
+
72
+ new_space = {
73
+ "id": space_id,
74
+ "name": name,
75
+ "description": description,
76
+ "created_at": datetime.now().isoformat(),
77
+ "file_count": 0,
78
+ "chat_count": 0
79
+ }
80
+
81
+ self.spaces_data["spaces"].append(new_space)
82
+ self.save_spaces()
83
+
84
+ # Create dedicated directories for this space
85
+ space_dir = config.DATA_DIR / "spaces" / space_id
86
+ space_dir.mkdir(parents=True, exist_ok=True)
87
+ (space_dir / "chats").mkdir(exist_ok=True)
88
+ (space_dir / "vector_db").mkdir(exist_ok=True)
89
+ (space_dir / "uploads").mkdir(exist_ok=True)
90
+
91
+ return new_space
92
+
93
+ def delete_space(self, space_id: str):
94
+ """Delete a space (except General)."""
95
+ if space_id == "general":
96
+ raise ValueError("Cannot delete General space")
97
+
98
+ self.spaces_data["spaces"] = [
99
+ s for s in self.spaces_data["spaces"]
100
+ if s["id"] != space_id
101
+ ]
102
+ self.save_spaces()
103
+
104
+ def update_space_counts(self, space_id: str, file_count: int = None, chat_count: int = None):
105
+ """Update file/chat counts for a space."""
106
+ space = self.get_space(space_id)
107
+ if space:
108
+ if file_count is not None:
109
+ space["file_count"] = file_count
110
+ if chat_count is not None:
111
+ space["chat_count"] = chat_count
112
+ self.save_spaces()
113
+
114
+ def get_space_chats_dir(self, space_id: str) -> Path:
115
+ """Get chats directory for a space."""
116
+ return config.DATA_DIR / "spaces" / space_id / "chats"
117
+
118
+ def get_space_vector_db_dir(self, space_id: str) -> Path:
119
+ """Get vector DB directory for a space."""
120
+ return config.DATA_DIR / "spaces" / space_id / "vector_db"
121
+
122
+ def get_space_uploads_dir(self, space_id: str) -> Path:
123
+ """Get uploads directory for a space."""
124
+ return config.DATA_DIR / "spaces" / space_id / "uploads"
utils/studio_generator.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Studio Generator - Uses LLM to generate flashcards and quiz questions
3
+ """
4
+ from typing import List, Optional
5
+ import json
6
+ import re
7
+
8
+ from models.studio_models import (
9
+ Flashcard, FlashcardCreate, FlashcardGenerateRequest,
10
+ Quiz, QuizQuestion, QuizGenerateRequest,
11
+ DifficultyLevel, QuestionType
12
+ )
13
+ from utils.llm_generator import LLMGenerator
14
+ from utils.studio_manager import StudioManager
15
+
16
+
17
+ class StudioGenerator:
18
+ """Generate flashcards and quizzes using LLM"""
19
+
20
+ def __init__(self, llm_generator: LLMGenerator, studio_manager: StudioManager):
21
+ self.llm = llm_generator
22
+ self.studio = studio_manager
23
+
24
+ async def generate_flashcards(self, request: FlashcardGenerateRequest) -> List[Flashcard]:
25
+ """Generate flashcards from content using LLM"""
26
+
27
+ # Gather source content
28
+ content = await self._gather_content(
29
+ request.space_id,
30
+ request.source_type,
31
+ request.source_ids,
32
+ request.text_content
33
+ )
34
+
35
+ if not content:
36
+ return []
37
+
38
+ # Create prompt for LLM
39
+ prompt = self._create_flashcard_prompt(content, request.num_cards, request.difficulty)
40
+
41
+ # Generate flashcards using LLM
42
+ response = await self.llm.generate(prompt, max_tokens=2000)
43
+
44
+ if not response:
45
+ return []
46
+
47
+ # Parse flashcards from response
48
+ flashcards = self._parse_flashcards(
49
+ response,
50
+ request.space_id,
51
+ request.source_type,
52
+ request.source_ids,
53
+ request.difficulty
54
+ )
55
+
56
+ # Save flashcards to storage
57
+ saved_cards = []
58
+ for card_data in flashcards:
59
+ card = self.studio.create_flashcard(card_data)
60
+ saved_cards.append(card)
61
+
62
+ return saved_cards
63
+
64
+ async def generate_quiz(self, request: QuizGenerateRequest) -> Optional[Quiz]:
65
+ """Generate a quiz from content using LLM"""
66
+
67
+ # Gather source content
68
+ content = await self._gather_content(
69
+ request.space_id,
70
+ request.source_type,
71
+ request.source_ids,
72
+ request.text_content
73
+ )
74
+
75
+ if not content:
76
+ return None
77
+
78
+ # Create prompt for LLM
79
+ prompt = self._create_quiz_prompt(
80
+ content,
81
+ request.num_questions,
82
+ request.question_types,
83
+ request.difficulty
84
+ )
85
+
86
+ # Generate quiz using LLM
87
+ response = await self.llm.generate(prompt, max_tokens=3000)
88
+
89
+ if not response:
90
+ return None
91
+
92
+ # Parse quiz questions from response
93
+ questions = self._parse_quiz_questions(response, request.question_types, request.difficulty)
94
+
95
+ if not questions:
96
+ return None
97
+
98
+ # Create quiz
99
+ from models.studio_models import QuizCreate
100
+ quiz_data = QuizCreate(
101
+ space_id=request.space_id,
102
+ title=request.title,
103
+ description=f"Generated quiz with {len(questions)} questions",
104
+ questions=questions,
105
+ source_type=request.source_type,
106
+ source_ids=request.source_ids
107
+ )
108
+
109
+ quiz = self.studio.create_quiz(quiz_data)
110
+ return quiz
111
+
112
+ async def _gather_content(
113
+ self,
114
+ space_id: str,
115
+ source_type: str,
116
+ source_ids: Optional[List[str]],
117
+ text_content: Optional[str]
118
+ ) -> str:
119
+ """Gather content from various sources"""
120
+
121
+ if text_content:
122
+ return text_content
123
+
124
+ content_parts = []
125
+
126
+ if source_type == "notebook" and source_ids:
127
+ # Get notebook entries
128
+ for entry_id in source_ids:
129
+ entry = self.studio.get_notebook_entry(entry_id)
130
+ if entry:
131
+ content_parts.append(f"# {entry.title}\n\n{entry.content}")
132
+
133
+ elif source_type == "file" and source_ids:
134
+ # TODO: Integrate with file retriever to get file content
135
+ # For now, just return a placeholder
136
+ content_parts.append("File content retrieval not yet implemented")
137
+
138
+ return "\n\n---\n\n".join(content_parts)
139
+
140
+ def _create_flashcard_prompt(self, content: str, num_cards: int, difficulty: DifficultyLevel) -> str:
141
+ """Create prompt for flashcard generation based on user plan"""
142
+
143
+ prompt = f"""From the following study note, extract {num_cards} flashcards.
144
+ Each flashcard must have:
145
+ - A concise question (front)
146
+ - A precise answer (max 3 sentences) (back)
147
+ - A difficulty tag: easy / medium / hard
148
+ - A topic tag matching the concept covered
149
+
150
+ Return ONLY valid JSON, no markdown:
151
+ {{
152
+ "flashcards": [
153
+ {{
154
+ "question": "What is the naive assumption in Naive Bayes?",
155
+ "answer": "Every feature is entirely independent of every other feature given the class label.",
156
+ "difficulty": "medium",
157
+ "topic": "Naive Bayes"
158
+ }}
159
+ ]
160
+ }}
161
+
162
+ Note content:
163
+ {content[:4000]}
164
+ """
165
+ return prompt
166
+
167
+ def _create_quiz_prompt(
168
+ self,
169
+ content: str,
170
+ num_questions: int,
171
+ question_types: List[QuestionType],
172
+ difficulty: DifficultyLevel
173
+ ) -> str:
174
+ """Create prompt for quiz generation"""
175
+
176
+ types_str = ", ".join(qt.value for qt in question_types)
177
+
178
+ prompt = f"""Based on the following content, create a quiz with {num_questions} questions.
179
+
180
+ Content:
181
+ {content[:3000]} # Limit content length
182
+
183
+ Question types to include: {types_str}
184
+ Difficulty level: {difficulty.value}
185
+
186
+ Format your response as a JSON array of questions, where each question has:
187
+ - "question": The question text
188
+ - "type": One of: {types_str}
189
+ - "options": Array of 4 options (for multiple_choice only)
190
+ - "correct_answer": The correct answer
191
+ - "explanation": Brief explanation of why this is correct
192
+
193
+ Example format:
194
+ [
195
+ {{
196
+ "question": "What is...",
197
+ "type": "multiple_choice",
198
+ "options": ["Option A", "Option B", "Option C", "Option D"],
199
+ "correct_answer": "Option A",
200
+ "explanation": "This is correct because..."
201
+ }},
202
+ {{
203
+ "question": "True or False: ...",
204
+ "type": "true_false",
205
+ "options": ["True", "False"],
206
+ "correct_answer": "True",
207
+ "explanation": "This is true because..."
208
+ }}
209
+ ]
210
+
211
+ Generate exactly {num_questions} questions:"""
212
+
213
+ return prompt
214
+
215
+ def _parse_flashcards(
216
+ self,
217
+ response: str,
218
+ space_id: str,
219
+ source_type: str,
220
+ source_ids: Optional[List[str]],
221
+ difficulty: DifficultyLevel
222
+ ) -> List[FlashcardCreate]:
223
+ """Parse flashcards from LLM response"""
224
+
225
+ flashcards = []
226
+
227
+ try:
228
+ # Try to extract JSON from response (look for the "flashcards" array or direct array)
229
+ json_match = re.search(r'\{[\s\S]*"flashcards"[\s\S]*\}', response)
230
+ if json_match:
231
+ data = json.loads(json_match.group(0))
232
+ cards_data = data.get("flashcards", [])
233
+ else:
234
+ # Fallback to pure array
235
+ json_match = re.search(r'\[[\s\S]*\]', response)
236
+ cards_data = json.loads(json_match.group(0)) if json_match else []
237
+
238
+ for card_data in cards_data:
239
+ if 'question' in card_data and 'answer' in card_data:
240
+ # map the returned difficulty string to enum if possible
241
+ diff_val = card_data.get('difficulty', difficulty.value)
242
+ try:
243
+ parsed_diff = DifficultyLevel(diff_val.lower())
244
+ except ValueError:
245
+ parsed_diff = difficulty
246
+
247
+ flashcards.append(FlashcardCreate(
248
+ space_id=space_id,
249
+ question=card_data['question'],
250
+ answer=card_data['answer'],
251
+ difficulty=parsed_diff,
252
+ source_type=source_type,
253
+ source_id=source_ids[0] if source_ids else None,
254
+ metadata={"topic": card_data.get('topic', '')}
255
+ ))
256
+ except Exception as e:
257
+ print(f"Error parsing flashcards: {e}")
258
+ # Fallback: Try to parse as simple Q&A pairs
259
+ lines = response.split('\n')
260
+ current_question = None
261
+
262
+ for line in lines:
263
+ line = line.strip()
264
+ if line.startswith('Q:') or line.startswith('Question:'):
265
+ current_question = line.split(':', 1)[1].strip()
266
+ elif line.startswith('A:') or line.startswith('Answer:'):
267
+ if current_question:
268
+ flashcards.append(FlashcardCreate(
269
+ space_id=space_id,
270
+ question=current_question,
271
+ answer=answer,
272
+ difficulty=difficulty,
273
+ source_type=source_type,
274
+ source_id=source_ids[0] if source_ids else None
275
+ ))
276
+ current_question = None
277
+
278
+ return flashcards
279
+
280
+ def _parse_quiz_questions(
281
+ self,
282
+ response: str,
283
+ question_types: List[QuestionType],
284
+ difficulty: DifficultyLevel
285
+ ) -> List[QuizQuestion]:
286
+ """Parse quiz questions from LLM response"""
287
+
288
+ questions = []
289
+
290
+ try:
291
+ # Try to extract JSON from response
292
+ json_match = re.search(r'\[[\s\S]*\]', response)
293
+ if json_match:
294
+ questions_data = json.loads(json_match.group(0))
295
+
296
+ for idx, q_data in enumerate(questions_data):
297
+ import uuid
298
+
299
+ # Parse question type
300
+ q_type = QuestionType.MULTIPLE_CHOICE
301
+ if 'type' in q_data:
302
+ try:
303
+ q_type = QuestionType(q_data['type'])
304
+ except ValueError:
305
+ q_type = QuestionType.MULTIPLE_CHOICE
306
+
307
+ questions.append(QuizQuestion(
308
+ id=str(uuid.uuid4()),
309
+ question=q_data.get('question', ''),
310
+ type=q_type,
311
+ options=q_data.get('options'),
312
+ correct_answer=q_data.get('correct_answer', ''),
313
+ explanation=q_data.get('explanation'),
314
+ points=1,
315
+ difficulty=difficulty
316
+ ))
317
+ except Exception as e:
318
+ print(f"Error parsing quiz questions: {e}")
319
+
320
+ return questions
utils/studio_manager.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Studio Manager - Handles Notebook, Flashcards, and Quiz storage and operations
3
+ """
4
+ import json
5
+ from pathlib import Path
6
+ from typing import List, Optional, Dict, Any
7
+ from datetime import datetime, timedelta
8
+ import uuid
9
+
10
+ from models.studio_models import (
11
+ NotebookEntry, NotebookEntryCreate, NotebookEntryUpdate,
12
+ Flashcard, FlashcardCreate, FlashcardUpdate, FlashcardReview,
13
+ Quiz, QuizCreate, QuizResult, QuizHistory, QuizAnswer,
14
+ MasteryLevel, DifficultyLevel
15
+ )
16
+ import config
17
+
18
+
19
+ class StudioManager:
20
+ """Manages all Studio features: Notebook, Flashcards, Quiz"""
21
+
22
+ def __init__(self):
23
+ """Initialize studio manager with data directories"""
24
+ self.studio_dir = config.DATA_DIR / "studio"
25
+ self.notebooks_dir = self.studio_dir / "notebooks"
26
+ self.notebook_dir = self.studio_dir / "notebook"
27
+ self.flashcards_dir = self.studio_dir / "flashcards"
28
+ self.quizzes_dir = self.studio_dir / "quizzes"
29
+ self.quiz_results_dir = self.studio_dir / "quiz_results"
30
+
31
+ # Create directories
32
+ for directory in [self.notebooks_dir, self.notebook_dir, self.flashcards_dir,
33
+ self.quizzes_dir, self.quiz_results_dir]:
34
+ directory.mkdir(parents=True, exist_ok=True)
35
+
36
+ def _get_notebook_file_path(self, space_id: str) -> Path:
37
+ """Get the metadata file path for a space notebook."""
38
+ return self.notebooks_dir / f"{space_id}.json"
39
+
40
+ def ensure_space_notebook(self, space_id: str, space_name: str = "") -> Dict[str, Any]:
41
+ """Create notebook metadata for a space if it does not exist."""
42
+ file_path = self._get_notebook_file_path(space_id)
43
+
44
+ if file_path.exists():
45
+ with open(file_path, 'r', encoding='utf-8') as f:
46
+ return json.load(f)
47
+
48
+ now = datetime.now().isoformat()
49
+ notebook_name = space_name.strip() if space_name and space_name.strip() else space_id
50
+ notebook_data = {
51
+ "id": space_id,
52
+ "space_id": space_id,
53
+ "name": notebook_name,
54
+ "created_at": now,
55
+ "updated_at": now
56
+ }
57
+
58
+ with open(file_path, 'w', encoding='utf-8') as f:
59
+ json.dump(notebook_data, f, indent=2)
60
+
61
+ return notebook_data
62
+
63
+ def get_space_notebook(self, space_id: str) -> Optional[Dict[str, Any]]:
64
+ """Get notebook metadata for a specific space."""
65
+ file_path = self._get_notebook_file_path(space_id)
66
+ if not file_path.exists():
67
+ return None
68
+
69
+ with open(file_path, 'r', encoding='utf-8') as f:
70
+ return json.load(f)
71
+
72
+ def _derive_title_from_question(self, question: str) -> str:
73
+ """Generate a readable title from a chat question."""
74
+ question = (question or "").strip()
75
+ if not question:
76
+ return "Chat Note"
77
+
78
+ # Keep full question text; UI can visually truncate as needed.
79
+ return question.replace('\n', ' ').strip()
80
+
81
+ # ========================================================================
82
+ # NOTEBOOK OPERATIONS
83
+ # ========================================================================
84
+
85
+ def create_notebook_entry(self, entry_data: NotebookEntryCreate) -> NotebookEntry:
86
+ """Create a new notebook entry"""
87
+ # Ensure a notebook record exists for this space.
88
+ self.ensure_space_notebook(entry_data.space_id)
89
+
90
+ entry = NotebookEntry(
91
+ id=str(uuid.uuid4()),
92
+ **entry_data.dict()
93
+ )
94
+
95
+ # Save to file
96
+ file_path = self.notebook_dir / f"{entry.id}.json"
97
+ with open(file_path, 'w', encoding='utf-8') as f:
98
+ json.dump(entry.dict(), f, indent=2, default=str)
99
+
100
+ return entry
101
+
102
+ def create_notebook_entry_from_chat(
103
+ self,
104
+ space_id: str,
105
+ question: str,
106
+ answer: str,
107
+ chat_id: Optional[str] = None,
108
+ assistant_timestamp: Optional[str] = None,
109
+ tags: Optional[List[str]] = None,
110
+ space_name: str = ""
111
+ ) -> NotebookEntry:
112
+ """Create a notebook entry from a chat Q/A pair."""
113
+ self.ensure_space_notebook(space_id, space_name=space_name)
114
+
115
+ metadata: Dict[str, Any] = {
116
+ "question": question,
117
+ "assistant_timestamp": assistant_timestamp,
118
+ }
119
+ if chat_id:
120
+ metadata["chat_id"] = chat_id
121
+
122
+ entry_data = NotebookEntryCreate(
123
+ space_id=space_id,
124
+ title=self._derive_title_from_question(question),
125
+ content=f"Q: {question.strip()}\n\nA: {answer.strip()}",
126
+ source_type="chat",
127
+ source_id=chat_id,
128
+ tags=tags or ["chat"],
129
+ metadata=metadata
130
+ )
131
+
132
+ entry = self.create_notebook_entry(entry_data)
133
+
134
+ # Update notebook metadata timestamp.
135
+ notebook_data = self.ensure_space_notebook(space_id, space_name=space_name)
136
+ notebook_data["updated_at"] = datetime.now().isoformat()
137
+ with open(self._get_notebook_file_path(space_id), 'w', encoding='utf-8') as f:
138
+ json.dump(notebook_data, f, indent=2)
139
+
140
+ return entry
141
+
142
+ def get_notebook_entry(self, entry_id: str) -> Optional[NotebookEntry]:
143
+ """Get a single notebook entry by ID"""
144
+ file_path = self.notebook_dir / f"{entry_id}.json"
145
+ if not file_path.exists():
146
+ return None
147
+
148
+ with open(file_path, 'r', encoding='utf-8') as f:
149
+ data = json.load(f)
150
+
151
+ return NotebookEntry(**data)
152
+
153
+ def list_notebook_entries(self, space_id: Optional[str] = None) -> List[NotebookEntry]:
154
+ """List all notebook entries, optionally filtered by space"""
155
+ entries = []
156
+
157
+ for file_path in self.notebook_dir.glob("*.json"):
158
+ try:
159
+ with open(file_path, 'r', encoding='utf-8') as f:
160
+ data = json.load(f)
161
+
162
+ entry = NotebookEntry(**data)
163
+
164
+ # Filter by space if specified
165
+ if space_id is None or entry.space_id == space_id:
166
+ entries.append(entry)
167
+ except Exception as e:
168
+ print(f"Error loading notebook entry {file_path}: {e}")
169
+
170
+ # Sort by updated_at descending
171
+ entries.sort(key=lambda x: x.updated_at, reverse=True)
172
+ return entries
173
+
174
+ def update_notebook_entry(self, entry_id: str, update_data: NotebookEntryUpdate) -> Optional[NotebookEntry]:
175
+ """Update an existing notebook entry"""
176
+ entry = self.get_notebook_entry(entry_id)
177
+ if not entry:
178
+ return None
179
+
180
+ # Update fields
181
+ update_dict = update_data.dict(exclude_unset=True)
182
+ for key, value in update_dict.items():
183
+ setattr(entry, key, value)
184
+
185
+ entry.updated_at = datetime.now()
186
+
187
+ # Save
188
+ file_path = self.notebook_dir / f"{entry_id}.json"
189
+ with open(file_path, 'w', encoding='utf-8') as f:
190
+ json.dump(entry.dict(), f, indent=2, default=str)
191
+
192
+ return entry
193
+
194
+ def delete_notebook_entry(self, entry_id: str) -> bool:
195
+ """Delete a notebook entry"""
196
+ file_path = self.notebook_dir / f"{entry_id}.json"
197
+ if file_path.exists():
198
+ file_path.unlink()
199
+ return True
200
+ return False
201
+
202
+ # ========================================================================
203
+ # FLASHCARD OPERATIONS
204
+ # ========================================================================
205
+
206
+ def create_flashcard(self, card_data: FlashcardCreate) -> Flashcard:
207
+ """Create a new flashcard"""
208
+ card = Flashcard(
209
+ id=str(uuid.uuid4()),
210
+ **card_data.dict()
211
+ )
212
+
213
+ # Save to file
214
+ file_path = self.flashcards_dir / f"{card.id}.json"
215
+ with open(file_path, 'w', encoding='utf-8') as f:
216
+ json.dump(card.dict(), f, indent=2, default=str)
217
+
218
+ return card
219
+
220
+ def get_flashcard(self, card_id: str) -> Optional[Flashcard]:
221
+ """Get a single flashcard by ID"""
222
+ file_path = self.flashcards_dir / f"{card_id}.json"
223
+ if not file_path.exists():
224
+ return None
225
+
226
+ with open(file_path, 'r', encoding='utf-8') as f:
227
+ data = json.load(f)
228
+
229
+ return Flashcard(**data)
230
+
231
+ def list_flashcards(self, space_id: Optional[str] = None,
232
+ mastery: Optional[MasteryLevel] = None) -> List[Flashcard]:
233
+ """List all flashcards, optionally filtered"""
234
+ cards = []
235
+
236
+ for file_path in self.flashcards_dir.glob("*.json"):
237
+ try:
238
+ with open(file_path, 'r', encoding='utf-8') as f:
239
+ data = json.load(f)
240
+
241
+ card = Flashcard(**data)
242
+
243
+ # Apply filters
244
+ if space_id and card.space_id != space_id:
245
+ continue
246
+ if mastery and card.mastery != mastery:
247
+ continue
248
+
249
+ cards.append(card)
250
+ except Exception as e:
251
+ print(f"Error loading flashcard {file_path}: {e}")
252
+
253
+ # Sort by next_review date (cards due for review first)
254
+ cards.sort(key=lambda x: x.next_review or datetime.now())
255
+ return cards
256
+
257
+ def update_flashcard(self, card_id: str, update_data: FlashcardUpdate) -> Optional[Flashcard]:
258
+ """Update a flashcard"""
259
+ card = self.get_flashcard(card_id)
260
+ if not card:
261
+ return None
262
+
263
+ # Update fields
264
+ update_dict = update_data.dict(exclude_unset=True)
265
+ for key, value in update_dict.items():
266
+ setattr(card, key, value)
267
+
268
+ # Save
269
+ file_path = self.flashcards_dir / f"{card_id}.json"
270
+ with open(file_path, 'w', encoding='utf-8') as f:
271
+ json.dump(card.dict(), f, indent=2, default=str)
272
+
273
+ return card
274
+
275
+ def review_flashcard(self, card_id: str, review: FlashcardReview) -> Optional[Flashcard]:
276
+ """Record a flashcard review and update using SM-2 spaced repetition"""
277
+ card = self.get_flashcard(card_id)
278
+ if not card:
279
+ return None
280
+
281
+ # Update basic review stats
282
+ card.review_count += 1
283
+ if review.quality >= 3:
284
+ card.correct_count += 1
285
+
286
+ today = datetime.now()
287
+ card.last_reviewed = today
288
+
289
+ # SM-2 Algorithm implementation
290
+ quality = review.quality
291
+
292
+ if quality < 3:
293
+ card.interval = 1 # show again tomorrow
294
+ card.repetitions = 0
295
+
296
+ # Downgrade mastery based on failure
297
+ if card.mastery == MasteryLevel.MASTERED:
298
+ card.mastery = MasteryLevel.REVIEWING
299
+ else:
300
+ card.mastery = MasteryLevel.LEARNING
301
+ else:
302
+ if card.repetitions == 0:
303
+ card.interval = 1
304
+ elif card.repetitions == 1:
305
+ card.interval = 6
306
+ else:
307
+ card.interval = round(card.interval * card.ease_factor)
308
+ card.repetitions += 1
309
+
310
+ # Upgrade mastery based on string of consecutive successes
311
+ if card.repetitions >= 4:
312
+ card.mastery = MasteryLevel.MASTERED
313
+ elif card.repetitions >= 2:
314
+ card.mastery = MasteryLevel.REVIEWING
315
+ else:
316
+ card.mastery = MasteryLevel.LEARNING
317
+
318
+ # Adjust ease factor
319
+ card.ease_factor = max(1.3, card.ease_factor + 0.1 - (5 - quality) * 0.08)
320
+ card.next_review = today + timedelta(days=card.interval)
321
+
322
+ # Save
323
+ file_path = self.flashcards_dir / f"{card_id}.json"
324
+ with open(file_path, 'w', encoding='utf-8') as f:
325
+ json.dump(card.dict(), f, indent=2, default=str)
326
+
327
+ return card
328
+
329
+ def delete_flashcard(self, card_id: str) -> bool:
330
+ """Delete a flashcard"""
331
+ file_path = self.flashcards_dir / f"{card_id}.json"
332
+ if file_path.exists():
333
+ file_path.unlink()
334
+ return True
335
+ return False
336
+
337
+ # ========================================================================
338
+ # QUIZ OPERATIONS
339
+ # ========================================================================
340
+
341
+ def create_quiz(self, quiz_data: QuizCreate) -> Quiz:
342
+ """Create a new quiz"""
343
+ quiz = Quiz(
344
+ id=str(uuid.uuid4()),
345
+ **quiz_data.dict()
346
+ )
347
+
348
+ # Save to file
349
+ file_path = self.quizzes_dir / f"{quiz.id}.json"
350
+ with open(file_path, 'w', encoding='utf-8') as f:
351
+ json.dump(quiz.dict(), f, indent=2, default=str)
352
+
353
+ return quiz
354
+
355
+ def get_quiz(self, quiz_id: str) -> Optional[Quiz]:
356
+ """Get a quiz by ID"""
357
+ file_path = self.quizzes_dir / f"{quiz_id}.json"
358
+ if not file_path.exists():
359
+ return None
360
+
361
+ with open(file_path, 'r', encoding='utf-8') as f:
362
+ data = json.load(f)
363
+
364
+ return Quiz(**data)
365
+
366
+ def list_quizzes(self, space_id: Optional[str] = None) -> List[Quiz]:
367
+ """List all quizzes, optionally filtered by space"""
368
+ quizzes = []
369
+
370
+ for file_path in self.quizzes_dir.glob("*.json"):
371
+ try:
372
+ with open(file_path, 'r', encoding='utf-8') as f:
373
+ data = json.load(f)
374
+
375
+ quiz = Quiz(**data)
376
+
377
+ if space_id is None or quiz.space_id == space_id:
378
+ quizzes.append(quiz)
379
+ except Exception as e:
380
+ print(f"Error loading quiz {file_path}: {e}")
381
+
382
+ # Sort by created_at descending
383
+ quizzes.sort(key=lambda x: x.created_at, reverse=True)
384
+ return quizzes
385
+
386
+ def delete_quiz(self, quiz_id: str) -> bool:
387
+ """Delete a quiz"""
388
+ file_path = self.quizzes_dir / f"{quiz_id}.json"
389
+ if file_path.exists():
390
+ file_path.unlink()
391
+ return True
392
+ return False
393
+
394
+ def submit_quiz(self, quiz_id: str, answers: List[QuizAnswer]) -> Optional[QuizResult]:
395
+ """Submit quiz answers and calculate results"""
396
+ quiz = self.get_quiz(quiz_id)
397
+ if not quiz:
398
+ return None
399
+
400
+ # Create answer lookup
401
+ answer_dict = {ans.question_id: ans for ans in answers}
402
+
403
+ # Calculate results
404
+ total_points = sum(q.points for q in quiz.questions)
405
+ correct_count = 0
406
+ incorrect_count = 0
407
+ earned_points = 0
408
+ detailed_answers = []
409
+
410
+ for question in quiz.questions:
411
+ user_answer = answer_dict.get(question.id)
412
+ is_correct = False
413
+
414
+ if user_answer:
415
+ # Normalize answers for comparison
416
+ correct_ans = question.correct_answer.strip().lower()
417
+ user_ans = user_answer.answer.strip().lower()
418
+
419
+ is_correct = correct_ans == user_ans
420
+
421
+ if is_correct:
422
+ correct_count += 1
423
+ earned_points += question.points
424
+ else:
425
+ incorrect_count += 1
426
+ else:
427
+ incorrect_count += 1
428
+
429
+ detailed_answers.append({
430
+ "question_id": question.id,
431
+ "question": question.question,
432
+ "user_answer": user_answer.answer if user_answer else None,
433
+ "correct_answer": question.correct_answer,
434
+ "is_correct": is_correct,
435
+ "explanation": question.explanation,
436
+ "points": question.points if is_correct else 0
437
+ })
438
+
439
+ # Create result
440
+ result = QuizResult(
441
+ quiz_id=quiz_id,
442
+ submission_id=str(uuid.uuid4()),
443
+ total_questions=len(quiz.questions),
444
+ correct_answers=correct_count,
445
+ incorrect_answers=incorrect_count,
446
+ score_percentage=(correct_count / len(quiz.questions) * 100) if quiz.questions else 0,
447
+ total_points=total_points,
448
+ earned_points=earned_points,
449
+ answers=detailed_answers
450
+ )
451
+
452
+ # Save result
453
+ result_file = self.quiz_results_dir / f"{result.submission_id}.json"
454
+ with open(result_file, 'w', encoding='utf-8') as f:
455
+ json.dump(result.dict(), f, indent=2, default=str)
456
+
457
+ return result
458
+
459
+ def get_quiz_history(self, quiz_id: str) -> QuizHistory:
460
+ """Get quiz attempt history"""
461
+ quiz = self.get_quiz(quiz_id)
462
+ if not quiz:
463
+ return None
464
+
465
+ # Load all results for this quiz
466
+ results = []
467
+ for file_path in self.quiz_results_dir.glob("*.json"):
468
+ try:
469
+ with open(file_path, 'r', encoding='utf-8') as f:
470
+ data = json.load(f)
471
+
472
+ result = QuizResult(**data)
473
+ if result.quiz_id == quiz_id:
474
+ results.append(result)
475
+ except Exception as e:
476
+ print(f"Error loading quiz result {file_path}: {e}")
477
+
478
+ # Calculate statistics
479
+ scores = [r.score_percentage for r in results] if results else [0]
480
+
481
+ history = QuizHistory(
482
+ quiz_id=quiz_id,
483
+ space_id=quiz.space_id,
484
+ quiz_title=quiz.title,
485
+ results=results,
486
+ best_score=max(scores),
487
+ average_score=sum(scores) / len(scores) if scores else 0,
488
+ attempts_count=len(results)
489
+ )
490
+
491
+ return history
utils/vector_db.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import threading
4
+ import uuid
5
+ import warnings
6
+ from typing import Dict, List, Optional
7
+
8
+ import chromadb
9
+ from chromadb.config import Settings
10
+ from sentence_transformers import CrossEncoder, SentenceTransformer
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from transformers import AutoTokenizer, AutoModel
14
+
15
+ import config
16
+
17
+ # Suppress unnecessary warnings
18
+ warnings.filterwarnings("ignore", category=FutureWarning)
19
+ logging.getLogger("chromadb").setLevel(logging.ERROR)
20
+ logging.getLogger("sentence_transformers").setLevel(logging.WARNING)
21
+
22
+
23
+ class VectorDatabase:
24
+ """Manage vector database for document embeddings using ChromaDB."""
25
+
26
+ _embedding_model = None
27
+ _embedding_model_name = None
28
+ _embedding_model_lock = threading.Lock()
29
+ _tokenizer = None
30
+
31
+ _reranker_model = None
32
+ _reranker_model_name = None
33
+ _reranker_lock = threading.Lock()
34
+
35
+ @staticmethod
36
+ def _empty_query_result() -> Dict:
37
+ return {
38
+ "documents": [[]],
39
+ "metadatas": [[]],
40
+ "distances": [[]],
41
+ "ids": [[]],
42
+ }
43
+
44
+ @staticmethod
45
+ def _is_dimension_mismatch_error(err: Exception) -> bool:
46
+ msg = str(err).lower()
47
+ return (
48
+ ("expecting embedding with dimension" in msg and "got" in msg)
49
+ or ("does not match index dimensionality" in msg)
50
+ or ("dimensionality of" in msg and "index dimensionality" in msg)
51
+ )
52
+
53
+ @staticmethod
54
+ def _is_index_not_found_error(err: Exception) -> bool:
55
+ msg = str(err).lower()
56
+ return "index not found" in msg or "create an instance before querying" in msg
57
+
58
+ def _recreate_collection(self) -> None:
59
+ """Recreate collection to recover from stale/missing index internals."""
60
+ collection_name = self.collection.name
61
+ try:
62
+ self.client.delete_collection(name=collection_name)
63
+ except Exception:
64
+ pass
65
+
66
+ self.collection = self.client.get_or_create_collection(
67
+ name=collection_name,
68
+ metadata={"hnsw:space": "cosine"},
69
+ )
70
+
71
+ @staticmethod
72
+ def _resolve_torch_device(env_var_name: str) -> str:
73
+ """Resolve target device with optional env override."""
74
+ import torch
75
+
76
+ preference = os.getenv(env_var_name, "auto").strip().lower()
77
+ if preference == "cpu":
78
+ return "cpu"
79
+ if preference == "cuda":
80
+ return "cuda" if torch.cuda.is_available() else "cpu"
81
+ return "cuda" if torch.cuda.is_available() else "cpu"
82
+
83
+ def __init__(self, collection_name: str = "documents", persist_directory: str = None):
84
+ if persist_directory is None:
85
+ persist_directory = str(config.VECTOR_DB_DIR)
86
+
87
+ self.client = self._create_chroma_client(persist_directory)
88
+ self.collection = self.client.get_or_create_collection(
89
+ name=collection_name,
90
+ metadata={"hnsw:space": "cosine"},
91
+ )
92
+
93
+ self.embedding_model = self._get_or_create_embedding_model()
94
+
95
+ def _create_chroma_client(self, persist_directory: str):
96
+ """Create a Chroma client compatible with both legacy and modern APIs."""
97
+ if hasattr(chromadb, "PersistentClient"):
98
+ try:
99
+ return chromadb.PersistentClient(
100
+ path=persist_directory,
101
+ settings=Settings(anonymized_telemetry=False),
102
+ )
103
+ except TypeError:
104
+ return chromadb.PersistentClient(path=persist_directory)
105
+ except Exception:
106
+ pass
107
+
108
+ return chromadb.Client(
109
+ Settings(
110
+ chroma_db_impl="duckdb+parquet",
111
+ persist_directory=persist_directory,
112
+ anonymized_telemetry=False,
113
+ )
114
+ )
115
+
116
+ def ensure_collection_embedding_compatibility(self) -> bool:
117
+ """
118
+ Ensure persisted collection dimensionality matches current embedding model.
119
+
120
+ Returns:
121
+ True if collection was reset due to mismatch, else False.
122
+ """
123
+ try:
124
+ count = self.collection.count()
125
+ except Exception:
126
+ return False
127
+
128
+ try:
129
+ if count == 0:
130
+ # Query probing on empty indexes may not trigger dimension validation.
131
+ probe_id = f"_dim_probe_{uuid.uuid4().hex[:12]}"
132
+ probe_text = "embedding-dimension-probe"
133
+ probe_embedding = self._encode([probe_text])
134
+ self.collection.add(
135
+ embeddings=probe_embedding,
136
+ documents=[probe_text],
137
+ metadatas=[{"_probe": True}],
138
+ ids=[probe_id],
139
+ )
140
+ self.collection.delete(ids=[probe_id])
141
+ return False
142
+
143
+ probe = self._encode(["embedding-dimension-probe"])
144
+ self.collection.query(query_embeddings=probe, n_results=1)
145
+ return False
146
+ except Exception as e:
147
+ if not (self._is_dimension_mismatch_error(e) or self._is_index_not_found_error(e)):
148
+ raise
149
+
150
+ collection_name = self.collection.name
151
+ reason = "missing_index" if self._is_index_not_found_error(e) else "dimension_mismatch"
152
+ print(
153
+ "[VECTOR_DB] collection_incompatible "
154
+ f"reason={reason} collection={collection_name} model={config.EMBEDDING_MODEL}; resetting index"
155
+ )
156
+ self._recreate_collection()
157
+ return True
158
+
159
+ @classmethod
160
+ def _get_or_create_embedding_model(cls):
161
+ """Create embedding model once and reuse it for all vector DB instances."""
162
+ with cls._embedding_model_lock:
163
+ if cls._embedding_model is None or cls._embedding_model_name != config.EMBEDDING_MODEL:
164
+ device = cls._resolve_torch_device("EMBEDDING_DEVICE")
165
+ model_name = config.EMBEDDING_MODEL
166
+
167
+ print(f"Loading embedding model ({model_name}) on {device}...")
168
+ cls._tokenizer = None
169
+ cls._embedding_model = SentenceTransformer(
170
+ model_name,
171
+ device=device,
172
+ model_kwargs={"torch_dtype": torch.float16},
173
+ trust_remote_code=True
174
+ )
175
+ cls._embedding_model_name = model_name
176
+ print(f"Embedding model {model_name} loaded on {device}.")
177
+
178
+ return cls._embedding_model
179
+
180
+ @classmethod
181
+ def _get_or_create_reranker(cls):
182
+ """Create reranker model once and reuse it for all vector DB instances."""
183
+ target_model = getattr(config, "RERANKER_MODEL", "cross-encoder/ms-marco-MiniLM-L-12-v2")
184
+
185
+ with cls._reranker_lock:
186
+ if cls._reranker_model is None or cls._reranker_model_name != target_model:
187
+ device = cls._resolve_torch_device("RERANKER_DEVICE")
188
+ print(f"Loading reranker model ({target_model}) on {device}...")
189
+ cls._reranker_model = CrossEncoder(target_model, device=device, trust_remote_code=True, model_kwargs={"torch_dtype": torch.float16})
190
+
191
+ # Qwen3-Reranker lacks a default pad token, which breaks batch sizes > 1
192
+ if cls._reranker_model.tokenizer.pad_token is None:
193
+ cls._reranker_model.tokenizer.pad_token = cls._reranker_model.tokenizer.eos_token
194
+
195
+ cls._reranker_model_name = target_model
196
+ print(f"Reranker model {target_model} loaded on {device}.")
197
+
198
+ return cls._reranker_model
199
+
200
+ @classmethod
201
+ def clear_runtime_caches(cls, unload_embedding_model: bool = False):
202
+ """Best-effort cleanup for GPU/CPU caches between large space workloads."""
203
+ try:
204
+ import gc
205
+
206
+ gc.collect()
207
+ except Exception:
208
+ pass
209
+
210
+ try:
211
+ import torch
212
+
213
+ if unload_embedding_model and cls._embedding_model is not None:
214
+ try:
215
+ cls._embedding_model.to("cpu")
216
+ except Exception:
217
+ pass
218
+
219
+ try:
220
+ if cls._reranker_model is not None and hasattr(cls._reranker_model, "model"):
221
+ cls._reranker_model.model.to("cpu")
222
+ except Exception:
223
+ pass
224
+
225
+ cls._embedding_model = None
226
+ cls._embedding_model_name = None
227
+ cls._reranker_model = None
228
+ cls._reranker_model_name = None
229
+
230
+ if torch.cuda.is_available():
231
+ torch.cuda.empty_cache()
232
+ if hasattr(torch.cuda, "ipc_collect"):
233
+ torch.cuda.ipc_collect()
234
+ except Exception:
235
+ pass
236
+
237
+ def _embedding_batch_size(self) -> int:
238
+ """Embedding batch size tuned for low-VRAM GPUs with env override."""
239
+ if getattr(config, "EMBEDDING_BATCH_SIZE", 0) > 0:
240
+ return int(config.EMBEDDING_BATCH_SIZE)
241
+
242
+ model_name = (config.EMBEDDING_MODEL or "").lower()
243
+ if "nomic-embed-text" in model_name:
244
+ return 32
245
+ if "bge-m3" in model_name:
246
+ return 16
247
+ if "bge-large" in model_name:
248
+ return 24
249
+ return 64
250
+
251
+ def _reranker_batch_size(self) -> int:
252
+ if getattr(config, "RERANKER_BATCH_SIZE", 0) > 0:
253
+ return int(config.RERANKER_BATCH_SIZE)
254
+ return 16
255
+
256
+ def _encode(self, texts: list, instruction: str = None) -> list:
257
+ """Encode texts using SentenceTransformer."""
258
+ if instruction:
259
+ texts = [f"Instruct: {instruction}\nQuery: {t}" for t in texts]
260
+
261
+ batch_size = self._embedding_batch_size()
262
+
263
+ embeddings = self.embedding_model.encode(
264
+ texts,
265
+ batch_size=batch_size,
266
+ show_progress_bar=False,
267
+ convert_to_tensor=False,
268
+ normalize_embeddings=True
269
+ )
270
+ return embeddings.tolist()
271
+
272
+ def add_documents(self, texts: List[str], metadatas: List[Dict], ids: List[str]):
273
+ """Embed documents — no instruction prefix for docs."""
274
+ if not texts:
275
+ return
276
+
277
+ # Documents are encoded WITHOUT instruction
278
+ embeddings = self._encode(texts)
279
+
280
+ try:
281
+ self.collection.add(
282
+ embeddings=embeddings,
283
+ documents=texts,
284
+ metadatas=metadatas,
285
+ ids=ids,
286
+ )
287
+ except Exception as e:
288
+ if not (self._is_dimension_mismatch_error(e) or self._is_index_not_found_error(e)):
289
+ raise
290
+
291
+ # Auto-recover from stale dimensionality or missing collection index internals.
292
+ collection_name = self.collection.name
293
+ reason = "missing_index" if self._is_index_not_found_error(e) else "dimension_mismatch"
294
+ print(
295
+ "[VECTOR_DB] add_recover "
296
+ f"reason={reason} collection={collection_name} model={config.EMBEDDING_MODEL}; resetting index and retrying"
297
+ )
298
+ self._recreate_collection()
299
+ self.collection.add(
300
+ embeddings=embeddings,
301
+ documents=texts,
302
+ metadatas=metadatas,
303
+ ids=ids,
304
+ )
305
+
306
+ if hasattr(self.client, "persist"):
307
+ self.client.persist()
308
+
309
+ def query(self, query_text: str, n_results: int = 20, filter_dict: Optional[Dict] = None) -> Dict:
310
+ """Embed query WITH instruction for better retrieval."""
311
+ try:
312
+ if self.collection.count() == 0:
313
+ return self._empty_query_result()
314
+ except Exception:
315
+ pass
316
+
317
+ instruction = (
318
+ "Given a student's question, retrieve relevant passages "
319
+ "from academic textbooks that answer the question"
320
+ )
321
+ query_embedding = self._encode([query_text], instruction=instruction)
322
+
323
+ try:
324
+ return self.collection.query(
325
+ query_embeddings=query_embedding,
326
+ n_results=n_results,
327
+ where=filter_dict,
328
+ )
329
+ except Exception as e:
330
+ if "index not found" in str(e).lower() or "create an instance" in str(e).lower():
331
+ return self._empty_query_result()
332
+
333
+ if self._is_dimension_mismatch_error(e):
334
+ print(
335
+ "[VECTOR_DB] query_dimension_mismatch "
336
+ f"model={config.EMBEDDING_MODEL}; returning empty results"
337
+ )
338
+ return self._empty_query_result()
339
+ raise
340
+
341
+ def query_and_rerank(
342
+ self,
343
+ query_text: str,
344
+ n_retrieve: int = 20,
345
+ n_final: int = 6,
346
+ filter_dict: Optional[Dict] = None,
347
+ ) -> Dict:
348
+ """Two-stage retrieval: dense retrieval in Chroma followed by reranking."""
349
+ raw = self.query(query_text=query_text, n_results=n_retrieve, filter_dict=filter_dict)
350
+
351
+ docs = raw.get("documents", [[]])[0]
352
+ metadatas = raw.get("metadatas", [[]])[0]
353
+ distances = raw.get("distances", [[]])[0]
354
+ ids = raw.get("ids", [[]])[0]
355
+
356
+ if not docs:
357
+ return raw
358
+
359
+ reranker = self._get_or_create_reranker()
360
+ pairs = [[query_text, doc] for doc in docs]
361
+ scores = reranker.predict(
362
+ pairs,
363
+ batch_size=self._reranker_batch_size(),
364
+ show_progress_bar=False,
365
+ )
366
+
367
+ # Qwen3 outputs raw logits (e.g. -11 to +8). Convert them to 0-1 probabilities for the UI.
368
+ scores = torch.sigmoid(torch.tensor(list(scores))).tolist()
369
+ scores = [float(s) for s in scores]
370
+
371
+ ranked = sorted(
372
+ zip(scores, docs, metadatas, distances, ids),
373
+ key=lambda x: x[0],
374
+ reverse=True,
375
+ )[: max(1, n_final)]
376
+
377
+ scores_out, docs_out, metas_out, dists_out, ids_out = zip(*ranked)
378
+ return {
379
+ "documents": [list(docs_out)],
380
+ "metadatas": [list(metas_out)],
381
+ "distances": [list(dists_out)],
382
+ "ids": [list(ids_out)],
383
+ "reranker_scores": [list(scores_out)],
384
+ }
385
+
386
+ def delete_collection(self):
387
+ """Delete the entire collection."""
388
+ self.client.delete_collection(name=self.collection.name)
389
+
390
+ def get_collection_count(self) -> int:
391
+ """Get the number of documents in the collection."""
392
+ return self.collection.count()
393
+
394
+ def get_all_documents(self) -> tuple[List[str], List[Dict]]:
395
+ """Get all documents and metadata from the collection."""
396
+ count = self.collection.count()
397
+ if count == 0:
398
+ return [], []
399
+
400
+ results = self.collection.get()
401
+ return results.get("documents", []), results.get("metadatas", [])
402
+
403
+ def create_space_collection(self, space_name: str):
404
+ """Create a new collection for a specific subject space."""
405
+ return self.client.get_or_create_collection(
406
+ name=f"space_{space_name}",
407
+ metadata={"hnsw:space": "cosine"},
408
+ )