Spaces:
Running
Running
Upload 20 files
Browse files- CUSTOM_QUIZ_DEPLOYMENT.md +65 -0
- Dockerfile +1 -1
- Dockerfile.custom_quiz +28 -0
- app.py +488 -0
- config.py +105 -0
- custom_quiz/__init__.py +1 -0
- custom_quiz/__pycache__/parser.cpython-313.pyc +0 -0
- custom_quiz/__pycache__/search.cpython-313.pyc +0 -0
- custom_quiz/cache.py +36 -0
- custom_quiz/config.py +114 -0
- custom_quiz/index_manager.py +374 -0
- custom_quiz/lexical.py +83 -0
- custom_quiz/parser.py +120 -0
- custom_quiz/search.py +287 -0
- custom_quiz_app.py +243 -0
- rag_components.py +454 -0
- requirements.txt +20 -0
- scripts/export_quiz_questions.py +119 -0
- shared_models.py +119 -0
- sources/custom_quiz/aliases.json +3 -0
CUSTOM_QUIZ_DEPLOYMENT.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Custom Topic Quiz Retrieval Deployment
|
| 2 |
+
|
| 3 |
+
This service is a separate deployment from the existing knowledge/FAQ API. It
|
| 4 |
+
shares repository code and Python dependencies, but has a separate process,
|
| 5 |
+
URL, index directory, health endpoint, credentials, and Dockerfile.
|
| 6 |
+
|
| 7 |
+
## 1. Export the source CSV
|
| 8 |
+
|
| 9 |
+
Run the offline export job with service-role credentials in the export job only:
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
export QUIZ_EXPORT_SUPABASE_URL="https://supabase.example.com"
|
| 13 |
+
export QUIZ_EXPORT_SERVICE_ROLE_KEY="..."
|
| 14 |
+
export QUIZ_EXPORT_OUTPUT="sources/custom_quiz/quiz_questions.csv"
|
| 15 |
+
python scripts/export_quiz_questions.py
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
Upload the resulting CSV to the dedicated Google Drive file used by
|
| 19 |
+
`QUIZ_CSV_URL`. The CSV contains no options, answers, hints, or explanations.
|
| 20 |
+
|
| 21 |
+
## 2. Build and run the separate API
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
docker build -f Dockerfile.custom_quiz -t sealednectar-custom-quiz-rag .
|
| 25 |
+
docker run --rm -p 7861:7861 --env-file .env.custom_quiz sealednectar-custom-quiz-rag
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
The initial deployment either loads a valid active index or downloads and
|
| 29 |
+
builds the CSV index. Failed refreshes leave the previous index active.
|
| 30 |
+
|
| 31 |
+
## 3. Configure the Supabase Edge Function
|
| 32 |
+
|
| 33 |
+
Set these secrets:
|
| 34 |
+
|
| 35 |
+
```text
|
| 36 |
+
CUSTOM_QUIZ_API_BASE_URL
|
| 37 |
+
CUSTOM_QUIZ_API_USERNAME
|
| 38 |
+
CUSTOM_QUIZ_API_PASSWORD
|
| 39 |
+
CUSTOM_QUIZ_API_TIMEOUT_MS
|
| 40 |
+
CUSTOM_QUIZ_MAX_EXCLUDE_IDS
|
| 41 |
+
CUSTOM_QUIZ_STALE_ID_ALERT_THRESHOLD
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Before creating database objects, run the SELECT-only schema audit supplied
|
| 45 |
+
with the implementation review. Create the final database objects only after
|
| 46 |
+
that audit confirms the live column names and data types. Then deploy
|
| 47 |
+
`generate-custom-topic-quiz`. The function authenticates the caller itself,
|
| 48 |
+
which is why local `config.toml` sets `verify_jwt = false` for this function.
|
| 49 |
+
|
| 50 |
+
The retrieval API search endpoint uses HTTP Basic authentication. Store the
|
| 51 |
+
same `CUSTOM_QUIZ_API_USERNAME` and `CUSTOM_QUIZ_API_PASSWORD` in the retrieval
|
| 52 |
+
API environment and in `supabase/functions/.env`. Keep separate
|
| 53 |
+
`CUSTOM_QUIZ_ADMIN_USERNAME` and `CUSTOM_QUIZ_ADMIN_PASSWORD` values for the
|
| 54 |
+
internal index-management endpoints.
|
| 55 |
+
|
| 56 |
+
## 4. Flutter feature flag
|
| 57 |
+
|
| 58 |
+
The shared card is enabled by default. It can be disabled at build time with:
|
| 59 |
+
|
| 60 |
+
```text
|
| 61 |
+
--dart-define=CUSTOM_TOPIC_QUIZ_ENABLED=false
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
Flutter calls only the Supabase Edge Function. It never receives the retrieval
|
| 65 |
+
API URL or credentials.
|
Dockerfile
CHANGED
|
@@ -48,4 +48,4 @@ ENV HF_HOME=/tmp/hf_home
|
|
| 48 |
ENV TORCH_HOME=/tmp/torch_home
|
| 49 |
|
| 50 |
# Command to run the app
|
| 51 |
-
CMD ["
|
|
|
|
| 48 |
ENV TORCH_HOME=/tmp/torch_home
|
| 49 |
|
| 50 |
# Command to run the app
|
| 51 |
+
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--threads", "8", "--timeout", "180", "--access-logfile", "-", "--error-logfile", "-", "app:app"]
|
Dockerfile.custom_quiz
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 6 |
+
libgomp1 \
|
| 7 |
+
build-essential \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
COPY requirements.txt /app/requirements.txt
|
| 11 |
+
RUN pip install --no-cache-dir --timeout=1000 -r /app/requirements.txt
|
| 12 |
+
|
| 13 |
+
COPY . /app
|
| 14 |
+
RUN useradd -m -u 1000 appuser && \
|
| 15 |
+
mkdir -p /app/sources/custom_quiz /app/faiss_storage_custom_quiz \
|
| 16 |
+
/tmp/transformers_cache /tmp/hf_home /tmp/torch_home && \
|
| 17 |
+
chown -R appuser:appuser /app /tmp/transformers_cache /tmp/hf_home /tmp/torch_home
|
| 18 |
+
|
| 19 |
+
USER appuser
|
| 20 |
+
|
| 21 |
+
ENV PORT=7861 \
|
| 22 |
+
TRANSFORMERS_CACHE=/tmp/transformers_cache \
|
| 23 |
+
HF_HOME=/tmp/hf_home \
|
| 24 |
+
TORCH_HOME=/tmp/torch_home
|
| 25 |
+
|
| 26 |
+
EXPOSE 7861
|
| 27 |
+
|
| 28 |
+
CMD ["gunicorn", "--bind", "0.0.0.0:7861", "--workers", "1", "--threads", "8", "--timeout", "180", "--access-logfile", "-", "--error-logfile", "-", "custom_quiz_app:app"]
|
app.py
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify, Response, render_template
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
import os
|
| 4 |
+
import logging
|
| 5 |
+
import functools
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import threading
|
| 8 |
+
import time
|
| 9 |
+
import tempfile
|
| 10 |
+
import shutil
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
|
| 13 |
+
# Load environment variables
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# Custom Imports
|
| 17 |
+
from rag_system import initialize_and_get_rag_system
|
| 18 |
+
from config import (
|
| 19 |
+
API_USERNAME, API_PASSWORD, RAG_SOURCES_DIR, RAG_STORAGE_PARENT_DIR,
|
| 20 |
+
FAQ_SOURCES_DIR, FAQ_STORAGE_PARENT_DIR, FAQ_CSV_FILENAME,
|
| 21 |
+
FAQ_INITIAL_FETCH_K, FAQ_FINAL_K, FAQ_CONFIDENCE_THRESHOLD,
|
| 22 |
+
GDRIVE_INDEX_ENABLED, GDRIVE_INDEX_ID_OR_URL,
|
| 23 |
+
GDRIVE_USERS_CSV_ENABLED, GDRIVE_USERS_CSV_ID_OR_URL,
|
| 24 |
+
ADMIN_USERNAME, ADMIN_PASSWORD, RAG_RERANKER_K, RAG_INITIAL_FETCH_K,
|
| 25 |
+
EXTERNAL_URL, URL_UPDATE_PERIOD_MINUTES, URL_FETCH_ENABLED,
|
| 26 |
+
RAG_CSV_INITIAL_FETCH_K, RAG_CSV_FINAL_K,
|
| 27 |
+
RAG_CSV_MAX_RESULTS, RAG_CSV_CONFIDENCE_THRESHOLD
|
| 28 |
+
)
|
| 29 |
+
from utils import download_and_unzip_gdrive_file, download_gdrive_file, fetch_and_clean_url
|
| 30 |
+
|
| 31 |
+
# Logging Setup
|
| 32 |
+
logging.basicConfig(level=logging.INFO)
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
# Flask Init
|
| 36 |
+
app = Flask(__name__, static_folder='static', template_folder='templates')
|
| 37 |
+
CORS(app)
|
| 38 |
+
|
| 39 |
+
# Global State
|
| 40 |
+
rag_system = None
|
| 41 |
+
faq_rag_system = None
|
| 42 |
+
user_df = None
|
| 43 |
+
_APP_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 44 |
+
|
| 45 |
+
# --- Helper: Load Users ---
|
| 46 |
+
def load_users_from_csv():
|
| 47 |
+
global user_df
|
| 48 |
+
assets_folder = os.path.join(_APP_BASE_DIR, 'assets')
|
| 49 |
+
os.makedirs(assets_folder, exist_ok=True)
|
| 50 |
+
users_csv_path = os.path.join(assets_folder, 'users.csv')
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
if os.path.exists(users_csv_path):
|
| 54 |
+
user_df = pd.read_csv(users_csv_path)
|
| 55 |
+
# Normalize email
|
| 56 |
+
if 'email' in user_df.columns:
|
| 57 |
+
user_df['email'] = user_df['email'].str.lower().str.strip()
|
| 58 |
+
logger.info(f"Loaded {len(user_df)} users from CSV.")
|
| 59 |
+
else:
|
| 60 |
+
logger.warning("users.csv not found in assets folder.")
|
| 61 |
+
user_df = None
|
| 62 |
+
except Exception as e:
|
| 63 |
+
logger.error(f"Failed to load users.csv: {e}")
|
| 64 |
+
user_df = None
|
| 65 |
+
|
| 66 |
+
# --- Helper: Auth Decorators ---
|
| 67 |
+
def require_api_auth(f):
|
| 68 |
+
"""Protects the N8N Webhook endpoint"""
|
| 69 |
+
@functools.wraps(f)
|
| 70 |
+
def decorated(*args, **kwargs):
|
| 71 |
+
auth = request.authorization
|
| 72 |
+
if not API_USERNAME or not API_PASSWORD or not auth or auth.username != API_USERNAME or auth.password != API_PASSWORD:
|
| 73 |
+
return Response('Unauthorized', 401, {'WWW-Authenticate': 'Basic realm="API Login Required"'})
|
| 74 |
+
return f(*args, **kwargs)
|
| 75 |
+
return decorated
|
| 76 |
+
|
| 77 |
+
def require_admin_auth(f):
|
| 78 |
+
"""Protects Admin Rebuild/Update endpoints"""
|
| 79 |
+
@functools.wraps(f)
|
| 80 |
+
def decorated(*args, **kwargs):
|
| 81 |
+
auth = request.authorization
|
| 82 |
+
if not auth:
|
| 83 |
+
return jsonify({"error": "Unauthorized"}), 401
|
| 84 |
+
|
| 85 |
+
if user_df is not None:
|
| 86 |
+
user_email = auth.username.lower().strip()
|
| 87 |
+
user_record = user_df[user_df['email'] == user_email]
|
| 88 |
+
if not user_record.empty:
|
| 89 |
+
user_data = user_record.iloc[0]
|
| 90 |
+
if str(user_data['password']) == auth.password and user_data['role'] == 'admin':
|
| 91 |
+
return f(*args, **kwargs)
|
| 92 |
+
|
| 93 |
+
if ADMIN_USERNAME and ADMIN_PASSWORD and auth.username == ADMIN_USERNAME and auth.password == ADMIN_PASSWORD:
|
| 94 |
+
return f(*args, **kwargs)
|
| 95 |
+
|
| 96 |
+
return jsonify({"error": "Unauthorized"}), 401
|
| 97 |
+
return decorated
|
| 98 |
+
|
| 99 |
+
# --- URL Zero-Downtime Updater ---
|
| 100 |
+
def trigger_url_update():
|
| 101 |
+
global rag_system
|
| 102 |
+
if not URL_FETCH_ENABLED or not EXTERNAL_URL:
|
| 103 |
+
return {"error": "External URL fetching is disabled or not configured"}
|
| 104 |
+
|
| 105 |
+
logger.info(f"[URL_UPDATE] Starting zero-downtime fetch from {EXTERNAL_URL}")
|
| 106 |
+
|
| 107 |
+
# 1. Create temporary staging folders
|
| 108 |
+
temp_staging_sources = tempfile.mkdtemp(prefix="rag_sources_temp_")
|
| 109 |
+
temp_index = tempfile.mkdtemp(prefix="rag_index_temp_")
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
# 2. COMBINE SOURCES: Copy existing GDrive/Local sources to staging first
|
| 113 |
+
if os.path.exists(RAG_SOURCES_DIR):
|
| 114 |
+
shutil.copytree(RAG_SOURCES_DIR, temp_staging_sources, dirs_exist_ok=True)
|
| 115 |
+
|
| 116 |
+
# 3. Fetch URL data — saved to <app_root>/tmp/ for persistence & inspection
|
| 117 |
+
tmp_dir = os.path.join(_APP_BASE_DIR, 'tmp')
|
| 118 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 119 |
+
url_out_path = os.path.join(tmp_dir, "url_data.txt")
|
| 120 |
+
success = fetch_and_clean_url(EXTERNAL_URL, url_out_path)
|
| 121 |
+
|
| 122 |
+
if not success:
|
| 123 |
+
return {"error": "Failed to fetch or parse the URL."}
|
| 124 |
+
|
| 125 |
+
# Copy from tmp/ into staging so it gets indexed alongside other sources
|
| 126 |
+
shutil.copy2(url_out_path, os.path.join(temp_staging_sources, "url_data.txt"))
|
| 127 |
+
|
| 128 |
+
# 4. Build a brand new RAG instance isolated in the temp directories
|
| 129 |
+
new_rag = initialize_and_get_rag_system(
|
| 130 |
+
force_rebuild=True,
|
| 131 |
+
source_dir_override=temp_staging_sources,
|
| 132 |
+
storage_dir_override=temp_index
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
if new_rag is None:
|
| 136 |
+
raise Exception("Failed to build new RAG index from parsed text.")
|
| 137 |
+
|
| 138 |
+
# 5. Atomic Swap (Now incoming requests hit the new DB immediately)
|
| 139 |
+
rag_system = new_rag
|
| 140 |
+
|
| 141 |
+
# 6. Backup/Replace persistent INDEX directory ONLY
|
| 142 |
+
os.makedirs(RAG_STORAGE_PARENT_DIR, exist_ok=True)
|
| 143 |
+
shutil.copytree(temp_index, RAG_STORAGE_PARENT_DIR, dirs_exist_ok=True)
|
| 144 |
+
|
| 145 |
+
rag_system.index_storage_dir = RAG_STORAGE_PARENT_DIR
|
| 146 |
+
|
| 147 |
+
logger.info("[URL_UPDATE] Success! RAG database updated combining Local, GDrive, and URL sources.")
|
| 148 |
+
return {"status": "success", "message": "Database successfully updated using combined sources."}
|
| 149 |
+
|
| 150 |
+
except Exception as e:
|
| 151 |
+
logger.error(f"[URL_UPDATE] Error during update: {e}", exc_info=True)
|
| 152 |
+
return {"error": str(e)}
|
| 153 |
+
|
| 154 |
+
finally:
|
| 155 |
+
shutil.rmtree(temp_staging_sources, ignore_errors=True)
|
| 156 |
+
shutil.rmtree(temp_index, ignore_errors=True)
|
| 157 |
+
|
| 158 |
+
def url_periodic_loop():
|
| 159 |
+
if not URL_FETCH_ENABLED or not EXTERNAL_URL or URL_UPDATE_PERIOD_MINUTES <= 0:
|
| 160 |
+
logger.info("Periodic URL updates disabled.")
|
| 161 |
+
return
|
| 162 |
+
|
| 163 |
+
logger.info(f"[URL_UPDATE] Background thread started for: {EXTERNAL_URL}")
|
| 164 |
+
trigger_url_update()
|
| 165 |
+
|
| 166 |
+
while True:
|
| 167 |
+
time.sleep(URL_UPDATE_PERIOD_MINUTES * 60)
|
| 168 |
+
logger.info(f"[URL_UPDATE] Triggering scheduled periodic update...")
|
| 169 |
+
trigger_url_update()
|
| 170 |
+
|
| 171 |
+
# --- Startup Logic ---
|
| 172 |
+
def run_startup_tasks():
|
| 173 |
+
global rag_system, faq_rag_system
|
| 174 |
+
logger.info("--- Executing Startup Tasks ---")
|
| 175 |
+
|
| 176 |
+
if GDRIVE_USERS_CSV_ENABLED and GDRIVE_USERS_CSV_ID_OR_URL:
|
| 177 |
+
target = os.path.join(_APP_BASE_DIR, 'assets', 'users.csv')
|
| 178 |
+
download_gdrive_file(GDRIVE_USERS_CSV_ID_OR_URL, target)
|
| 179 |
+
|
| 180 |
+
load_users_from_csv()
|
| 181 |
+
|
| 182 |
+
if GDRIVE_INDEX_ENABLED and GDRIVE_INDEX_ID_OR_URL:
|
| 183 |
+
download_and_unzip_gdrive_file(GDRIVE_INDEX_ID_OR_URL, os.getcwd())
|
| 184 |
+
|
| 185 |
+
# Main knowledgebase: unchanged behavior, indexes the regular sources directory.
|
| 186 |
+
rag_system = initialize_and_get_rag_system()
|
| 187 |
+
|
| 188 |
+
# App FAQs: separate source folder and separate index/storage.
|
| 189 |
+
# Put faqs.csv in sources/app_faqs/ by default, or override FAQ_SOURCES_DIR.
|
| 190 |
+
faq_rag_system = initialize_and_get_rag_system(
|
| 191 |
+
source_dir_override=FAQ_SOURCES_DIR,
|
| 192 |
+
storage_dir_override=FAQ_STORAGE_PARENT_DIR
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
if URL_FETCH_ENABLED and EXTERNAL_URL:
|
| 196 |
+
threading.Thread(target=url_periodic_loop, daemon=True).start()
|
| 197 |
+
|
| 198 |
+
logger.info("--- Startup Tasks Complete ---")
|
| 199 |
+
|
| 200 |
+
with app.app_context():
|
| 201 |
+
run_startup_tasks()
|
| 202 |
+
|
| 203 |
+
def _csv_row_is_inactive(content: str) -> bool:
|
| 204 |
+
"""Blank/missing active is active; only explicit false values are hidden."""
|
| 205 |
+
inactive_values = {"0", "false", "no", "n", "inactive", "disabled", "off"}
|
| 206 |
+
for line in content.splitlines():
|
| 207 |
+
key, sep, value = line.partition(":")
|
| 208 |
+
if sep and key.strip().lower() == "active":
|
| 209 |
+
return value.strip().lower() in inactive_values
|
| 210 |
+
return False
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _search_rag_system(
|
| 214 |
+
target_rag,
|
| 215 |
+
label,
|
| 216 |
+
default_initial_fetch_k,
|
| 217 |
+
default_final_k,
|
| 218 |
+
csv_initial_fetch_k,
|
| 219 |
+
csv_final_k,
|
| 220 |
+
csv_max_results,
|
| 221 |
+
csv_confidence_threshold,
|
| 222 |
+
allowed_source_name=None,
|
| 223 |
+
):
|
| 224 |
+
if not target_rag or not target_rag.retriever:
|
| 225 |
+
return jsonify({"error": f"{label} RAG not initialized. Check server logs and source files."}), 503
|
| 226 |
+
|
| 227 |
+
data = request.json or {}
|
| 228 |
+
|
| 229 |
+
query = data.get('query')
|
| 230 |
+
if not query:
|
| 231 |
+
return jsonify({"error": "Query field is required"}), 400
|
| 232 |
+
|
| 233 |
+
final_k = data.get('final_k', default_final_k)
|
| 234 |
+
initial_fetch_k = data.get('initial_fetch_k', default_initial_fetch_k)
|
| 235 |
+
csv_initial_fetch_k = data.get('csv_initial_fetch_k', csv_initial_fetch_k)
|
| 236 |
+
csv_final_k = data.get('csv_final_k', csv_final_k)
|
| 237 |
+
use_reranker = data.get('use_reranker', True)
|
| 238 |
+
cleaned = data.get('cleaned', False)
|
| 239 |
+
min_score = data.get('min_score')
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
final_k = int(final_k)
|
| 243 |
+
initial_fetch_k = int(initial_fetch_k)
|
| 244 |
+
csv_initial_fetch_k = int(csv_initial_fetch_k)
|
| 245 |
+
csv_final_k = int(csv_final_k)
|
| 246 |
+
|
| 247 |
+
if final_k <= 0 or initial_fetch_k <= 0 or csv_initial_fetch_k <= 0 or csv_final_k <= 0:
|
| 248 |
+
return jsonify({"error": "final_k, initial_fetch_k, csv_initial_fetch_k, and csv_final_k must be positive integers"}), 400
|
| 249 |
+
|
| 250 |
+
if min_score is not None:
|
| 251 |
+
min_score = float(min_score)
|
| 252 |
+
|
| 253 |
+
except (TypeError, ValueError):
|
| 254 |
+
return jsonify({"error": "Invalid final_k, initial_fetch_k, csv_initial_fetch_k, csv_final_k, or min_score"}), 400
|
| 255 |
+
|
| 256 |
+
# initial_fetch_k = normal candidate retrieval.
|
| 257 |
+
# csv_initial_fetch_k = wider candidate retrieval for row-by-row CSVs.
|
| 258 |
+
# final_k = max total results returned.
|
| 259 |
+
# csv_final_k = max CSV rows allowed inside final results.
|
| 260 |
+
effective_initial_fetch_k = max(initial_fetch_k, csv_initial_fetch_k)
|
| 261 |
+
candidate_k = max(effective_initial_fetch_k, final_k, csv_final_k)
|
| 262 |
+
|
| 263 |
+
try:
|
| 264 |
+
raw_results = target_rag.search_knowledge_base(
|
| 265 |
+
query,
|
| 266 |
+
top_k=candidate_k,
|
| 267 |
+
initial_fetch_k=effective_initial_fetch_k,
|
| 268 |
+
use_reranker=use_reranker,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
# Normalize scores so clients can always treat higher as better.
|
| 272 |
+
# With reranker enabled: score is reranker_score, already higher-is-better.
|
| 273 |
+
# With reranker disabled: score is FAISS L2 distance, lower-is-better, so convert it.
|
| 274 |
+
for res in raw_results:
|
| 275 |
+
score = res.get("score")
|
| 276 |
+
if score is None:
|
| 277 |
+
continue
|
| 278 |
+
|
| 279 |
+
if not use_reranker:
|
| 280 |
+
res.setdefault("metadata", {})["raw_retrieval_score"] = score
|
| 281 |
+
res["score"] = 1 / (1 + score)
|
| 282 |
+
|
| 283 |
+
filtered_results = []
|
| 284 |
+
csv_count = 0
|
| 285 |
+
|
| 286 |
+
for res in raw_results:
|
| 287 |
+
metadata = res.get("metadata", {})
|
| 288 |
+
source_name = metadata.get("source_document_name", "")
|
| 289 |
+
is_csv = metadata.get("source_type") == "csv" or source_name.endswith(".csv")
|
| 290 |
+
score = res.get("score")
|
| 291 |
+
|
| 292 |
+
# FAQ endpoint must only return rows from the app FAQ CSV.
|
| 293 |
+
if allowed_source_name and source_name != allowed_source_name:
|
| 294 |
+
continue
|
| 295 |
+
|
| 296 |
+
# FAQ CSV can keep inactive rows for future use; they will not be returned.
|
| 297 |
+
if allowed_source_name == FAQ_CSV_FILENAME and _csv_row_is_inactive(res.get("content", "")):
|
| 298 |
+
continue
|
| 299 |
+
|
| 300 |
+
# Optional per-request global score filter.
|
| 301 |
+
if min_score is not None and (score is None or score < min_score):
|
| 302 |
+
continue
|
| 303 |
+
|
| 304 |
+
# Existing CSV-specific filter, scoped per endpoint.
|
| 305 |
+
if is_csv:
|
| 306 |
+
csv_result_cap = min(csv_max_results, csv_final_k)
|
| 307 |
+
if score is not None and score >= csv_confidence_threshold and csv_count < csv_result_cap:
|
| 308 |
+
filtered_results.append(res)
|
| 309 |
+
csv_count += 1
|
| 310 |
+
else:
|
| 311 |
+
filtered_results.append(res)
|
| 312 |
+
|
| 313 |
+
if len(filtered_results) >= final_k:
|
| 314 |
+
break
|
| 315 |
+
|
| 316 |
+
if cleaned:
|
| 317 |
+
filtered_results = [{"content": r["content"]} for r in filtered_results]
|
| 318 |
+
|
| 319 |
+
return jsonify({"results": filtered_results, "count": len(filtered_results), "status": "success"})
|
| 320 |
+
|
| 321 |
+
except Exception as e:
|
| 322 |
+
logger.error(f"{label} Search API Error: {e}", exc_info=True)
|
| 323 |
+
return jsonify({"error": str(e)}), 500
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# ===========================
|
| 327 |
+
# API ROUTES
|
| 328 |
+
# ===========================
|
| 329 |
+
|
| 330 |
+
@app.route('/webhook/search', methods=['POST'])
|
| 331 |
+
@require_api_auth
|
| 332 |
+
def search_knowledgebase_api():
|
| 333 |
+
# Current regular knowledgebase endpoint: same URL, same auth, same response shape.
|
| 334 |
+
return _search_rag_system(
|
| 335 |
+
target_rag=rag_system,
|
| 336 |
+
label="Knowledgebase",
|
| 337 |
+
default_initial_fetch_k=RAG_INITIAL_FETCH_K,
|
| 338 |
+
default_final_k=RAG_RERANKER_K,
|
| 339 |
+
csv_initial_fetch_k=RAG_CSV_INITIAL_FETCH_K,
|
| 340 |
+
csv_final_k=RAG_CSV_FINAL_K,
|
| 341 |
+
csv_max_results=RAG_CSV_MAX_RESULTS,
|
| 342 |
+
csv_confidence_threshold=RAG_CSV_CONFIDENCE_THRESHOLD,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
@app.route('/webhook/search_faqs', methods=['POST'])
|
| 347 |
+
@require_api_auth
|
| 348 |
+
def search_app_faqs_api():
|
| 349 |
+
# Dedicated app FAQ endpoint: searches only sources/app_faqs/faqs.csv.
|
| 350 |
+
return _search_rag_system(
|
| 351 |
+
target_rag=faq_rag_system,
|
| 352 |
+
label="App FAQ",
|
| 353 |
+
default_initial_fetch_k=FAQ_INITIAL_FETCH_K,
|
| 354 |
+
default_final_k=FAQ_FINAL_K,
|
| 355 |
+
csv_initial_fetch_k=FAQ_INITIAL_FETCH_K,
|
| 356 |
+
csv_final_k=FAQ_FINAL_K,
|
| 357 |
+
csv_max_results=FAQ_FINAL_K,
|
| 358 |
+
csv_confidence_threshold=FAQ_CONFIDENCE_THRESHOLD,
|
| 359 |
+
allowed_source_name=FAQ_CSV_FILENAME,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
@app.route('/user-login', methods=['POST'])
|
| 363 |
+
def user_login():
|
| 364 |
+
if user_df is None:
|
| 365 |
+
return jsonify({"error": "User database not available."}), 503
|
| 366 |
+
|
| 367 |
+
data = request.json
|
| 368 |
+
email = data.get('email', '').lower().strip()
|
| 369 |
+
password = data.get('password')
|
| 370 |
+
|
| 371 |
+
if not email or not password:
|
| 372 |
+
return jsonify({"error": "Email and password required"}), 400
|
| 373 |
+
|
| 374 |
+
user_record = user_df[user_df['email'] == email]
|
| 375 |
+
if not user_record.empty:
|
| 376 |
+
u_data = user_record.iloc[0]
|
| 377 |
+
if str(u_data['password']) == str(password):
|
| 378 |
+
resp = u_data.to_dict()
|
| 379 |
+
if 'password' in resp:
|
| 380 |
+
del resp['password']
|
| 381 |
+
return jsonify(resp), 200
|
| 382 |
+
|
| 383 |
+
return jsonify({"error": "Invalid credentials"}), 401
|
| 384 |
+
|
| 385 |
+
@app.route('/')
|
| 386 |
+
def index_route():
|
| 387 |
+
return render_template('chat-bot.html')
|
| 388 |
+
|
| 389 |
+
@app.route('/admin/login', methods=['POST'])
|
| 390 |
+
@require_admin_auth
|
| 391 |
+
def admin_login():
|
| 392 |
+
return jsonify({"status": "success", "message": "Authenticated"}), 200
|
| 393 |
+
|
| 394 |
+
@app.route('/admin/update_faiss_index', methods=['POST'])
|
| 395 |
+
@require_admin_auth
|
| 396 |
+
def update_faiss_index():
|
| 397 |
+
if not rag_system:
|
| 398 |
+
return jsonify({"error": "RAG system not initialized"}), 503
|
| 399 |
+
|
| 400 |
+
data = request.json or {}
|
| 401 |
+
max_files = data.get('max_new_files')
|
| 402 |
+
|
| 403 |
+
try:
|
| 404 |
+
result = rag_system.update_index_with_new_files(RAG_SOURCES_DIR, max_files)
|
| 405 |
+
return jsonify(result), 200
|
| 406 |
+
except Exception as e:
|
| 407 |
+
return jsonify({"error": str(e)}), 500
|
| 408 |
+
|
| 409 |
+
@app.route('/admin/rebuild_index', methods=['POST'])
|
| 410 |
+
@require_admin_auth
|
| 411 |
+
def rebuild_index():
|
| 412 |
+
global rag_system
|
| 413 |
+
try:
|
| 414 |
+
if URL_FETCH_ENABLED and EXTERNAL_URL:
|
| 415 |
+
result = trigger_url_update()
|
| 416 |
+
if "error" in result:
|
| 417 |
+
return jsonify(result), 500
|
| 418 |
+
return jsonify({"status": "Index rebuilt successfully using combined local & URL sources"}), 200
|
| 419 |
+
else:
|
| 420 |
+
rag_system = initialize_and_get_rag_system(force_rebuild=True)
|
| 421 |
+
return jsonify({"status": "Index rebuilt successfully"}), 200
|
| 422 |
+
except Exception as e:
|
| 423 |
+
return jsonify({"error": str(e)}), 500
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
@app.route('/admin/rebuild_faq_index', methods=['POST'])
|
| 427 |
+
@require_admin_auth
|
| 428 |
+
def rebuild_faq_index():
|
| 429 |
+
global faq_rag_system
|
| 430 |
+
try:
|
| 431 |
+
faq_rag_system = initialize_and_get_rag_system(
|
| 432 |
+
force_rebuild=True,
|
| 433 |
+
source_dir_override=FAQ_SOURCES_DIR,
|
| 434 |
+
storage_dir_override=FAQ_STORAGE_PARENT_DIR
|
| 435 |
+
)
|
| 436 |
+
if not faq_rag_system or not faq_rag_system.retriever:
|
| 437 |
+
return jsonify({"error": "FAQ index rebuild failed. Check sources/app_faqs/faqs.csv."}), 500
|
| 438 |
+
return jsonify({"status": "FAQ index rebuilt successfully"}), 200
|
| 439 |
+
except Exception as e:
|
| 440 |
+
return jsonify({"error": str(e)}), 500
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
@app.route('/admin/update_faq_index', methods=['POST'])
|
| 444 |
+
@require_admin_auth
|
| 445 |
+
def update_faq_index():
|
| 446 |
+
if not faq_rag_system:
|
| 447 |
+
return jsonify({"error": "FAQ RAG system not initialized"}), 503
|
| 448 |
+
|
| 449 |
+
data = request.json or {}
|
| 450 |
+
max_files = data.get('max_new_files')
|
| 451 |
+
|
| 452 |
+
try:
|
| 453 |
+
result = faq_rag_system.update_index_with_new_files(FAQ_SOURCES_DIR, max_files)
|
| 454 |
+
return jsonify(result), 200
|
| 455 |
+
except Exception as e:
|
| 456 |
+
return jsonify({"error": str(e)}), 500
|
| 457 |
+
|
| 458 |
+
# Retained specific endpoint name to ensure the frontend doesn't break
|
| 459 |
+
@app.route('/admin/fetch_rentry', methods=['POST'])
|
| 460 |
+
@require_admin_auth
|
| 461 |
+
def api_fetch_url():
|
| 462 |
+
result = trigger_url_update()
|
| 463 |
+
if "error" in result:
|
| 464 |
+
return jsonify(result), 500
|
| 465 |
+
return jsonify(result), 200
|
| 466 |
+
|
| 467 |
+
def _rag_ready(target_rag):
|
| 468 |
+
return target_rag is not None and getattr(target_rag, "retriever", None) is not None
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
@app.route('/status', methods=['GET'])
|
| 472 |
+
def status_route():
|
| 473 |
+
main_rag_ready = _rag_ready(rag_system)
|
| 474 |
+
faq_rag_ready = _rag_ready(faq_rag_system)
|
| 475 |
+
|
| 476 |
+
return jsonify({
|
| 477 |
+
"status": "online",
|
| 478 |
+
"rag_initialized": main_rag_ready or faq_rag_ready,
|
| 479 |
+
"main_rag_initialized": main_rag_ready,
|
| 480 |
+
"faq_rag_initialized": faq_rag_ready,
|
| 481 |
+
"faq_sources_dir": FAQ_SOURCES_DIR,
|
| 482 |
+
"faq_csv_filename": FAQ_CSV_FILENAME,
|
| 483 |
+
"users_loaded": user_df is not None
|
| 484 |
+
})
|
| 485 |
+
|
| 486 |
+
if __name__ == '__main__':
|
| 487 |
+
port = int(os.environ.get("PORT", 7860))
|
| 488 |
+
app.run(host='0.0.0.0', port=port)
|
config.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
|
| 5 |
+
load_dotenv()
|
| 6 |
+
|
| 7 |
+
# --- Logging Setup ---
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
if not logger.handlers:
|
| 10 |
+
logging.basicConfig(
|
| 11 |
+
level=logging.INFO,
|
| 12 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
_MODULE_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 16 |
+
|
| 17 |
+
# API Authentication for n8n (Basic Auth)
|
| 18 |
+
API_USERNAME = os.getenv("API_USERNAME", "").strip()
|
| 19 |
+
API_PASSWORD = os.getenv("API_PASSWORD", "").strip()
|
| 20 |
+
|
| 21 |
+
# Admin fallback credentials for dashboard (used when users.csv is missing or unavailable)
|
| 22 |
+
ADMIN_USERNAME = os.getenv('FLASK_ADMIN_USERNAME', '').strip()
|
| 23 |
+
ADMIN_PASSWORD = os.getenv('FLASK_ADMIN_PASSWORD', '').strip()
|
| 24 |
+
|
| 25 |
+
# URL Fetcher configs (Generalized from Rentry)
|
| 26 |
+
URL_FETCH_ENABLED = os.getenv("URL_FETCH_ENABLED", "False").lower() == "true"
|
| 27 |
+
EXTERNAL_URL = os.getenv("EXTERNAL_URL", os.getenv("RENTRY_URL", ""))
|
| 28 |
+
URL_UPDATE_PERIOD_MINUTES = int(os.getenv("URL_UPDATE_PERIOD_MINUTES", os.getenv("RENTRY_UPDATE_PERIOD_MINUTES", "60")))
|
| 29 |
+
|
| 30 |
+
# CSV Configuration
|
| 31 |
+
RAG_CSV_MAX_RESULTS = int(os.getenv("RAG_CSV_MAX_RESULTS", "5"))
|
| 32 |
+
RAG_CSV_CONFIDENCE_THRESHOLD = float(os.getenv("RAG_CSV_CONFIDENCE_THRESHOLD", "0.5"))
|
| 33 |
+
# Separate CSV retrieval controls. CSV is row-by-row, so it usually needs a wider candidate pool.
|
| 34 |
+
RAG_CSV_INITIAL_FETCH_K = int(os.getenv("RAG_CSV_INITIAL_FETCH_K", "50"))
|
| 35 |
+
RAG_CSV_FINAL_K = int(os.getenv("RAG_CSV_FINAL_K", str(RAG_CSV_MAX_RESULTS)))
|
| 36 |
+
# Number of CSV rows stored in each vector-search chunk. Use 1 for strict row-by-row CSV indexing.
|
| 37 |
+
RAG_CSV_ROWS_PER_CHUNK = max(1, int(os.getenv("RAG_CSV_ROWS_PER_CHUNK", "1")))
|
| 38 |
+
|
| 39 |
+
RAG_FAISS_INDEX_SUBDIR_NAME = "faiss_index"
|
| 40 |
+
RAG_STORAGE_PARENT_DIR = os.getenv("RAG_STORAGE_DIR", os.path.join(_MODULE_BASE_DIR, "faiss_storage"))
|
| 41 |
+
RAG_SOURCES_DIR = os.getenv("SOURCES_DIR", os.path.join(_MODULE_BASE_DIR, "sources"))
|
| 42 |
+
RAG_CHUNKED_SOURCES_FILENAME = "pre_chunked_sources.json"
|
| 43 |
+
|
| 44 |
+
# App FAQ Configuration
|
| 45 |
+
# Keep app-only FAQ content here (default: sources/app_faqs/faqs.csv).
|
| 46 |
+
# It has separate FAISS storage, so it does not mix into the main knowledgebase.
|
| 47 |
+
FAQ_SOURCES_DIR = os.getenv("FAQ_SOURCES_DIR", os.path.join(RAG_SOURCES_DIR, "app_faqs"))
|
| 48 |
+
FAQ_STORAGE_PARENT_DIR = os.getenv("FAQ_STORAGE_DIR", os.path.join(_MODULE_BASE_DIR, "faiss_storage_app_faqs"))
|
| 49 |
+
FAQ_CSV_FILENAME = os.getenv("FAQ_CSV_FILENAME", "faqs.csv")
|
| 50 |
+
FAQ_INITIAL_FETCH_K = int(os.getenv("FAQ_INITIAL_FETCH_K", "50"))
|
| 51 |
+
FAQ_FINAL_K = int(os.getenv("FAQ_FINAL_K", "5"))
|
| 52 |
+
FAQ_CONFIDENCE_THRESHOLD = float(os.getenv("FAQ_CONFIDENCE_THRESHOLD", str(RAG_CSV_CONFIDENCE_THRESHOLD)))
|
| 53 |
+
|
| 54 |
+
os.makedirs(RAG_SOURCES_DIR, exist_ok=True)
|
| 55 |
+
os.makedirs(RAG_STORAGE_PARENT_DIR, exist_ok=True)
|
| 56 |
+
os.makedirs(FAQ_SOURCES_DIR, exist_ok=True)
|
| 57 |
+
os.makedirs(FAQ_STORAGE_PARENT_DIR, exist_ok=True)
|
| 58 |
+
|
| 59 |
+
# Embedding and model configuration
|
| 60 |
+
RAG_EMBEDDING_MODEL_NAME = os.getenv("RAG_EMBEDDING_MODEL", "BAAI/bge-small-en")
|
| 61 |
+
RAG_EMBEDDING_USE_GPU = os.getenv("RAG_EMBEDDING_GPU", "False").lower() == "true"
|
| 62 |
+
RAG_LOAD_INDEX_ON_STARTUP = os.getenv("RAG_LOAD_INDEX", "True").lower() == "true"
|
| 63 |
+
|
| 64 |
+
# Retrieval Settings
|
| 65 |
+
RAG_INITIAL_FETCH_K = int(os.getenv("RAG_INITIAL_FETCH_K", 20))
|
| 66 |
+
RAG_RERANKER_K = int(os.getenv("RAG_RERANKER_K", 5))
|
| 67 |
+
RAG_MAX_FILES_FOR_INCREMENTAL = int(os.getenv("RAG_MAX_FILES_FOR_INCREMENTAL", "50"))
|
| 68 |
+
|
| 69 |
+
# Chunk configuration
|
| 70 |
+
RAG_CHUNK_SIZE = int(os.getenv("RAG_CHUNK_SIZE", 2000))
|
| 71 |
+
RAG_CHUNK_OVERLAP = int(os.getenv("RAG_CHUNK_OVERLAP", 150))
|
| 72 |
+
|
| 73 |
+
# Reranker configuration
|
| 74 |
+
RAG_RERANKER_MODEL_NAME = os.getenv("RAG_RERANKER_MODEL", "jinaai/jina-reranker-v2-base-multilingual")
|
| 75 |
+
RAG_RERANKER_ENABLED = os.getenv("RAG_RERANKER_ENABLED", "True").lower() == "true"
|
| 76 |
+
|
| 77 |
+
# GDrive configuration for RAG sources
|
| 78 |
+
GDRIVE_SOURCES_ENABLED = os.getenv("GDRIVE_SOURCES_ENABLED", "False").lower() == "true"
|
| 79 |
+
GDRIVE_FOLDER_ID_OR_URL = os.getenv("GDRIVE_FOLDER_URL")
|
| 80 |
+
|
| 81 |
+
# GDrive configuration for downloading a pre-built FAISS index
|
| 82 |
+
GDRIVE_INDEX_ENABLED = os.getenv("GDRIVE_INDEX_ENABLED", "False").lower() == "true"
|
| 83 |
+
GDRIVE_INDEX_ID_OR_URL = os.getenv("GDRIVE_INDEX_URL")
|
| 84 |
+
|
| 85 |
+
# GDrive configuration for downloading users.csv
|
| 86 |
+
GDRIVE_USERS_CSV_ENABLED = os.getenv("GDRIVE_USERS_CSV_ENABLED", "False").lower() == "true"
|
| 87 |
+
GDRIVE_USERS_CSV_ID_OR_URL = os.getenv("GDRIVE_USERS_CSV_URL")
|
| 88 |
+
|
| 89 |
+
RAG_DETAILED_LOGGING = os.getenv("RAG_DETAILED_LOGGING", "True").lower() == "true"
|
| 90 |
+
|
| 91 |
+
logger.info(f"RAG Config Loaded - Chunk Size: {RAG_CHUNK_SIZE}, Chunk Overlap: {RAG_CHUNK_OVERLAP}")
|
| 92 |
+
logger.info(f"Embedding Model: {RAG_EMBEDDING_MODEL_NAME}")
|
| 93 |
+
logger.info(f"Reranker Model: {RAG_RERANKER_MODEL_NAME}")
|
| 94 |
+
logger.info(f"Retrieval Pipeline: Initial Fetch K={RAG_INITIAL_FETCH_K}, Reranker Final K={RAG_RERANKER_K}")
|
| 95 |
+
logger.info(f"CSV Filters: Max Results={RAG_CSV_MAX_RESULTS}, Threshold={RAG_CSV_CONFIDENCE_THRESHOLD}")
|
| 96 |
+
logger.info(f"CSV Retrieval: Initial Fetch K={RAG_CSV_INITIAL_FETCH_K}, Final K={RAG_CSV_FINAL_K}")
|
| 97 |
+
logger.info(f"App FAQ Source: {os.path.join(FAQ_SOURCES_DIR, FAQ_CSV_FILENAME)}")
|
| 98 |
+
logger.info(f"App FAQ Retrieval: Initial Fetch K={FAQ_INITIAL_FETCH_K}, Final K={FAQ_FINAL_K}")
|
| 99 |
+
logger.info(f"App FAQ Filter: Threshold={FAQ_CONFIDENCE_THRESHOLD}")
|
| 100 |
+
logger.info(f"CSV Chunking: Rows Per Chunk={RAG_CSV_ROWS_PER_CHUNK}")
|
| 101 |
+
logger.info(f"URL Fetching: {'ENABLED' if URL_FETCH_ENABLED else 'DISABLED'}")
|
| 102 |
+
logger.info(f"Detailed Logging: {'ENABLED' if RAG_DETAILED_LOGGING else 'DISABLED'}")
|
| 103 |
+
logger.info(f"GDrive Sources Download: {'ENABLED' if GDRIVE_SOURCES_ENABLED else 'DISABLED'}")
|
| 104 |
+
logger.info(f"GDrive Pre-built Index Download: {'ENABLED' if GDRIVE_INDEX_ENABLED else 'DISABLED'}")
|
| 105 |
+
logger.info(f"GDrive users.csv Download: {'ENABLED' if GDRIVE_USERS_CSV_ENABLED else 'DISABLED'}")
|
custom_quiz/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Question-only custom topic retrieval service."""
|
custom_quiz/__pycache__/parser.cpython-313.pyc
ADDED
|
Binary file (6.05 kB). View file
|
|
|
custom_quiz/__pycache__/search.cpython-313.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
custom_quiz/cache.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
from typing import Generic, Hashable, Optional, TypeVar
|
| 4 |
+
|
| 5 |
+
K = TypeVar("K", bound=Hashable)
|
| 6 |
+
V = TypeVar("V")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class LruCache(Generic[K, V]):
|
| 10 |
+
def __init__(self, capacity: int):
|
| 11 |
+
self.capacity = max(1, capacity)
|
| 12 |
+
self._items: "OrderedDict[K, V]" = OrderedDict()
|
| 13 |
+
self._lock = threading.RLock()
|
| 14 |
+
|
| 15 |
+
def get(self, key: K) -> Optional[V]:
|
| 16 |
+
with self._lock:
|
| 17 |
+
value = self._items.get(key)
|
| 18 |
+
if value is None:
|
| 19 |
+
return None
|
| 20 |
+
self._items.move_to_end(key)
|
| 21 |
+
return value
|
| 22 |
+
|
| 23 |
+
def put(self, key: K, value: V) -> None:
|
| 24 |
+
with self._lock:
|
| 25 |
+
self._items[key] = value
|
| 26 |
+
self._items.move_to_end(key)
|
| 27 |
+
while len(self._items) > self.capacity:
|
| 28 |
+
self._items.popitem(last=False)
|
| 29 |
+
|
| 30 |
+
def clear(self) -> None:
|
| 31 |
+
with self._lock:
|
| 32 |
+
self._items.clear()
|
| 33 |
+
|
| 34 |
+
def __len__(self) -> int:
|
| 35 |
+
with self._lock:
|
| 36 |
+
return len(self._items)
|
custom_quiz/config.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _bool(name: str, default: bool) -> bool:
|
| 7 |
+
raw = os.getenv(name)
|
| 8 |
+
return default if raw is None else raw.strip().lower() in {"1", "true", "yes", "on"}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _int(name: str, default: int, minimum: int = 0) -> int:
|
| 12 |
+
try:
|
| 13 |
+
value = int(os.getenv(name, str(default)))
|
| 14 |
+
except ValueError:
|
| 15 |
+
value = default
|
| 16 |
+
return max(minimum, value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _float(name: str, default: float, minimum: float = 0.0) -> float:
|
| 20 |
+
try:
|
| 21 |
+
value = float(os.getenv(name, str(default)))
|
| 22 |
+
except ValueError:
|
| 23 |
+
value = default
|
| 24 |
+
return max(minimum, value)
|
| 25 |
+
|
| 26 |
+
def _signed_float(name: str, default: float) -> float:
|
| 27 |
+
try:
|
| 28 |
+
return float(os.getenv(name, str(default)))
|
| 29 |
+
except ValueError:
|
| 30 |
+
return default
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass(frozen=True)
|
| 34 |
+
class QuizConfig:
|
| 35 |
+
csv_url: str
|
| 36 |
+
source_dir: Path
|
| 37 |
+
csv_path: Path
|
| 38 |
+
index_dir: Path
|
| 39 |
+
aliases_path: Path
|
| 40 |
+
embedding_model: str
|
| 41 |
+
reranker_model: str
|
| 42 |
+
embedding_gpu: bool
|
| 43 |
+
reranker_enabled: bool
|
| 44 |
+
api_username: str
|
| 45 |
+
api_password: str
|
| 46 |
+
admin_username: str
|
| 47 |
+
admin_password: str
|
| 48 |
+
max_results: int
|
| 49 |
+
max_exclude_ids: int
|
| 50 |
+
min_score: float
|
| 51 |
+
cache_size: int
|
| 52 |
+
cache_candidate_count: int
|
| 53 |
+
body_limit_bytes: int
|
| 54 |
+
row_drop_ratio: float
|
| 55 |
+
refresh_minutes: int
|
| 56 |
+
rrf_k: int
|
| 57 |
+
dense_weight: float
|
| 58 |
+
lexical_weight: float
|
| 59 |
+
keep_versions: int
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def from_env(cls) -> "QuizConfig":
|
| 63 |
+
base = Path(__file__).resolve().parent.parent
|
| 64 |
+
source_dir = Path(os.getenv("QUIZ_SOURCE_DIR", str(base / "sources" / "custom_quiz"))).resolve()
|
| 65 |
+
index_dir = Path(os.getenv("QUIZ_INDEX_DIR", str(base / "faiss_storage_custom_quiz"))).resolve()
|
| 66 |
+
csv_path = Path(os.getenv("QUIZ_CSV_PATH", str(source_dir / "quiz_questions.csv"))).resolve()
|
| 67 |
+
aliases_path = Path(os.getenv("QUIZ_ALIASES_PATH", str(source_dir / "aliases.json"))).resolve()
|
| 68 |
+
api_username = os.getenv("CUSTOM_QUIZ_API_USERNAME", "").strip()
|
| 69 |
+
api_password = os.getenv("CUSTOM_QUIZ_API_PASSWORD", "").strip()
|
| 70 |
+
admin_username = os.getenv("CUSTOM_QUIZ_ADMIN_USERNAME", "").strip()
|
| 71 |
+
admin_password = os.getenv("CUSTOM_QUIZ_ADMIN_PASSWORD", "").strip()
|
| 72 |
+
if not api_username or not api_password:
|
| 73 |
+
raise RuntimeError(
|
| 74 |
+
"CUSTOM_QUIZ_API_USERNAME and CUSTOM_QUIZ_API_PASSWORD are required."
|
| 75 |
+
)
|
| 76 |
+
if ":" in api_username:
|
| 77 |
+
raise RuntimeError("CUSTOM_QUIZ_API_USERNAME must not contain a colon.")
|
| 78 |
+
if len(api_password) < 20:
|
| 79 |
+
raise RuntimeError("CUSTOM_QUIZ_API_PASSWORD must contain at least 20 characters.")
|
| 80 |
+
if not admin_username or not admin_password:
|
| 81 |
+
raise RuntimeError(
|
| 82 |
+
"CUSTOM_QUIZ_ADMIN_USERNAME and CUSTOM_QUIZ_ADMIN_PASSWORD are required."
|
| 83 |
+
)
|
| 84 |
+
if ":" in admin_username:
|
| 85 |
+
raise RuntimeError("CUSTOM_QUIZ_ADMIN_USERNAME must not contain a colon.")
|
| 86 |
+
if len(admin_password) < 20:
|
| 87 |
+
raise RuntimeError("CUSTOM_QUIZ_ADMIN_PASSWORD must contain at least 20 characters.")
|
| 88 |
+
return cls(
|
| 89 |
+
csv_url=(os.getenv("QUIZ_CSV_URL") or os.getenv("QUIZ_QUESTIONS_CSV_URL") or "").strip(),
|
| 90 |
+
source_dir=source_dir,
|
| 91 |
+
csv_path=csv_path,
|
| 92 |
+
index_dir=index_dir,
|
| 93 |
+
aliases_path=aliases_path,
|
| 94 |
+
embedding_model=os.getenv("QUIZ_EMBEDDING_MODEL", "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2").strip(),
|
| 95 |
+
reranker_model=os.getenv("QUIZ_RERANKER_MODEL", "jinaai/jina-reranker-v2-base-multilingual").strip(),
|
| 96 |
+
embedding_gpu=_bool("QUIZ_EMBEDDING_GPU", False),
|
| 97 |
+
reranker_enabled=_bool("QUIZ_RERANKER_ENABLED", True),
|
| 98 |
+
api_username=api_username,
|
| 99 |
+
api_password=api_password,
|
| 100 |
+
admin_username=admin_username,
|
| 101 |
+
admin_password=admin_password,
|
| 102 |
+
max_results=_int("QUIZ_MAX_RESULTS", 50, 1),
|
| 103 |
+
max_exclude_ids=_int("QUIZ_MAX_EXCLUDE_IDS", 25000, 1),
|
| 104 |
+
min_score=_signed_float("QUIZ_MIN_SCORE", -1_000_000_000.0),
|
| 105 |
+
cache_size=_int("QUIZ_CACHE_SIZE", 256, 1),
|
| 106 |
+
cache_candidate_count=_int("QUIZ_CACHE_CANDIDATES", 500, 50),
|
| 107 |
+
body_limit_bytes=_int("QUIZ_BODY_LIMIT_BYTES", 2_000_000, 1024),
|
| 108 |
+
row_drop_ratio=min(1.0, _float("QUIZ_MIN_ROW_RATIO", 0.80, 0.05)),
|
| 109 |
+
refresh_minutes=_int("QUIZ_INDEX_REFRESH_MINUTES", 0, 0),
|
| 110 |
+
rrf_k=_int("QUIZ_RRF_K", 60, 1),
|
| 111 |
+
dense_weight=_float("QUIZ_DENSE_WEIGHT", 1.0, 0.0),
|
| 112 |
+
lexical_weight=_float("QUIZ_LEXICAL_WEIGHT", 1.25, 0.0),
|
| 113 |
+
keep_versions=_int("QUIZ_KEEP_INDEX_VERSIONS", 2, 2),
|
| 114 |
+
)
|
custom_quiz/index_manager.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import tempfile
|
| 6 |
+
import threading
|
| 7 |
+
from dataclasses import asdict, dataclass
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 11 |
+
|
| 12 |
+
import faiss
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
from shared_models import ModelBundle
|
| 16 |
+
from utils import download_gdrive_file
|
| 17 |
+
from .cache import LruCache
|
| 18 |
+
from .config import QuizConfig
|
| 19 |
+
from .lexical import BM25Index, normalize_text
|
| 20 |
+
from .parser import ParsedQuestions, QuestionRecord, QuizCsvValidationError, parse_questions_csv
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass(frozen=True)
|
| 26 |
+
class IndexManifest:
|
| 27 |
+
index_version: str
|
| 28 |
+
source_sha256: str
|
| 29 |
+
row_count: int
|
| 30 |
+
invalid_count: int
|
| 31 |
+
deleted_count: int
|
| 32 |
+
embedding_model: str
|
| 33 |
+
reranker_model: str
|
| 34 |
+
built_at: str
|
| 35 |
+
csv_updated_at: str
|
| 36 |
+
|
| 37 |
+
@classmethod
|
| 38 |
+
def from_dict(cls, raw: Dict[str, object]) -> "IndexManifest":
|
| 39 |
+
return cls(
|
| 40 |
+
index_version=str(raw.get("index_version") or ""),
|
| 41 |
+
source_sha256=str(raw.get("source_sha256") or ""),
|
| 42 |
+
row_count=int(raw.get("row_count") or 0),
|
| 43 |
+
invalid_count=int(raw.get("invalid_count") or 0),
|
| 44 |
+
deleted_count=int(raw.get("deleted_count") or 0),
|
| 45 |
+
embedding_model=str(raw.get("embedding_model") or ""),
|
| 46 |
+
reranker_model=str(raw.get("reranker_model") or ""),
|
| 47 |
+
built_at=str(raw.get("built_at") or ""),
|
| 48 |
+
csv_updated_at=str(raw.get("csv_updated_at") or ""),
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class LoadedQuizIndex:
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
*,
|
| 56 |
+
directory: Path,
|
| 57 |
+
manifest: IndexManifest,
|
| 58 |
+
faiss_index: faiss.Index,
|
| 59 |
+
records: Sequence[QuestionRecord],
|
| 60 |
+
):
|
| 61 |
+
self.directory = directory
|
| 62 |
+
self.manifest = manifest
|
| 63 |
+
self.faiss_index = faiss_index
|
| 64 |
+
self.records = list(records)
|
| 65 |
+
self.lexical = BM25Index([record.question for record in self.records])
|
| 66 |
+
self.id_to_index = {
|
| 67 |
+
record.question_id: index for index, record in enumerate(self.records)
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class QuizIndexManager:
|
| 72 |
+
def __init__(self, config: QuizConfig, models: ModelBundle):
|
| 73 |
+
self.config = config
|
| 74 |
+
self.models = models
|
| 75 |
+
self._active: Optional[LoadedQuizIndex] = None
|
| 76 |
+
self._swap_lock = threading.RLock()
|
| 77 |
+
self._build_lock = threading.Lock()
|
| 78 |
+
self._candidate_cache: LruCache[Tuple[object, ...], List[Tuple[int, float]]] = LruCache(
|
| 79 |
+
config.cache_size
|
| 80 |
+
)
|
| 81 |
+
self._aliases = self._load_aliases()
|
| 82 |
+
self.config.source_dir.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
self.config.index_dir.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
(self.config.index_dir / "versions").mkdir(parents=True, exist_ok=True)
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def active(self) -> Optional[LoadedQuizIndex]:
|
| 88 |
+
with self._swap_lock:
|
| 89 |
+
return self._active
|
| 90 |
+
|
| 91 |
+
def _load_aliases(self) -> Dict[str, List[str]]:
|
| 92 |
+
path = self.config.aliases_path
|
| 93 |
+
if not path.is_file():
|
| 94 |
+
return {}
|
| 95 |
+
try:
|
| 96 |
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
| 97 |
+
if not isinstance(raw, dict):
|
| 98 |
+
raise ValueError("aliases root must be an object")
|
| 99 |
+
aliases: Dict[str, List[str]] = {}
|
| 100 |
+
for key, values in raw.items():
|
| 101 |
+
canonical = normalize_text(str(key))
|
| 102 |
+
if not canonical:
|
| 103 |
+
continue
|
| 104 |
+
if isinstance(values, str):
|
| 105 |
+
candidates = [values]
|
| 106 |
+
elif isinstance(values, list):
|
| 107 |
+
candidates = values
|
| 108 |
+
else:
|
| 109 |
+
continue
|
| 110 |
+
clean = []
|
| 111 |
+
for value in candidates:
|
| 112 |
+
normalized = normalize_text(str(value))
|
| 113 |
+
if normalized and normalized not in clean:
|
| 114 |
+
clean.append(normalized)
|
| 115 |
+
if clean:
|
| 116 |
+
aliases[canonical] = clean
|
| 117 |
+
return aliases
|
| 118 |
+
except Exception:
|
| 119 |
+
logger.exception("[QUIZ_INDEX] Could not load alias file %s", path)
|
| 120 |
+
return {}
|
| 121 |
+
|
| 122 |
+
def reload_aliases(self) -> None:
|
| 123 |
+
self._aliases = self._load_aliases()
|
| 124 |
+
self._candidate_cache.clear()
|
| 125 |
+
|
| 126 |
+
def expand_query(self, query: str) -> Tuple[str, str]:
|
| 127 |
+
normalized = normalize_text(query)
|
| 128 |
+
expansions = [normalized] if normalized else []
|
| 129 |
+
normalized_tokens = set(normalized.split())
|
| 130 |
+
for canonical, variants in self._aliases.items():
|
| 131 |
+
variant_tokens = [set(item.split()) for item in variants]
|
| 132 |
+
if canonical in normalized or set(canonical.split()).issubset(normalized_tokens):
|
| 133 |
+
expansions.extend(variants)
|
| 134 |
+
elif any(tokens and tokens.issubset(normalized_tokens) for tokens in variant_tokens):
|
| 135 |
+
expansions.append(canonical)
|
| 136 |
+
expansions.extend(variants)
|
| 137 |
+
unique = []
|
| 138 |
+
for value in expansions:
|
| 139 |
+
if value and value not in unique:
|
| 140 |
+
unique.append(value)
|
| 141 |
+
return normalized, " ".join(unique)
|
| 142 |
+
|
| 143 |
+
def load_active(self) -> bool:
|
| 144 |
+
pointer = self.config.index_dir / "active.json"
|
| 145 |
+
if not pointer.is_file():
|
| 146 |
+
return False
|
| 147 |
+
raw = json.loads(pointer.read_text(encoding="utf-8"))
|
| 148 |
+
version = str(raw.get("index_version") or "").strip()
|
| 149 |
+
if not version:
|
| 150 |
+
return False
|
| 151 |
+
directory = self.config.index_dir / "versions" / version
|
| 152 |
+
loaded = self._load_version(directory)
|
| 153 |
+
with self._swap_lock:
|
| 154 |
+
self._active = loaded
|
| 155 |
+
self._candidate_cache.clear()
|
| 156 |
+
logger.info(
|
| 157 |
+
"[QUIZ_INDEX] Loaded version=%s rows=%d",
|
| 158 |
+
loaded.manifest.index_version,
|
| 159 |
+
loaded.manifest.row_count,
|
| 160 |
+
)
|
| 161 |
+
return True
|
| 162 |
+
|
| 163 |
+
def _load_version(self, directory: Path) -> LoadedQuizIndex:
|
| 164 |
+
manifest = IndexManifest.from_dict(
|
| 165 |
+
json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
|
| 166 |
+
)
|
| 167 |
+
rows = json.loads((directory / "records.json").read_text(encoding="utf-8"))
|
| 168 |
+
records = [QuestionRecord(**row) for row in rows]
|
| 169 |
+
index = faiss.read_index(str(directory / "questions.faiss"))
|
| 170 |
+
if index.ntotal != len(records):
|
| 171 |
+
raise RuntimeError(
|
| 172 |
+
f"Index/document mismatch: vectors={index.ntotal}, records={len(records)}"
|
| 173 |
+
)
|
| 174 |
+
return LoadedQuizIndex(
|
| 175 |
+
directory=directory,
|
| 176 |
+
manifest=manifest,
|
| 177 |
+
faiss_index=index,
|
| 178 |
+
records=records,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def _current_manifest(self) -> Optional[IndexManifest]:
|
| 182 |
+
active = self.active
|
| 183 |
+
return active.manifest if active else None
|
| 184 |
+
|
| 185 |
+
def rebuild(self, csv_path: Optional[Path] = None, force: bool = False) -> Dict[str, object]:
|
| 186 |
+
source = (csv_path or self.config.csv_path).resolve()
|
| 187 |
+
if not self._build_lock.acquire(blocking=False):
|
| 188 |
+
return {"status": "busy", "message": "An index rebuild is already running."}
|
| 189 |
+
try:
|
| 190 |
+
self.reload_aliases()
|
| 191 |
+
parsed = parse_questions_csv(source)
|
| 192 |
+
current = self._current_manifest()
|
| 193 |
+
if (
|
| 194 |
+
current
|
| 195 |
+
and current.source_sha256 == parsed.source_sha256
|
| 196 |
+
and current.embedding_model == self.config.embedding_model
|
| 197 |
+
and current.reranker_model == self.config.reranker_model
|
| 198 |
+
and not force
|
| 199 |
+
):
|
| 200 |
+
return {
|
| 201 |
+
"status": "unchanged",
|
| 202 |
+
"index_version": current.index_version,
|
| 203 |
+
"row_count": current.row_count,
|
| 204 |
+
}
|
| 205 |
+
if current and parsed.records:
|
| 206 |
+
minimum_rows = max(1, int(current.row_count * self.config.row_drop_ratio))
|
| 207 |
+
if len(parsed.records) < minimum_rows and not force:
|
| 208 |
+
raise QuizCsvValidationError(
|
| 209 |
+
"Quiz CSV row count dropped below the configured safety threshold: "
|
| 210 |
+
f"previous={current.row_count}, new={len(parsed.records)}, minimum={minimum_rows}."
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
version = f"quiz-{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}-{parsed.source_sha256[:12]}"
|
| 214 |
+
versions_dir = self.config.index_dir / "versions"
|
| 215 |
+
staging = Path(tempfile.mkdtemp(prefix=".staging-", dir=str(versions_dir)))
|
| 216 |
+
try:
|
| 217 |
+
loaded = self._build_version(staging, version, parsed, source)
|
| 218 |
+
final_dir = versions_dir / version
|
| 219 |
+
if final_dir.exists():
|
| 220 |
+
shutil.rmtree(final_dir)
|
| 221 |
+
os.replace(staging, final_dir)
|
| 222 |
+
loaded = self._load_version(final_dir)
|
| 223 |
+
self._smoke_test(loaded)
|
| 224 |
+
self._activate(loaded)
|
| 225 |
+
self._prune_versions()
|
| 226 |
+
return {
|
| 227 |
+
"status": "rebuilt",
|
| 228 |
+
"index_version": loaded.manifest.index_version,
|
| 229 |
+
"row_count": loaded.manifest.row_count,
|
| 230 |
+
"source_sha256": loaded.manifest.source_sha256,
|
| 231 |
+
}
|
| 232 |
+
finally:
|
| 233 |
+
if staging.exists():
|
| 234 |
+
shutil.rmtree(staging, ignore_errors=True)
|
| 235 |
+
finally:
|
| 236 |
+
self._build_lock.release()
|
| 237 |
+
|
| 238 |
+
def _build_version(
|
| 239 |
+
self,
|
| 240 |
+
directory: Path,
|
| 241 |
+
version: str,
|
| 242 |
+
parsed: ParsedQuestions,
|
| 243 |
+
source: Path,
|
| 244 |
+
) -> LoadedQuizIndex:
|
| 245 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 246 |
+
questions = [record.question for record in parsed.records]
|
| 247 |
+
logger.info("[QUIZ_INDEX] Embedding %d questions", len(questions))
|
| 248 |
+
vectors = self.models.embeddings.embed_documents(questions)
|
| 249 |
+
matrix = np.asarray(vectors, dtype="float32")
|
| 250 |
+
if matrix.ndim != 2 or matrix.shape[0] != len(parsed.records):
|
| 251 |
+
raise RuntimeError("Embedding model returned an invalid matrix.")
|
| 252 |
+
faiss.normalize_L2(matrix)
|
| 253 |
+
index = faiss.IndexFlatIP(matrix.shape[1])
|
| 254 |
+
index.add(matrix)
|
| 255 |
+
faiss.write_index(index, str(directory / "questions.faiss"))
|
| 256 |
+
(directory / "records.json").write_text(
|
| 257 |
+
json.dumps([asdict(record) for record in parsed.records], ensure_ascii=False),
|
| 258 |
+
encoding="utf-8",
|
| 259 |
+
)
|
| 260 |
+
csv_updated = datetime.fromtimestamp(
|
| 261 |
+
source.stat().st_mtime, tz=timezone.utc
|
| 262 |
+
).isoformat()
|
| 263 |
+
manifest = IndexManifest(
|
| 264 |
+
index_version=version,
|
| 265 |
+
source_sha256=parsed.source_sha256,
|
| 266 |
+
row_count=len(parsed.records),
|
| 267 |
+
invalid_count=parsed.invalid_count,
|
| 268 |
+
deleted_count=parsed.deleted_count,
|
| 269 |
+
embedding_model=self.config.embedding_model,
|
| 270 |
+
reranker_model=self.config.reranker_model,
|
| 271 |
+
built_at=datetime.now(timezone.utc).isoformat(),
|
| 272 |
+
csv_updated_at=csv_updated,
|
| 273 |
+
)
|
| 274 |
+
(directory / "manifest.json").write_text(
|
| 275 |
+
json.dumps(asdict(manifest), indent=2), encoding="utf-8"
|
| 276 |
+
)
|
| 277 |
+
return LoadedQuizIndex(
|
| 278 |
+
directory=directory,
|
| 279 |
+
manifest=manifest,
|
| 280 |
+
faiss_index=index,
|
| 281 |
+
records=parsed.records,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
def _smoke_test(self, loaded: LoadedQuizIndex) -> None:
|
| 285 |
+
if not loaded.records or loaded.faiss_index.ntotal <= 0:
|
| 286 |
+
raise RuntimeError("Smoke test failed: empty quiz index.")
|
| 287 |
+
sample = loaded.records[0]
|
| 288 |
+
query = " ".join(sample.question.split()[:8]) or sample.question
|
| 289 |
+
vector = np.asarray(
|
| 290 |
+
[self.models.embeddings.embed_query(query)], dtype="float32"
|
| 291 |
+
)
|
| 292 |
+
faiss.normalize_L2(vector)
|
| 293 |
+
_, indices = loaded.faiss_index.search(vector, min(20, len(loaded.records)))
|
| 294 |
+
if 0 not in set(int(value) for value in indices[0] if value >= 0):
|
| 295 |
+
raise RuntimeError("Smoke test failed: sample question was not retrievable.")
|
| 296 |
+
lexical = loaded.lexical.search(query, min(20, len(loaded.records)))
|
| 297 |
+
if not lexical:
|
| 298 |
+
raise RuntimeError("Smoke test failed: lexical index returned no result.")
|
| 299 |
+
|
| 300 |
+
def _activate(self, loaded: LoadedQuizIndex) -> None:
|
| 301 |
+
pointer = self.config.index_dir / "active.json"
|
| 302 |
+
temp_pointer = self.config.index_dir / ".active.json.tmp"
|
| 303 |
+
temp_pointer.write_text(
|
| 304 |
+
json.dumps(
|
| 305 |
+
{
|
| 306 |
+
"index_version": loaded.manifest.index_version,
|
| 307 |
+
"activated_at": datetime.now(timezone.utc).isoformat(),
|
| 308 |
+
},
|
| 309 |
+
indent=2,
|
| 310 |
+
),
|
| 311 |
+
encoding="utf-8",
|
| 312 |
+
)
|
| 313 |
+
os.replace(temp_pointer, pointer)
|
| 314 |
+
with self._swap_lock:
|
| 315 |
+
self._active = loaded
|
| 316 |
+
self._candidate_cache.clear()
|
| 317 |
+
logger.info(
|
| 318 |
+
"[QUIZ_INDEX] Activated version=%s rows=%d",
|
| 319 |
+
loaded.manifest.index_version,
|
| 320 |
+
loaded.manifest.row_count,
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
def _prune_versions(self) -> None:
|
| 324 |
+
active = self.active
|
| 325 |
+
active_version = active.manifest.index_version if active else ""
|
| 326 |
+
versions_dir = self.config.index_dir / "versions"
|
| 327 |
+
directories = sorted(
|
| 328 |
+
[path for path in versions_dir.iterdir() if path.is_dir() and not path.name.startswith(".staging-")],
|
| 329 |
+
key=lambda path: path.stat().st_mtime,
|
| 330 |
+
reverse=True,
|
| 331 |
+
)
|
| 332 |
+
keep = {path.name for path in directories[: self.config.keep_versions]}
|
| 333 |
+
if active_version:
|
| 334 |
+
keep.add(active_version)
|
| 335 |
+
for path in directories:
|
| 336 |
+
if path.name not in keep:
|
| 337 |
+
shutil.rmtree(path, ignore_errors=True)
|
| 338 |
+
|
| 339 |
+
def refresh_from_google(self, force: bool = False) -> Dict[str, object]:
|
| 340 |
+
if not self.config.csv_url:
|
| 341 |
+
raise RuntimeError("QUIZ_CSV_URL is not configured.")
|
| 342 |
+
with tempfile.TemporaryDirectory(prefix="quiz-csv-refresh-") as directory:
|
| 343 |
+
downloaded = Path(directory) / "quiz_questions.csv"
|
| 344 |
+
if not download_gdrive_file(self.config.csv_url, str(downloaded)):
|
| 345 |
+
raise RuntimeError("Could not download the quiz CSV from Google Drive.")
|
| 346 |
+
result = self.rebuild(downloaded, force=force)
|
| 347 |
+
if result.get("status") in {"rebuilt", "unchanged"}:
|
| 348 |
+
self.config.csv_path.parent.mkdir(parents=True, exist_ok=True)
|
| 349 |
+
shutil.copy2(downloaded, self.config.csv_path)
|
| 350 |
+
return result
|
| 351 |
+
|
| 352 |
+
def status(self) -> Dict[str, object]:
|
| 353 |
+
active = self.active
|
| 354 |
+
manifest = active.manifest if active else None
|
| 355 |
+
return {
|
| 356 |
+
"ready": active is not None,
|
| 357 |
+
"index_version": manifest.index_version if manifest else None,
|
| 358 |
+
"source_sha256": manifest.source_sha256 if manifest else None,
|
| 359 |
+
"row_count": manifest.row_count if manifest else 0,
|
| 360 |
+
"invalid_count": manifest.invalid_count if manifest else 0,
|
| 361 |
+
"deleted_count": manifest.deleted_count if manifest else 0,
|
| 362 |
+
"built_at": manifest.built_at if manifest else None,
|
| 363 |
+
"csv_updated_at": manifest.csv_updated_at if manifest else None,
|
| 364 |
+
"embedding_model": self.models.embedding_model_name,
|
| 365 |
+
"reranker_model": self.models.reranker_model_name,
|
| 366 |
+
"reranker_ready": self.models.reranker is not None,
|
| 367 |
+
"cache_entries": len(self._candidate_cache),
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
def cached_candidates(self, key: Tuple[object, ...]) -> Optional[List[Tuple[int, float]]]:
|
| 371 |
+
return self._candidate_cache.get(key)
|
| 372 |
+
|
| 373 |
+
def store_candidates(self, key: Tuple[object, ...], value: List[Tuple[int, float]]) -> None:
|
| 374 |
+
self._candidate_cache.put(key, value)
|
custom_quiz/lexical.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import re
|
| 3 |
+
import unicodedata
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import DefaultDict, Dict, Iterable, List, Sequence, Tuple
|
| 7 |
+
|
| 8 |
+
_TOKEN_RE = re.compile(r"[\w\u0600-\u06ff]+", re.UNICODE)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def normalize_text(value: str) -> str:
|
| 12 |
+
normalized = unicodedata.normalize("NFKC", value or "").casefold()
|
| 13 |
+
return " ".join(_TOKEN_RE.findall(normalized))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def tokenize(value: str) -> List[str]:
|
| 17 |
+
normalized = normalize_text(value)
|
| 18 |
+
return normalized.split() if normalized else []
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(frozen=True)
|
| 22 |
+
class LexicalHit:
|
| 23 |
+
index: int
|
| 24 |
+
score: float
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class BM25Index:
|
| 28 |
+
def __init__(self, documents: Sequence[str], k1: float = 1.5, b: float = 0.75):
|
| 29 |
+
self.k1 = k1
|
| 30 |
+
self.b = b
|
| 31 |
+
self.doc_count = len(documents)
|
| 32 |
+
self.doc_lengths: List[int] = []
|
| 33 |
+
self.term_frequencies: List[Counter[str]] = []
|
| 34 |
+
document_frequency: Counter[str] = Counter()
|
| 35 |
+
self.postings: DefaultDict[str, List[int]] = defaultdict(list)
|
| 36 |
+
|
| 37 |
+
for index, document in enumerate(documents):
|
| 38 |
+
frequencies = Counter(tokenize(document))
|
| 39 |
+
self.term_frequencies.append(frequencies)
|
| 40 |
+
self.doc_lengths.append(sum(frequencies.values()))
|
| 41 |
+
for term in frequencies:
|
| 42 |
+
document_frequency[term] += 1
|
| 43 |
+
self.postings[term].append(index)
|
| 44 |
+
|
| 45 |
+
self.average_length = (
|
| 46 |
+
sum(self.doc_lengths) / self.doc_count if self.doc_count else 0.0
|
| 47 |
+
)
|
| 48 |
+
self.idf = {
|
| 49 |
+
term: math.log(1.0 + (self.doc_count - freq + 0.5) / (freq + 0.5))
|
| 50 |
+
for term, freq in document_frequency.items()
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
def search(self, query: str, limit: int) -> List[LexicalHit]:
|
| 54 |
+
if limit <= 0 or not self.doc_count:
|
| 55 |
+
return []
|
| 56 |
+
query_terms = tokenize(query)
|
| 57 |
+
if not query_terms:
|
| 58 |
+
return []
|
| 59 |
+
|
| 60 |
+
candidate_indices = set()
|
| 61 |
+
for term in query_terms:
|
| 62 |
+
candidate_indices.update(self.postings.get(term, ()))
|
| 63 |
+
if not candidate_indices:
|
| 64 |
+
return []
|
| 65 |
+
|
| 66 |
+
scores: Dict[int, float] = defaultdict(float)
|
| 67 |
+
for index in candidate_indices:
|
| 68 |
+
doc_length = self.doc_lengths[index]
|
| 69 |
+
frequencies = self.term_frequencies[index]
|
| 70 |
+
for term in query_terms:
|
| 71 |
+
frequency = frequencies.get(term, 0)
|
| 72 |
+
if frequency <= 0:
|
| 73 |
+
continue
|
| 74 |
+
denominator = frequency + self.k1 * (
|
| 75 |
+
1.0 - self.b
|
| 76 |
+
+ self.b * doc_length / max(self.average_length, 1.0)
|
| 77 |
+
)
|
| 78 |
+
scores[index] += self.idf.get(term, 0.0) * (
|
| 79 |
+
frequency * (self.k1 + 1.0) / denominator
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
ranked = sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
|
| 83 |
+
return [LexicalHit(index=index, score=score) for index, score in ranked[:limit]]
|
custom_quiz/parser.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import hashlib
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Dict, List, Optional
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# The retrieval index intentionally contains only the authoritative database ID
|
| 9 |
+
# and exact question text. All mutable eligibility/filter metadata is checked by
|
| 10 |
+
# the Supabase Edge Function against the live quiz_questions row.
|
| 11 |
+
REQUIRED_COLUMNS = {"id", "question"}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass(frozen=True)
|
| 15 |
+
class QuestionRecord:
|
| 16 |
+
question_id: int
|
| 17 |
+
question: str
|
| 18 |
+
# Retained for backwards-compatible index deserialization. New two-column
|
| 19 |
+
# CSV builds leave these unset because Supabase owns live filtering.
|
| 20 |
+
source_id: Optional[int] = None
|
| 21 |
+
category_id: Optional[int] = None
|
| 22 |
+
chapter_id: Optional[int] = None
|
| 23 |
+
difficulty: Optional[int] = None
|
| 24 |
+
flash: bool = False
|
| 25 |
+
event_seerah: bool = False
|
| 26 |
+
updated_at: str = ""
|
| 27 |
+
|
| 28 |
+
def metadata(self) -> Dict[str, object]:
|
| 29 |
+
return {"question_id": self.question_id}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass(frozen=True)
|
| 33 |
+
class ParsedQuestions:
|
| 34 |
+
records: List[QuestionRecord]
|
| 35 |
+
source_sha256: str
|
| 36 |
+
invalid_count: int
|
| 37 |
+
deleted_count: int
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class QuizCsvValidationError(ValueError):
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _text(value: object) -> str:
|
| 45 |
+
text = str(value or "").strip()
|
| 46 |
+
return "" if text.lower() == "null" else text
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _required_positive_int(value: object, field: str, row_number: int) -> int:
|
| 50 |
+
text = _text(value)
|
| 51 |
+
if not text:
|
| 52 |
+
raise QuizCsvValidationError(f"Row {row_number}: {field} is required.")
|
| 53 |
+
try:
|
| 54 |
+
numeric = float(text)
|
| 55 |
+
except ValueError as exc:
|
| 56 |
+
raise QuizCsvValidationError(
|
| 57 |
+
f"Row {row_number}: {field} is not an integer."
|
| 58 |
+
) from exc
|
| 59 |
+
if not numeric.is_integer():
|
| 60 |
+
raise QuizCsvValidationError(f"Row {row_number}: {field} is not an integer.")
|
| 61 |
+
parsed = int(numeric)
|
| 62 |
+
if parsed <= 0:
|
| 63 |
+
raise QuizCsvValidationError(f"Row {row_number}: {field} must be positive.")
|
| 64 |
+
return parsed
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def file_sha256(path: Path) -> str:
|
| 68 |
+
digest = hashlib.sha256()
|
| 69 |
+
with path.open("rb") as handle:
|
| 70 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 71 |
+
digest.update(chunk)
|
| 72 |
+
return digest.hexdigest()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def parse_questions_csv(path: Path) -> ParsedQuestions:
|
| 76 |
+
if not path.is_file() or path.stat().st_size <= 0:
|
| 77 |
+
raise QuizCsvValidationError("Quiz CSV is missing or empty.")
|
| 78 |
+
|
| 79 |
+
records: List[QuestionRecord] = []
|
| 80 |
+
seen_ids = set()
|
| 81 |
+
invalid_count = 0
|
| 82 |
+
|
| 83 |
+
with path.open("r", encoding="utf-8-sig", newline="") as handle:
|
| 84 |
+
reader = csv.DictReader(handle)
|
| 85 |
+
fieldnames = {str(name or "").strip() for name in (reader.fieldnames or [])}
|
| 86 |
+
missing = sorted(REQUIRED_COLUMNS - fieldnames)
|
| 87 |
+
if missing:
|
| 88 |
+
raise QuizCsvValidationError(
|
| 89 |
+
"Quiz CSV is missing required columns: " + ", ".join(missing)
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
for row_number, raw in enumerate(reader, start=2):
|
| 93 |
+
try:
|
| 94 |
+
question_id = _required_positive_int(raw.get("id"), "id", row_number)
|
| 95 |
+
question = _text(raw.get("question"))
|
| 96 |
+
if not question:
|
| 97 |
+
raise QuizCsvValidationError(f"Row {row_number}: question is blank.")
|
| 98 |
+
if question_id in seen_ids:
|
| 99 |
+
raise QuizCsvValidationError(
|
| 100 |
+
f"Row {row_number}: duplicate id {question_id}."
|
| 101 |
+
)
|
| 102 |
+
seen_ids.add(question_id)
|
| 103 |
+
records.append(
|
| 104 |
+
QuestionRecord(question_id=question_id, question=question)
|
| 105 |
+
)
|
| 106 |
+
except QuizCsvValidationError:
|
| 107 |
+
invalid_count += 1
|
| 108 |
+
raise
|
| 109 |
+
|
| 110 |
+
if not records:
|
| 111 |
+
raise QuizCsvValidationError("Quiz CSV contains no questions.")
|
| 112 |
+
|
| 113 |
+
return ParsedQuestions(
|
| 114 |
+
records=records,
|
| 115 |
+
source_sha256=file_sha256(path),
|
| 116 |
+
invalid_count=invalid_count,
|
| 117 |
+
# Deleted rows cannot be represented in a two-column CSV. The export
|
| 118 |
+
# excludes them, and the Edge Function rechecks is_deleted live.
|
| 119 |
+
deleted_count=0,
|
| 120 |
+
)
|
custom_quiz/search.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import time
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
|
| 5 |
+
|
| 6 |
+
import faiss
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from shared_models import ModelBundle
|
| 10 |
+
from .config import QuizConfig
|
| 11 |
+
from .index_manager import LoadedQuizIndex, QuizIndexManager
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass(frozen=True)
|
| 17 |
+
class SearchFilters:
|
| 18 |
+
source_ids: Tuple[int, ...] = ()
|
| 19 |
+
category_ids: Tuple[int, ...] = ()
|
| 20 |
+
difficulty: Tuple[int, ...] = ()
|
| 21 |
+
|
| 22 |
+
@classmethod
|
| 23 |
+
def from_payload(cls, raw: object) -> "SearchFilters":
|
| 24 |
+
data = raw if isinstance(raw, dict) else {}
|
| 25 |
+
|
| 26 |
+
def positive_ints(
|
| 27 |
+
value: object,
|
| 28 |
+
allowed: Optional[Set[int]] = None,
|
| 29 |
+
max_items: int = 100,
|
| 30 |
+
) -> Tuple[int, ...]:
|
| 31 |
+
values = value if isinstance(value, list) else []
|
| 32 |
+
if len(values) > max_items:
|
| 33 |
+
raise ValueError(f"A filter contains more than {max_items} values.")
|
| 34 |
+
clean = set()
|
| 35 |
+
for item in values:
|
| 36 |
+
try:
|
| 37 |
+
parsed = int(item)
|
| 38 |
+
except (TypeError, ValueError):
|
| 39 |
+
continue
|
| 40 |
+
if parsed > 0 and (allowed is None or parsed in allowed):
|
| 41 |
+
clean.add(parsed)
|
| 42 |
+
return tuple(sorted(clean))
|
| 43 |
+
|
| 44 |
+
return cls(
|
| 45 |
+
source_ids=positive_ints(data.get("source_ids")),
|
| 46 |
+
category_ids=positive_ints(data.get("category_ids")),
|
| 47 |
+
difficulty=positive_ints(data.get("difficulty"), {1, 2, 3}),
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def cache_key(self) -> Tuple[object, ...]:
|
| 51 |
+
# The two-column RAG index has no live database metadata. Candidate
|
| 52 |
+
# ranking is therefore query/index-version specific only. Supabase
|
| 53 |
+
# applies source/category/difficulty eligibility after hydration.
|
| 54 |
+
return ()
|
| 55 |
+
|
| 56 |
+
def matches(self, metadata: Dict[str, object]) -> bool:
|
| 57 |
+
# Intentionally do not filter in the retrieval service. The Edge
|
| 58 |
+
# Function owns all authoritative live database filtering.
|
| 59 |
+
return True
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@dataclass(frozen=True)
|
| 63 |
+
class RankedQuestion:
|
| 64 |
+
question_id: int
|
| 65 |
+
score: float
|
| 66 |
+
rank: int
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass(frozen=True)
|
| 70 |
+
class SearchResponse:
|
| 71 |
+
normalized_query: str
|
| 72 |
+
index_version: str
|
| 73 |
+
results: List[RankedQuestion]
|
| 74 |
+
requested: int
|
| 75 |
+
returned: int
|
| 76 |
+
exhausted: bool
|
| 77 |
+
candidate_count: int
|
| 78 |
+
excluded_count: int
|
| 79 |
+
timings_ms: Dict[str, float]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class HybridQuizSearcher:
|
| 83 |
+
def __init__(
|
| 84 |
+
self,
|
| 85 |
+
config: QuizConfig,
|
| 86 |
+
models: ModelBundle,
|
| 87 |
+
manager: QuizIndexManager,
|
| 88 |
+
):
|
| 89 |
+
self.config = config
|
| 90 |
+
self.models = models
|
| 91 |
+
self.manager = manager
|
| 92 |
+
|
| 93 |
+
def search(
|
| 94 |
+
self,
|
| 95 |
+
*,
|
| 96 |
+
query: str,
|
| 97 |
+
limit: int,
|
| 98 |
+
exclude_ids: Set[int],
|
| 99 |
+
filters: SearchFilters,
|
| 100 |
+
) -> SearchResponse:
|
| 101 |
+
active = self.manager.active
|
| 102 |
+
if active is None:
|
| 103 |
+
raise RuntimeError("Quiz index is not ready.")
|
| 104 |
+
normalized, expanded = self.manager.expand_query(query)
|
| 105 |
+
if not normalized:
|
| 106 |
+
raise ValueError("Query is required.")
|
| 107 |
+
|
| 108 |
+
timings: Dict[str, float] = {}
|
| 109 |
+
cache_key = (
|
| 110 |
+
normalized,
|
| 111 |
+
filters.cache_key(),
|
| 112 |
+
active.manifest.index_version,
|
| 113 |
+
)
|
| 114 |
+
started = time.perf_counter()
|
| 115 |
+
cached = self.manager.cached_candidates(cache_key)
|
| 116 |
+
timings["cache_lookup"] = (time.perf_counter() - started) * 1000.0
|
| 117 |
+
|
| 118 |
+
candidate_sizes = []
|
| 119 |
+
for size in (
|
| 120 |
+
max(100, limit * 5),
|
| 121 |
+
max(300, limit * 15),
|
| 122 |
+
max(1000, limit * 50),
|
| 123 |
+
len(active.records),
|
| 124 |
+
):
|
| 125 |
+
bounded = min(len(active.records), size)
|
| 126 |
+
if bounded > 0 and bounded not in candidate_sizes:
|
| 127 |
+
candidate_sizes.append(bounded)
|
| 128 |
+
|
| 129 |
+
candidates = cached or []
|
| 130 |
+
if cached is None:
|
| 131 |
+
# Build a user-independent ranked candidate cache. Exclusions are
|
| 132 |
+
# deliberately not applied here, otherwise one user's history can
|
| 133 |
+
# remove top candidates from every later user's cached results.
|
| 134 |
+
global_candidate_size = min(
|
| 135 |
+
len(active.records),
|
| 136 |
+
max(1000, self.config.cache_candidate_count * 2, limit * 20),
|
| 137 |
+
)
|
| 138 |
+
candidates, stage_timings = self._rank_candidates(
|
| 139 |
+
active=active,
|
| 140 |
+
query=expanded or normalized,
|
| 141 |
+
candidate_size=global_candidate_size,
|
| 142 |
+
filters=filters,
|
| 143 |
+
exclude_ids=set(),
|
| 144 |
+
max_output=self.config.cache_candidate_count,
|
| 145 |
+
)
|
| 146 |
+
for key, value in stage_timings.items():
|
| 147 |
+
timings[key] = timings.get(key, 0.0) + value
|
| 148 |
+
self.manager.store_candidates(
|
| 149 |
+
cache_key,
|
| 150 |
+
candidates[: self.config.cache_candidate_count],
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
selected = self._filter_candidates(candidates, exclude_ids, filters, limit)
|
| 154 |
+
if len(selected) < limit:
|
| 155 |
+
# Exclusions are applied before reranking for each adaptive pass so
|
| 156 |
+
# a heavily exposed user can still receive the requested number of
|
| 157 |
+
# unseen questions instead of only the global top-N remainder.
|
| 158 |
+
for candidate_size in candidate_sizes:
|
| 159 |
+
request_candidates, stage_timings = self._rank_candidates(
|
| 160 |
+
active=active,
|
| 161 |
+
query=expanded or normalized,
|
| 162 |
+
candidate_size=candidate_size,
|
| 163 |
+
filters=filters,
|
| 164 |
+
exclude_ids=exclude_ids,
|
| 165 |
+
max_output=max(self.config.cache_candidate_count, limit),
|
| 166 |
+
)
|
| 167 |
+
for key, value in stage_timings.items():
|
| 168 |
+
timings[key] = timings.get(key, 0.0) + value
|
| 169 |
+
selected = request_candidates[:limit]
|
| 170 |
+
candidates = request_candidates
|
| 171 |
+
if len(selected) >= limit or candidate_size >= len(active.records):
|
| 172 |
+
break
|
| 173 |
+
|
| 174 |
+
results = [
|
| 175 |
+
RankedQuestion(question_id=question_id, score=score, rank=index + 1)
|
| 176 |
+
for index, (question_id, score) in enumerate(selected[:limit])
|
| 177 |
+
if score >= self.config.min_score
|
| 178 |
+
]
|
| 179 |
+
exhausted = len(results) < limit
|
| 180 |
+
timings["total"] = (time.perf_counter() - started) * 1000.0
|
| 181 |
+
return SearchResponse(
|
| 182 |
+
normalized_query=normalized,
|
| 183 |
+
index_version=active.manifest.index_version,
|
| 184 |
+
results=results,
|
| 185 |
+
requested=limit,
|
| 186 |
+
returned=len(results),
|
| 187 |
+
exhausted=exhausted,
|
| 188 |
+
candidate_count=len(candidates),
|
| 189 |
+
excluded_count=len(exclude_ids),
|
| 190 |
+
timings_ms={key: round(value, 3) for key, value in timings.items()},
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
def _filter_candidates(
|
| 194 |
+
self,
|
| 195 |
+
candidates: Sequence[Tuple[int, float]],
|
| 196 |
+
exclude_ids: Set[int],
|
| 197 |
+
filters: SearchFilters,
|
| 198 |
+
limit: int,
|
| 199 |
+
) -> List[Tuple[int, float]]:
|
| 200 |
+
active = self.manager.active
|
| 201 |
+
if active is None:
|
| 202 |
+
return []
|
| 203 |
+
selected: List[Tuple[int, float]] = []
|
| 204 |
+
for question_id, score in candidates:
|
| 205 |
+
if question_id in exclude_ids:
|
| 206 |
+
continue
|
| 207 |
+
index = active.id_to_index.get(question_id)
|
| 208 |
+
if index is None or not filters.matches(active.records[index].metadata()):
|
| 209 |
+
continue
|
| 210 |
+
selected.append((question_id, score))
|
| 211 |
+
if len(selected) >= limit:
|
| 212 |
+
break
|
| 213 |
+
return selected
|
| 214 |
+
|
| 215 |
+
def _rank_candidates(
|
| 216 |
+
self,
|
| 217 |
+
*,
|
| 218 |
+
active: LoadedQuizIndex,
|
| 219 |
+
query: str,
|
| 220 |
+
candidate_size: int,
|
| 221 |
+
filters: SearchFilters,
|
| 222 |
+
exclude_ids: Set[int],
|
| 223 |
+
max_output: int,
|
| 224 |
+
) -> Tuple[List[Tuple[int, float]], Dict[str, float]]:
|
| 225 |
+
timings: Dict[str, float] = {}
|
| 226 |
+
|
| 227 |
+
embedding_started = time.perf_counter()
|
| 228 |
+
query_vector = np.asarray(
|
| 229 |
+
[self.models.embeddings.embed_query(query)], dtype="float32"
|
| 230 |
+
)
|
| 231 |
+
faiss.normalize_L2(query_vector)
|
| 232 |
+
timings["embedding"] = (time.perf_counter() - embedding_started) * 1000.0
|
| 233 |
+
|
| 234 |
+
dense_started = time.perf_counter()
|
| 235 |
+
dense_scores, dense_indices = active.faiss_index.search(
|
| 236 |
+
query_vector, min(candidate_size, len(active.records))
|
| 237 |
+
)
|
| 238 |
+
dense_ranked = [
|
| 239 |
+
(int(index), float(score))
|
| 240 |
+
for index, score in zip(dense_indices[0], dense_scores[0])
|
| 241 |
+
if index >= 0
|
| 242 |
+
]
|
| 243 |
+
timings["dense"] = (time.perf_counter() - dense_started) * 1000.0
|
| 244 |
+
|
| 245 |
+
lexical_started = time.perf_counter()
|
| 246 |
+
lexical_hits = active.lexical.search(query, candidate_size)
|
| 247 |
+
timings["lexical"] = (time.perf_counter() - lexical_started) * 1000.0
|
| 248 |
+
|
| 249 |
+
fused: Dict[int, float] = {}
|
| 250 |
+
raw_dense: Dict[int, float] = {}
|
| 251 |
+
for rank, (index, score) in enumerate(dense_ranked, start=1):
|
| 252 |
+
fused[index] = fused.get(index, 0.0) + self.config.dense_weight / (
|
| 253 |
+
self.config.rrf_k + rank
|
| 254 |
+
)
|
| 255 |
+
raw_dense[index] = score
|
| 256 |
+
for rank, hit in enumerate(lexical_hits, start=1):
|
| 257 |
+
fused[hit.index] = fused.get(hit.index, 0.0) + self.config.lexical_weight / (
|
| 258 |
+
self.config.rrf_k + rank
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
fused_ranked = sorted(fused.items(), key=lambda pair: pair[1], reverse=True)
|
| 262 |
+
eligible: List[Tuple[int, float]] = []
|
| 263 |
+
for index, fused_score in fused_ranked:
|
| 264 |
+
record = active.records[index]
|
| 265 |
+
if record.question_id in exclude_ids:
|
| 266 |
+
continue
|
| 267 |
+
if not filters.matches(record.metadata()):
|
| 268 |
+
continue
|
| 269 |
+
eligible.append((index, fused_score))
|
| 270 |
+
|
| 271 |
+
rerank_started = time.perf_counter()
|
| 272 |
+
rerank_cap = min(len(eligible), max(1, max_output))
|
| 273 |
+
rerank_input = eligible[:rerank_cap]
|
| 274 |
+
ranked: List[Tuple[int, float]] = []
|
| 275 |
+
if self.models.reranker is not None and rerank_input:
|
| 276 |
+
items = [
|
| 277 |
+
(index, active.records[index].question) for index, _ in rerank_input
|
| 278 |
+
]
|
| 279 |
+
reranked = self.models.reranker.rank(query, items, top_k=len(items))
|
| 280 |
+
for index, score in reranked:
|
| 281 |
+
ranked.append((active.records[int(index)].question_id, float(score)))
|
| 282 |
+
else:
|
| 283 |
+
for index, score in rerank_input:
|
| 284 |
+
dense = raw_dense.get(index, 0.0)
|
| 285 |
+
ranked.append((active.records[index].question_id, float(score + dense)))
|
| 286 |
+
timings["reranker"] = (time.perf_counter() - rerank_started) * 1000.0
|
| 287 |
+
return ranked, timings
|
custom_quiz_app.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import binascii
|
| 3 |
+
import functools
|
| 4 |
+
import hmac
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import threading
|
| 8 |
+
import time
|
| 9 |
+
from dataclasses import asdict
|
| 10 |
+
from typing import Dict, Set
|
| 11 |
+
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
from flask import Flask, Response, jsonify, request
|
| 14 |
+
from werkzeug.exceptions import RequestEntityTooLarge
|
| 15 |
+
|
| 16 |
+
from shared_models import ModelBundle
|
| 17 |
+
from custom_quiz.config import QuizConfig
|
| 18 |
+
from custom_quiz.index_manager import QuizIndexManager
|
| 19 |
+
from custom_quiz.search import HybridQuizSearcher, SearchFilters
|
| 20 |
+
|
| 21 |
+
load_dotenv()
|
| 22 |
+
logging.basicConfig(
|
| 23 |
+
level=os.getenv("LOG_LEVEL", "INFO").upper(),
|
| 24 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 25 |
+
)
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
config = QuizConfig.from_env()
|
| 29 |
+
app = Flask(__name__)
|
| 30 |
+
app.config["MAX_CONTENT_LENGTH"] = config.body_limit_bytes
|
| 31 |
+
|
| 32 |
+
models = ModelBundle.load(
|
| 33 |
+
embedding_model_name=config.embedding_model,
|
| 34 |
+
reranker_model_name=config.reranker_model,
|
| 35 |
+
use_gpu_for_embeddings=config.embedding_gpu,
|
| 36 |
+
enable_reranker=config.reranker_enabled,
|
| 37 |
+
)
|
| 38 |
+
manager = QuizIndexManager(config, models)
|
| 39 |
+
searcher = HybridQuizSearcher(config, models, manager)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _basic_credentials() -> tuple[str, str]:
|
| 43 |
+
raw = request.headers.get("Authorization", "").strip()
|
| 44 |
+
if not raw.lower().startswith("basic "):
|
| 45 |
+
return "", ""
|
| 46 |
+
encoded = raw[6:].strip()
|
| 47 |
+
if not encoded:
|
| 48 |
+
return "", ""
|
| 49 |
+
try:
|
| 50 |
+
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
|
| 51 |
+
except (binascii.Error, UnicodeDecodeError, ValueError):
|
| 52 |
+
return "", ""
|
| 53 |
+
if ":" not in decoded:
|
| 54 |
+
return "", ""
|
| 55 |
+
return tuple(decoded.split(":", 1))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _requires_basic_auth(expected_username: str, expected_password: str):
|
| 59 |
+
def decorator(function):
|
| 60 |
+
@functools.wraps(function)
|
| 61 |
+
def wrapped(*args, **kwargs):
|
| 62 |
+
provided_username, provided_password = _basic_credentials()
|
| 63 |
+
username_ok = bool(expected_username) and hmac.compare_digest(
|
| 64 |
+
provided_username, expected_username
|
| 65 |
+
)
|
| 66 |
+
password_ok = bool(expected_password) and hmac.compare_digest(
|
| 67 |
+
provided_password, expected_password
|
| 68 |
+
)
|
| 69 |
+
if not username_ok or not password_ok:
|
| 70 |
+
response = jsonify({"error": "Unauthorized"})
|
| 71 |
+
response.headers["WWW-Authenticate"] = 'Basic realm="custom-quiz-api"'
|
| 72 |
+
return response, 401
|
| 73 |
+
return function(*args, **kwargs)
|
| 74 |
+
return wrapped
|
| 75 |
+
return decorator
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _positive_int(value: object, default: int) -> int:
|
| 79 |
+
try:
|
| 80 |
+
parsed = int(value)
|
| 81 |
+
except (TypeError, ValueError):
|
| 82 |
+
return default
|
| 83 |
+
return parsed
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _exclude_ids(value: object) -> Set[int]:
|
| 87 |
+
if not isinstance(value, list):
|
| 88 |
+
return set()
|
| 89 |
+
if len(value) > config.max_exclude_ids:
|
| 90 |
+
raise ValueError(
|
| 91 |
+
f"exclude_ids exceeds the maximum of {config.max_exclude_ids}."
|
| 92 |
+
)
|
| 93 |
+
result = set()
|
| 94 |
+
for item in value:
|
| 95 |
+
try:
|
| 96 |
+
parsed = int(item)
|
| 97 |
+
except (TypeError, ValueError):
|
| 98 |
+
continue
|
| 99 |
+
if parsed > 0:
|
| 100 |
+
result.add(parsed)
|
| 101 |
+
return result
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _initialize() -> None:
|
| 105 |
+
try:
|
| 106 |
+
if manager.load_active():
|
| 107 |
+
return
|
| 108 |
+
except Exception:
|
| 109 |
+
logger.exception("[CUSTOM_QUIZ] Active index could not be loaded.")
|
| 110 |
+
try:
|
| 111 |
+
if config.csv_path.is_file():
|
| 112 |
+
manager.rebuild(config.csv_path)
|
| 113 |
+
return
|
| 114 |
+
if config.csv_url:
|
| 115 |
+
manager.refresh_from_google()
|
| 116 |
+
except Exception:
|
| 117 |
+
logger.exception(
|
| 118 |
+
"[CUSTOM_QUIZ] Startup index initialization failed; health will remain unready."
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _refresh_loop() -> None:
|
| 123 |
+
while True:
|
| 124 |
+
time.sleep(config.refresh_minutes * 60)
|
| 125 |
+
try:
|
| 126 |
+
manager.refresh_from_google()
|
| 127 |
+
except Exception:
|
| 128 |
+
logger.exception("[CUSTOM_QUIZ] Scheduled CSV refresh failed.")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
_initialize()
|
| 132 |
+
if config.refresh_minutes > 0 and config.csv_url:
|
| 133 |
+
threading.Thread(target=_refresh_loop, daemon=True).start()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@app.errorhandler(RequestEntityTooLarge)
|
| 137 |
+
def body_too_large(_: RequestEntityTooLarge):
|
| 138 |
+
return jsonify({"error": "Request body is too large."}), 413
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@app.get("/health")
|
| 142 |
+
def health():
|
| 143 |
+
status = manager.status()
|
| 144 |
+
return jsonify({"status": "ok" if status["ready"] else "unready", **status}), (200 if status["ready"] else 503)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@app.post("/v1/custom-quiz/search")
|
| 148 |
+
@_requires_basic_auth(config.api_username, config.api_password)
|
| 149 |
+
def custom_quiz_search():
|
| 150 |
+
data = request.get_json(silent=True)
|
| 151 |
+
if not isinstance(data, dict):
|
| 152 |
+
return jsonify({"error": "Request body must be a JSON object."}), 400
|
| 153 |
+
|
| 154 |
+
query = str(data.get("query") or "").strip()
|
| 155 |
+
if not query:
|
| 156 |
+
return jsonify({"error": "query is required."}), 400
|
| 157 |
+
if len(query) > 300:
|
| 158 |
+
return jsonify({"error": "query is too long."}), 400
|
| 159 |
+
|
| 160 |
+
limit = _positive_int(data.get("limit"), 10)
|
| 161 |
+
if limit < 1 or limit > config.max_results:
|
| 162 |
+
return jsonify({"error": f"limit must be between 1 and {config.max_results}."}), 400
|
| 163 |
+
|
| 164 |
+
mode = str(data.get("mode") or "quiz").strip().lower()
|
| 165 |
+
if mode not in {"quiz", "exam", "flash"}:
|
| 166 |
+
return jsonify({"error": "mode must be quiz, exam, or flash."}), 400
|
| 167 |
+
|
| 168 |
+
try:
|
| 169 |
+
exclusions = _exclude_ids(data.get("exclude_ids"))
|
| 170 |
+
filters = SearchFilters.from_payload(data.get("filters"))
|
| 171 |
+
response = searcher.search(
|
| 172 |
+
query=query,
|
| 173 |
+
limit=limit,
|
| 174 |
+
exclude_ids=exclusions,
|
| 175 |
+
filters=filters,
|
| 176 |
+
)
|
| 177 |
+
except ValueError as error:
|
| 178 |
+
return jsonify({"error": str(error)}), 400
|
| 179 |
+
except RuntimeError as error:
|
| 180 |
+
logger.warning("[CUSTOM_QUIZ] Search unavailable: %s", error)
|
| 181 |
+
return jsonify({"error": "Quiz retrieval is temporarily unavailable."}), 503
|
| 182 |
+
except Exception:
|
| 183 |
+
logger.exception("[CUSTOM_QUIZ] Search failed.")
|
| 184 |
+
return jsonify({"error": "Quiz retrieval failed."}), 500
|
| 185 |
+
|
| 186 |
+
logger.info(
|
| 187 |
+
"[CUSTOM_QUIZ] request_id=%s mode=%s query_chars=%d requested=%d returned=%d excluded=%d candidates=%d exhausted=%s timings_ms=%s",
|
| 188 |
+
str(data.get("request_id") or "")[:80],
|
| 189 |
+
mode,
|
| 190 |
+
len(query),
|
| 191 |
+
response.requested,
|
| 192 |
+
response.returned,
|
| 193 |
+
response.excluded_count,
|
| 194 |
+
response.candidate_count,
|
| 195 |
+
response.exhausted,
|
| 196 |
+
response.timings_ms,
|
| 197 |
+
)
|
| 198 |
+
return jsonify(
|
| 199 |
+
{
|
| 200 |
+
"query": query,
|
| 201 |
+
"normalized_query": response.normalized_query,
|
| 202 |
+
"index_version": response.index_version,
|
| 203 |
+
"results": [asdict(item) for item in response.results],
|
| 204 |
+
"requested": response.requested,
|
| 205 |
+
"returned": response.returned,
|
| 206 |
+
"exhausted": response.exhausted,
|
| 207 |
+
}
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@app.get("/internal/index/status")
|
| 212 |
+
@_requires_basic_auth(config.admin_username, config.admin_password)
|
| 213 |
+
def index_status():
|
| 214 |
+
return jsonify(manager.status())
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@app.post("/internal/index/rebuild")
|
| 218 |
+
@_requires_basic_auth(config.admin_username, config.admin_password)
|
| 219 |
+
def index_rebuild():
|
| 220 |
+
data = request.get_json(silent=True) or {}
|
| 221 |
+
try:
|
| 222 |
+
result = manager.rebuild(force=bool(data.get("force")))
|
| 223 |
+
return jsonify(result), (409 if result.get("status") == "busy" else 200)
|
| 224 |
+
except Exception as error:
|
| 225 |
+
logger.exception("[CUSTOM_QUIZ] Manual rebuild failed.")
|
| 226 |
+
return jsonify({"error": str(error)}), 400
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@app.post("/internal/index/refresh-from-google")
|
| 230 |
+
@_requires_basic_auth(config.admin_username, config.admin_password)
|
| 231 |
+
def index_refresh():
|
| 232 |
+
data = request.get_json(silent=True) or {}
|
| 233 |
+
try:
|
| 234 |
+
result = manager.refresh_from_google(force=bool(data.get("force")))
|
| 235 |
+
return jsonify(result), (409 if result.get("status") == "busy" else 200)
|
| 236 |
+
except Exception as error:
|
| 237 |
+
logger.exception("[CUSTOM_QUIZ] Google refresh failed.")
|
| 238 |
+
return jsonify({"error": str(error)}), 400
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
port = int(os.getenv("PORT", "7861"))
|
| 243 |
+
app.run(host="0.0.0.0", port=port, threaded=True)
|
rag_components.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import csv
|
| 6 |
+
import threading
|
| 7 |
+
from typing import List, Dict, Optional, Any
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from sentence_transformers import CrossEncoder
|
| 11 |
+
|
| 12 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 13 |
+
from langchain_community.vectorstores import FAISS
|
| 14 |
+
|
| 15 |
+
from langchain_core.documents import Document
|
| 16 |
+
from langchain_core.embeddings import Embeddings
|
| 17 |
+
from langchain_core.retrievers import BaseRetriever
|
| 18 |
+
from langchain_core.callbacks import CallbackManagerForRetrieverRun
|
| 19 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 20 |
+
|
| 21 |
+
from config import (
|
| 22 |
+
RAG_RERANKER_MODEL_NAME, RAG_DETAILED_LOGGING,
|
| 23 |
+
RAG_CHUNK_SIZE, RAG_CHUNK_OVERLAP, RAG_CHUNKED_SOURCES_FILENAME,
|
| 24 |
+
RAG_FAISS_INDEX_SUBDIR_NAME, RAG_INITIAL_FETCH_K, RAG_RERANKER_K,
|
| 25 |
+
RAG_MAX_FILES_FOR_INCREMENTAL, RAG_CSV_ROWS_PER_CHUNK
|
| 26 |
+
)
|
| 27 |
+
from utils import FAISS_RAG_SUPPORTED_EXTENSIONS
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
_MODEL_CACHE_LOCK = threading.RLock()
|
| 32 |
+
_EMBEDDING_MODEL_CACHE = {}
|
| 33 |
+
_RERANKER_MODEL_CACHE = {}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ThreadSafeEmbeddings(Embeddings):
|
| 37 |
+
def __init__(self, model: HuggingFaceEmbeddings):
|
| 38 |
+
self._model = model
|
| 39 |
+
self._lock = threading.RLock()
|
| 40 |
+
|
| 41 |
+
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
| 42 |
+
with self._lock:
|
| 43 |
+
return self._model.embed_documents(texts)
|
| 44 |
+
|
| 45 |
+
def embed_query(self, text: str) -> List[float]:
|
| 46 |
+
with self._lock:
|
| 47 |
+
return self._model.embed_query(text)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _shared_embeddings(model_name: str, device: str):
|
| 51 |
+
key = (model_name, device)
|
| 52 |
+
with _MODEL_CACHE_LOCK:
|
| 53 |
+
model = _EMBEDDING_MODEL_CACHE.get(key)
|
| 54 |
+
if model is None:
|
| 55 |
+
model = ThreadSafeEmbeddings(
|
| 56 |
+
HuggingFaceEmbeddings(
|
| 57 |
+
model_name=model_name,
|
| 58 |
+
model_kwargs={"device": device},
|
| 59 |
+
encode_kwargs={"normalize_embeddings": True},
|
| 60 |
+
)
|
| 61 |
+
)
|
| 62 |
+
_EMBEDDING_MODEL_CACHE[key] = model
|
| 63 |
+
return model
|
| 64 |
+
|
| 65 |
+
def _shared_reranker(model_name: str):
|
| 66 |
+
with _MODEL_CACHE_LOCK:
|
| 67 |
+
model = _RERANKER_MODEL_CACHE.get(model_name)
|
| 68 |
+
if model is None:
|
| 69 |
+
model = DocumentReranker(model_name)
|
| 70 |
+
_RERANKER_MODEL_CACHE[model_name] = model
|
| 71 |
+
return model
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _row_to_text(row: Dict) -> str:
|
| 75 |
+
return "\n".join([
|
| 76 |
+
f"{k}: {v}"
|
| 77 |
+
for k, v in row.items()
|
| 78 |
+
if k and v and str(v).strip()
|
| 79 |
+
])
|
| 80 |
+
|
| 81 |
+
def _csv_rows_to_documents(file_path: str, filename: str, rows_per_chunk: int) -> List[Document]:
|
| 82 |
+
from utils import extract_csv_chunks
|
| 83 |
+
extracted_chunks = extract_csv_chunks(file_path, filename, rows_per_chunk)
|
| 84 |
+
docs = []
|
| 85 |
+
for content, meta in extracted_chunks:
|
| 86 |
+
docs.append(Document(page_content=content, metadata=meta))
|
| 87 |
+
return docs
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class DocumentReranker:
|
| 91 |
+
def __init__(self, model_name: str = RAG_RERANKER_MODEL_NAME):
|
| 92 |
+
self.logger = logging.getLogger(__name__ + ".DocumentReranker")
|
| 93 |
+
self.model_name = model_name
|
| 94 |
+
self.model = None
|
| 95 |
+
self._predict_lock = threading.RLock()
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
self.logger.info(f"[RERANKER_INIT] Loading reranker model: {self.model_name}")
|
| 99 |
+
start_time = time.time()
|
| 100 |
+
self.model = CrossEncoder(model_name, trust_remote_code=True)
|
| 101 |
+
load_time = time.time() - start_time
|
| 102 |
+
self.logger.info(f"[RERANKER_INIT] Reranker model '{self.model_name}' loaded successfully in {load_time:.2f}s")
|
| 103 |
+
except Exception as e:
|
| 104 |
+
self.logger.error(f"[RERANKER_INIT] Failed to load reranker model '{self.model_name}': {e}", exc_info=True)
|
| 105 |
+
raise RuntimeError(f"Could not initialize reranker model: {e}") from e
|
| 106 |
+
|
| 107 |
+
def rerank_documents(self, query: str, documents: List[Document], top_k: int) -> List[Document]:
|
| 108 |
+
if not documents or not self.model:
|
| 109 |
+
return documents[:top_k] if documents else []
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
start_time = time.time()
|
| 113 |
+
doc_pairs = [[query, doc.page_content] for doc in documents]
|
| 114 |
+
with self._predict_lock:
|
| 115 |
+
scores = self.model.predict(doc_pairs)
|
| 116 |
+
rerank_time = time.time() - start_time
|
| 117 |
+
self.logger.info(f"[RERANKER] Computed relevance scores in {rerank_time:.3f}s")
|
| 118 |
+
|
| 119 |
+
doc_score_pairs = list(zip(documents, scores))
|
| 120 |
+
doc_score_pairs.sort(key=lambda x: x[1], reverse=True)
|
| 121 |
+
|
| 122 |
+
reranked_docs = []
|
| 123 |
+
for doc, score in doc_score_pairs[:top_k]:
|
| 124 |
+
doc.metadata["reranker_score"] = float(score)
|
| 125 |
+
reranked_docs.append(doc)
|
| 126 |
+
|
| 127 |
+
return reranked_docs
|
| 128 |
+
except Exception as e:
|
| 129 |
+
self.logger.error(f"[RERANKER] Error during reranking: {e}", exc_info=True)
|
| 130 |
+
return documents[:top_k] if documents else []
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class FAISSRetrieverWithScore(BaseRetriever):
|
| 134 |
+
vectorstore: FAISS
|
| 135 |
+
reranker: Optional[DocumentReranker] = None
|
| 136 |
+
initial_fetch_k: int = RAG_INITIAL_FETCH_K
|
| 137 |
+
final_k: int = RAG_RERANKER_K
|
| 138 |
+
|
| 139 |
+
def _get_relevant_documents(
|
| 140 |
+
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
|
| 141 |
+
) -> List[Document]:
|
| 142 |
+
|
| 143 |
+
start_time = time.time()
|
| 144 |
+
num_to_fetch = self.initial_fetch_k if self.reranker else self.final_k
|
| 145 |
+
|
| 146 |
+
logger.info(f"[RETRIEVER] Fetching {num_to_fetch} docs (Rerank={self.reranker is not None})")
|
| 147 |
+
|
| 148 |
+
docs_and_scores = self.vectorstore.similarity_search_with_score(query, k=num_to_fetch)
|
| 149 |
+
|
| 150 |
+
relevant_docs = []
|
| 151 |
+
for doc, score in docs_and_scores:
|
| 152 |
+
doc.metadata["retrieval_score"] = float(score)
|
| 153 |
+
relevant_docs.append(doc)
|
| 154 |
+
|
| 155 |
+
if self.reranker and relevant_docs:
|
| 156 |
+
relevant_docs = self.reranker.rerank_documents(query, relevant_docs, top_k=self.final_k)
|
| 157 |
+
|
| 158 |
+
total_time = time.time() - start_time
|
| 159 |
+
logger.info(f"[RETRIEVER] Completed in {total_time:.3f}s. Returned {len(relevant_docs)} docs.")
|
| 160 |
+
return relevant_docs
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class KnowledgeRAG:
|
| 164 |
+
def __init__(
|
| 165 |
+
self,
|
| 166 |
+
index_storage_dir: str,
|
| 167 |
+
embedding_model_name: str,
|
| 168 |
+
use_gpu_for_embeddings: bool,
|
| 169 |
+
chunk_size: int = RAG_CHUNK_SIZE,
|
| 170 |
+
chunk_overlap: int = RAG_CHUNK_OVERLAP,
|
| 171 |
+
reranker_model_name: Optional[str] = None,
|
| 172 |
+
enable_reranker: bool = True,
|
| 173 |
+
):
|
| 174 |
+
self.logger = logging.getLogger(__name__ + ".KnowledgeRAG")
|
| 175 |
+
self.logger.info(f"[RAG_INIT] Initializing KnowledgeRAG system")
|
| 176 |
+
|
| 177 |
+
self.index_storage_dir = index_storage_dir
|
| 178 |
+
os.makedirs(self.index_storage_dir, exist_ok=True)
|
| 179 |
+
|
| 180 |
+
self.embedding_model_name = embedding_model_name
|
| 181 |
+
self.use_gpu_for_embeddings = use_gpu_for_embeddings
|
| 182 |
+
self.chunk_size = chunk_size
|
| 183 |
+
self.chunk_overlap = chunk_overlap
|
| 184 |
+
self.csv_rows_per_chunk = RAG_CSV_ROWS_PER_CHUNK
|
| 185 |
+
self.reranker_model_name = reranker_model_name or RAG_RERANKER_MODEL_NAME
|
| 186 |
+
self.enable_reranker = enable_reranker
|
| 187 |
+
self.reranker = None
|
| 188 |
+
|
| 189 |
+
device = "cpu"
|
| 190 |
+
if self.use_gpu_for_embeddings:
|
| 191 |
+
if torch.cuda.is_available():
|
| 192 |
+
self.logger.info(f"[RAG_INIT] CUDA available. Requesting GPU.")
|
| 193 |
+
device = "cuda"
|
| 194 |
+
else:
|
| 195 |
+
self.logger.warning("[RAG_INIT] CUDA not available. Fallback to CPU.")
|
| 196 |
+
|
| 197 |
+
self.embeddings = _shared_embeddings(self.embedding_model_name, device)
|
| 198 |
+
|
| 199 |
+
if self.enable_reranker:
|
| 200 |
+
try:
|
| 201 |
+
self.reranker = _shared_reranker(self.reranker_model_name)
|
| 202 |
+
except Exception as e:
|
| 203 |
+
self.logger.warning(f"[RAG_INIT] Reranker Init Failed: {e}")
|
| 204 |
+
self.reranker = None
|
| 205 |
+
|
| 206 |
+
self.vector_store: Optional[FAISS] = None
|
| 207 |
+
self.retriever: Optional[FAISSRetrieverWithScore] = None
|
| 208 |
+
self.processed_source_files: List[str] = []
|
| 209 |
+
|
| 210 |
+
def _save_chunk_config(self):
|
| 211 |
+
faiss_path = os.path.join(self.index_storage_dir, RAG_FAISS_INDEX_SUBDIR_NAME)
|
| 212 |
+
config_file = os.path.join(faiss_path, "chunk_config.json")
|
| 213 |
+
with open(config_file, 'w') as f:
|
| 214 |
+
json.dump({
|
| 215 |
+
"chunk_size": self.chunk_size,
|
| 216 |
+
"chunk_overlap": self.chunk_overlap,
|
| 217 |
+
"csv_rows_per_chunk": self.csv_rows_per_chunk
|
| 218 |
+
}, f)
|
| 219 |
+
|
| 220 |
+
def _load_chunk_config(self) -> Optional[dict]:
|
| 221 |
+
faiss_path = os.path.join(self.index_storage_dir, RAG_FAISS_INDEX_SUBDIR_NAME)
|
| 222 |
+
config_file = os.path.join(faiss_path, "chunk_config.json")
|
| 223 |
+
if os.path.exists(config_file):
|
| 224 |
+
with open(config_file, 'r') as f:
|
| 225 |
+
return json.load(f)
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
def chunk_config_has_changed(self) -> bool:
|
| 229 |
+
faiss_path = os.path.join(self.index_storage_dir, RAG_FAISS_INDEX_SUBDIR_NAME)
|
| 230 |
+
if not os.path.exists(faiss_path):
|
| 231 |
+
return False
|
| 232 |
+
|
| 233 |
+
saved = self._load_chunk_config()
|
| 234 |
+
if saved is None:
|
| 235 |
+
self.logger.warning("[CONFIG_CHANGE] No chunk config found. Forcing rebuild to ensure consistency.")
|
| 236 |
+
return True
|
| 237 |
+
|
| 238 |
+
saved_csv_rows_per_chunk = saved.get("csv_rows_per_chunk", 1)
|
| 239 |
+
changed = (
|
| 240 |
+
saved.get("chunk_size") != self.chunk_size
|
| 241 |
+
or saved.get("chunk_overlap") != self.chunk_overlap
|
| 242 |
+
or saved_csv_rows_per_chunk != self.csv_rows_per_chunk
|
| 243 |
+
)
|
| 244 |
+
if changed:
|
| 245 |
+
self.logger.warning(
|
| 246 |
+
f"[CONFIG_CHANGE] Chunk config mismatch! "
|
| 247 |
+
f"Saved=(size={saved.get('chunk_size')}, overlap={saved.get('chunk_overlap')}, "
|
| 248 |
+
f"csv_rows_per_chunk={saved_csv_rows_per_chunk}) "
|
| 249 |
+
f"Current=(size={self.chunk_size}, overlap={self.chunk_overlap}, "
|
| 250 |
+
f"csv_rows_per_chunk={self.csv_rows_per_chunk}). "
|
| 251 |
+
f"Index will be rebuilt."
|
| 252 |
+
)
|
| 253 |
+
return changed
|
| 254 |
+
|
| 255 |
+
def build_index_from_source_files(self, source_folder_path: str):
|
| 256 |
+
self.logger.info(f"[INDEX_BUILD] Building from: {source_folder_path}")
|
| 257 |
+
if not os.path.isdir(source_folder_path):
|
| 258 |
+
raise FileNotFoundError(f"Source folder not found: '{source_folder_path}'.")
|
| 259 |
+
|
| 260 |
+
all_docs = []
|
| 261 |
+
processed_files = []
|
| 262 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=self.chunk_size, chunk_overlap=self.chunk_overlap)
|
| 263 |
+
|
| 264 |
+
pre_chunked_path = os.path.join(self.index_storage_dir, RAG_CHUNKED_SOURCES_FILENAME)
|
| 265 |
+
if os.path.exists(pre_chunked_path):
|
| 266 |
+
try:
|
| 267 |
+
self.logger.info(f"[INDEX_BUILD] Loading pre-chunked documents from {pre_chunked_path}")
|
| 268 |
+
with open(pre_chunked_path, 'r', encoding='utf-8') as f:
|
| 269 |
+
chunk_data_list = json.load(f)
|
| 270 |
+
for chunk in chunk_data_list:
|
| 271 |
+
doc = Document(page_content=chunk.get("page_content", ""), metadata=chunk.get("metadata", {}))
|
| 272 |
+
all_docs.append(doc)
|
| 273 |
+
if 'source_document_name' in doc.metadata:
|
| 274 |
+
processed_files.append(doc.metadata['source_document_name'])
|
| 275 |
+
processed_files = sorted(list(set(processed_files)))
|
| 276 |
+
except Exception as e:
|
| 277 |
+
self.logger.error(f"[INDEX_BUILD] JSON load failed: {e}")
|
| 278 |
+
|
| 279 |
+
processed_set = set(processed_files)
|
| 280 |
+
|
| 281 |
+
for filename in os.listdir(source_folder_path):
|
| 282 |
+
if filename in processed_set:
|
| 283 |
+
continue
|
| 284 |
+
|
| 285 |
+
file_path = os.path.join(source_folder_path, filename)
|
| 286 |
+
if not os.path.isfile(file_path): continue
|
| 287 |
+
file_ext = filename.split('.')[-1].lower()
|
| 288 |
+
|
| 289 |
+
if file_ext in FAISS_RAG_SUPPORTED_EXTENSIONS:
|
| 290 |
+
if file_ext == 'csv':
|
| 291 |
+
try:
|
| 292 |
+
docs = _csv_rows_to_documents(file_path, filename, self.csv_rows_per_chunk)
|
| 293 |
+
all_docs.extend(docs)
|
| 294 |
+
processed_files.append(filename)
|
| 295 |
+
self.logger.info(f"[INDEX_BUILD] Processed CSV {filename} into {len(docs)} chunks.")
|
| 296 |
+
except Exception as e:
|
| 297 |
+
self.logger.error(f"[INDEX_BUILD] Error processing CSV {filename}: {e}")
|
| 298 |
+
else:
|
| 299 |
+
text_content = FAISS_RAG_SUPPORTED_EXTENSIONS[file_ext](file_path)
|
| 300 |
+
if text_content and text_content != "CSV_HANDLED_NATIVELY":
|
| 301 |
+
chunks = text_splitter.split_text(text_content)
|
| 302 |
+
for i, chunk_text in enumerate(chunks):
|
| 303 |
+
meta = {"source_document_name": filename, "chunk_index": i}
|
| 304 |
+
all_docs.append(Document(page_content=chunk_text, metadata=meta))
|
| 305 |
+
processed_files.append(filename)
|
| 306 |
+
|
| 307 |
+
if not all_docs:
|
| 308 |
+
raise ValueError("No documents to index.")
|
| 309 |
+
|
| 310 |
+
self.processed_source_files = processed_files
|
| 311 |
+
self.logger.info(f"[INDEX_BUILD] Creating FAISS index with {len(all_docs)} chunks.")
|
| 312 |
+
|
| 313 |
+
self.vector_store = FAISS.from_documents(all_docs, self.embeddings)
|
| 314 |
+
faiss_path = os.path.join(self.index_storage_dir, RAG_FAISS_INDEX_SUBDIR_NAME)
|
| 315 |
+
self.vector_store.save_local(faiss_path)
|
| 316 |
+
with open(os.path.join(faiss_path, "trusted_index.json"), "w", encoding="utf-8") as marker_file:
|
| 317 |
+
json.dump({"created_by": "sealednectar-rag-build-pipeline"}, marker_file)
|
| 318 |
+
self._save_chunk_config()
|
| 319 |
+
|
| 320 |
+
self.retriever = FAISSRetrieverWithScore(
|
| 321 |
+
vectorstore=self.vector_store,
|
| 322 |
+
reranker=self.reranker,
|
| 323 |
+
initial_fetch_k=RAG_INITIAL_FETCH_K,
|
| 324 |
+
final_k=RAG_RERANKER_K
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
def load_index_from_disk(self):
|
| 328 |
+
faiss_path = os.path.join(self.index_storage_dir, RAG_FAISS_INDEX_SUBDIR_NAME)
|
| 329 |
+
if not os.path.exists(faiss_path):
|
| 330 |
+
raise FileNotFoundError("Index not found.")
|
| 331 |
+
|
| 332 |
+
trusted_marker = os.path.join(faiss_path, "trusted_index.json")
|
| 333 |
+
if not os.path.isfile(trusted_marker):
|
| 334 |
+
raise RuntimeError("Refusing to deserialize an index without the trusted build marker.")
|
| 335 |
+
with open(trusted_marker, "r", encoding="utf-8") as marker_file:
|
| 336 |
+
marker = json.load(marker_file)
|
| 337 |
+
if marker.get("created_by") != "sealednectar-rag-build-pipeline":
|
| 338 |
+
raise RuntimeError("Refusing to deserialize an untrusted index marker.")
|
| 339 |
+
self.vector_store = FAISS.load_local(
|
| 340 |
+
folder_path=faiss_path,
|
| 341 |
+
embeddings=self.embeddings,
|
| 342 |
+
allow_dangerous_deserialization=True
|
| 343 |
+
)
|
| 344 |
+
self.retriever = FAISSRetrieverWithScore(
|
| 345 |
+
vectorstore=self.vector_store,
|
| 346 |
+
reranker=self.reranker,
|
| 347 |
+
initial_fetch_k=RAG_INITIAL_FETCH_K,
|
| 348 |
+
final_k=RAG_RERANKER_K
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
meta_file = os.path.join(faiss_path, "processed_files.json")
|
| 352 |
+
if os.path.exists(meta_file):
|
| 353 |
+
with open(meta_file, 'r') as f:
|
| 354 |
+
self.processed_source_files = json.load(f)
|
| 355 |
+
else:
|
| 356 |
+
self.processed_source_files = ["Loaded from disk (unknown sources)"]
|
| 357 |
+
|
| 358 |
+
self.logger.info("[INDEX_LOAD] Success.")
|
| 359 |
+
|
| 360 |
+
def update_index_with_new_files(self, source_folder_path: str, max_files_to_process: Optional[int] = None) -> Dict[str, Any]:
|
| 361 |
+
self.logger.info(f"[INDEX_UPDATE] Checking for new files in: {source_folder_path}")
|
| 362 |
+
|
| 363 |
+
if not self.vector_store:
|
| 364 |
+
raise RuntimeError("Cannot update: no index loaded.")
|
| 365 |
+
|
| 366 |
+
processed_set = set(self.processed_source_files)
|
| 367 |
+
all_new_files = []
|
| 368 |
+
for filename in sorted(os.listdir(source_folder_path)):
|
| 369 |
+
if filename not in processed_set:
|
| 370 |
+
file_ext = filename.split('.')[-1].lower()
|
| 371 |
+
if file_ext in FAISS_RAG_SUPPORTED_EXTENSIONS:
|
| 372 |
+
all_new_files.append(filename)
|
| 373 |
+
|
| 374 |
+
if not all_new_files:
|
| 375 |
+
return {"status": "success", "message": "No new files found.", "files_added": []}
|
| 376 |
+
|
| 377 |
+
limit = max_files_to_process if max_files_to_process is not None else RAG_MAX_FILES_FOR_INCREMENTAL
|
| 378 |
+
files_to_process = all_new_files[:limit]
|
| 379 |
+
|
| 380 |
+
new_docs = []
|
| 381 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=self.chunk_size, chunk_overlap=self.chunk_overlap)
|
| 382 |
+
|
| 383 |
+
for filename in files_to_process:
|
| 384 |
+
file_path = os.path.join(source_folder_path, filename)
|
| 385 |
+
file_ext = filename.split('.')[-1].lower()
|
| 386 |
+
|
| 387 |
+
if file_ext == 'csv':
|
| 388 |
+
try:
|
| 389 |
+
new_docs.extend(_csv_rows_to_documents(file_path, filename, self.csv_rows_per_chunk))
|
| 390 |
+
except Exception as e:
|
| 391 |
+
self.logger.error(f"[INDEX_UPDATE] Error processing CSV {filename}: {e}")
|
| 392 |
+
else:
|
| 393 |
+
text_content = FAISS_RAG_SUPPORTED_EXTENSIONS[file_ext](file_path)
|
| 394 |
+
if text_content and text_content != "CSV_HANDLED_NATIVELY":
|
| 395 |
+
chunks = text_splitter.split_text(text_content)
|
| 396 |
+
for i, chunk_text in enumerate(chunks):
|
| 397 |
+
meta = {"source_document_name": filename, "chunk_index": i}
|
| 398 |
+
new_docs.append(Document(page_content=chunk_text, metadata=meta))
|
| 399 |
+
|
| 400 |
+
if not new_docs:
|
| 401 |
+
return {"status": "warning", "message": "New files found but no text extracted.", "files_added": []}
|
| 402 |
+
|
| 403 |
+
self.vector_store.add_documents(new_docs)
|
| 404 |
+
|
| 405 |
+
faiss_path = os.path.join(self.index_storage_dir, RAG_FAISS_INDEX_SUBDIR_NAME)
|
| 406 |
+
self.vector_store.save_local(faiss_path)
|
| 407 |
+
|
| 408 |
+
self.processed_source_files.extend(files_to_process)
|
| 409 |
+
with open(os.path.join(faiss_path, "processed_files.json"), 'w') as f:
|
| 410 |
+
json.dump(sorted(self.processed_source_files), f)
|
| 411 |
+
|
| 412 |
+
return {
|
| 413 |
+
"status": "success",
|
| 414 |
+
"message": f"Added {len(files_to_process)} files.",
|
| 415 |
+
"files_added": files_to_process,
|
| 416 |
+
"remaining": len(all_new_files) - len(files_to_process)
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
def search_knowledge_base(
|
| 420 |
+
self,
|
| 421 |
+
query: str,
|
| 422 |
+
top_k: Optional[int] = None,
|
| 423 |
+
*,
|
| 424 |
+
initial_fetch_k: Optional[int] = None,
|
| 425 |
+
use_reranker: bool = True,
|
| 426 |
+
) -> List[Dict[str, Any]]:
|
| 427 |
+
if not self.vector_store:
|
| 428 |
+
raise RuntimeError("Vector store not initialized.")
|
| 429 |
+
|
| 430 |
+
final_k = max(1, int(top_k or RAG_RERANKER_K))
|
| 431 |
+
reranker = self.reranker if use_reranker else None
|
| 432 |
+
fetch_k = max(final_k, int(initial_fetch_k or RAG_INITIAL_FETCH_K)) if reranker else final_k
|
| 433 |
+
docs_and_scores = self.vector_store.similarity_search_with_score(query, k=fetch_k)
|
| 434 |
+
documents = []
|
| 435 |
+
for doc, score in docs_and_scores:
|
| 436 |
+
metadata = dict(doc.metadata)
|
| 437 |
+
metadata["retrieval_score"] = float(score)
|
| 438 |
+
documents.append(Document(page_content=doc.page_content, metadata=metadata))
|
| 439 |
+
|
| 440 |
+
if reranker and documents:
|
| 441 |
+
documents = reranker.rerank_documents(query, documents, top_k=final_k)
|
| 442 |
+
else:
|
| 443 |
+
documents = documents[:final_k]
|
| 444 |
+
|
| 445 |
+
return [
|
| 446 |
+
{
|
| 447 |
+
"content": doc.page_content,
|
| 448 |
+
"metadata": dict(doc.metadata),
|
| 449 |
+
"score": doc.metadata.get("reranker_score")
|
| 450 |
+
if doc.metadata.get("reranker_score") is not None
|
| 451 |
+
else doc.metadata.get("retrieval_score"),
|
| 452 |
+
}
|
| 453 |
+
for doc in documents
|
| 454 |
+
]
|
requirements.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
flask-cors
|
| 3 |
+
pandas
|
| 4 |
+
python-dotenv
|
| 5 |
+
requests
|
| 6 |
+
beautifulsoup4
|
| 7 |
+
gdown
|
| 8 |
+
pypdf
|
| 9 |
+
python-docx
|
| 10 |
+
torch
|
| 11 |
+
sentence-transformers
|
| 12 |
+
langchain
|
| 13 |
+
langchain-community
|
| 14 |
+
langchain-core
|
| 15 |
+
langchain-huggingface
|
| 16 |
+
langchain-text-splitters
|
| 17 |
+
faiss-cpu
|
| 18 |
+
|
| 19 |
+
gunicorn
|
| 20 |
+
numpy
|
scripts/export_quiz_questions.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Export the two-column custom-quiz retrieval CSV from Supabase.
|
| 3 |
+
|
| 4 |
+
The retrieval index receives only the authoritative question ID and exact
|
| 5 |
+
question text. The Supabase Edge Function hydrates and validates every returned
|
| 6 |
+
ID against the live quiz_questions row.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import csv
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Dict, Iterable, List
|
| 17 |
+
|
| 18 |
+
import requests
|
| 19 |
+
|
| 20 |
+
FIELDS = ("id", "question")
|
| 21 |
+
PAGE_SIZE = 1000
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def require_env(name: str) -> str:
|
| 25 |
+
value = os.getenv(name, "").strip()
|
| 26 |
+
if not value:
|
| 27 |
+
raise RuntimeError(f"Missing required environment variable: {name}")
|
| 28 |
+
return value
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def fetch_rows(base_url: str, service_key: str) -> Iterable[Dict[str, object]]:
|
| 32 |
+
endpoint = f"{base_url.rstrip('/')}/rest/v1/quiz_questions"
|
| 33 |
+
offset = 0
|
| 34 |
+
headers = {
|
| 35 |
+
"apikey": service_key,
|
| 36 |
+
"Authorization": f"Bearer {service_key}",
|
| 37 |
+
"Accept": "application/json",
|
| 38 |
+
"Range-Unit": "items",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
while True:
|
| 42 |
+
response = requests.get(
|
| 43 |
+
endpoint,
|
| 44 |
+
headers={**headers, "Range": f"{offset}-{offset + PAGE_SIZE - 1}"},
|
| 45 |
+
params={
|
| 46 |
+
"select": ",".join(FIELDS),
|
| 47 |
+
"is_deleted": "eq.false",
|
| 48 |
+
"order": "id.asc",
|
| 49 |
+
},
|
| 50 |
+
timeout=60,
|
| 51 |
+
)
|
| 52 |
+
response.raise_for_status()
|
| 53 |
+
rows = response.json()
|
| 54 |
+
if not isinstance(rows, list):
|
| 55 |
+
raise RuntimeError("Supabase returned a non-list response.")
|
| 56 |
+
for row in rows:
|
| 57 |
+
if isinstance(row, dict):
|
| 58 |
+
yield row
|
| 59 |
+
if len(rows) < PAGE_SIZE:
|
| 60 |
+
break
|
| 61 |
+
offset += PAGE_SIZE
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def validate_rows(rows: List[Dict[str, object]]) -> None:
|
| 65 |
+
if not rows:
|
| 66 |
+
raise RuntimeError("The export contains no active quiz questions.")
|
| 67 |
+
seen = set()
|
| 68 |
+
for index, row in enumerate(rows, start=2):
|
| 69 |
+
question_id = row.get("id")
|
| 70 |
+
question = str(row.get("question") or "").strip()
|
| 71 |
+
if not isinstance(question_id, int) or question_id <= 0:
|
| 72 |
+
raise RuntimeError(f"Row {index}: invalid id {question_id!r}.")
|
| 73 |
+
if question_id in seen:
|
| 74 |
+
raise RuntimeError(f"Row {index}: duplicate id {question_id}.")
|
| 75 |
+
if not question:
|
| 76 |
+
raise RuntimeError(f"Row {index}: blank question.")
|
| 77 |
+
seen.add(question_id)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def write_atomic(rows: List[Dict[str, object]], output: Path) -> None:
|
| 81 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
with tempfile.NamedTemporaryFile(
|
| 83 |
+
"w",
|
| 84 |
+
encoding="utf-8-sig",
|
| 85 |
+
newline="",
|
| 86 |
+
dir=output.parent,
|
| 87 |
+
prefix=f".{output.name}.",
|
| 88 |
+
suffix=".tmp",
|
| 89 |
+
delete=False,
|
| 90 |
+
) as handle:
|
| 91 |
+
temp_path = Path(handle.name)
|
| 92 |
+
writer = csv.DictWriter(handle, fieldnames=FIELDS, extrasaction="ignore")
|
| 93 |
+
writer.writeheader()
|
| 94 |
+
writer.writerows(rows)
|
| 95 |
+
os.replace(temp_path, output)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main() -> int:
|
| 99 |
+
try:
|
| 100 |
+
base_url = require_env("QUIZ_EXPORT_SUPABASE_URL")
|
| 101 |
+
service_key = require_env("QUIZ_EXPORT_SERVICE_ROLE_KEY")
|
| 102 |
+
output = Path(
|
| 103 |
+
os.getenv(
|
| 104 |
+
"QUIZ_EXPORT_OUTPUT",
|
| 105 |
+
"sources/custom_quiz/quiz_questions.csv",
|
| 106 |
+
)
|
| 107 |
+
).resolve()
|
| 108 |
+
rows = list(fetch_rows(base_url, service_key))
|
| 109 |
+
validate_rows(rows)
|
| 110 |
+
write_atomic(rows, output)
|
| 111 |
+
print(f"Exported {len(rows)} active questions to {output}")
|
| 112 |
+
return 0
|
| 113 |
+
except Exception as error:
|
| 114 |
+
print(f"Export failed: {error}", file=sys.stderr)
|
| 115 |
+
return 1
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
raise SystemExit(main())
|
shared_models.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import threading
|
| 3 |
+
import time
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import List, Optional, Sequence, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 9 |
+
from sentence_transformers import CrossEncoder
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class SharedReranker:
|
| 15 |
+
"""Thread-safe cross-encoder wrapper shared by all indexes in one process."""
|
| 16 |
+
|
| 17 |
+
def __init__(self, model_name: str):
|
| 18 |
+
self.model_name = model_name
|
| 19 |
+
started = time.time()
|
| 20 |
+
logger.info("[MODEL_BUNDLE] Loading reranker model: %s", model_name)
|
| 21 |
+
self._model = CrossEncoder(model_name, trust_remote_code=True)
|
| 22 |
+
self._lock = threading.RLock()
|
| 23 |
+
logger.info(
|
| 24 |
+
"[MODEL_BUNDLE] Reranker loaded in %.2fs",
|
| 25 |
+
time.time() - started,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
def predict(self, query: str, texts: Sequence[str]) -> List[float]:
|
| 29 |
+
if not texts:
|
| 30 |
+
return []
|
| 31 |
+
pairs = [[query, text] for text in texts]
|
| 32 |
+
with self._lock:
|
| 33 |
+
scores = self._model.predict(pairs)
|
| 34 |
+
return [float(score) for score in scores]
|
| 35 |
+
|
| 36 |
+
def rank(
|
| 37 |
+
self,
|
| 38 |
+
query: str,
|
| 39 |
+
items: Sequence[Tuple[object, str]],
|
| 40 |
+
top_k: int,
|
| 41 |
+
) -> List[Tuple[object, float]]:
|
| 42 |
+
if not items or top_k <= 0:
|
| 43 |
+
return []
|
| 44 |
+
scores = self.predict(query, [text for _, text in items])
|
| 45 |
+
ranked = list(zip((item for item, _ in items), scores))
|
| 46 |
+
ranked.sort(key=lambda pair: pair[1], reverse=True)
|
| 47 |
+
return ranked[:top_k]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ThreadSafeEmbeddings:
|
| 51 |
+
"""Serialize model encoding while allowing concurrent FAISS/BM25 reads."""
|
| 52 |
+
|
| 53 |
+
def __init__(self, model: HuggingFaceEmbeddings):
|
| 54 |
+
self._model = model
|
| 55 |
+
self._lock = threading.RLock()
|
| 56 |
+
|
| 57 |
+
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
| 58 |
+
with self._lock:
|
| 59 |
+
return self._model.embed_documents(texts)
|
| 60 |
+
|
| 61 |
+
def embed_query(self, text: str) -> List[float]:
|
| 62 |
+
with self._lock:
|
| 63 |
+
return self._model.embed_query(text)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass(frozen=True)
|
| 67 |
+
class ModelBundle:
|
| 68 |
+
embeddings: ThreadSafeEmbeddings
|
| 69 |
+
reranker: Optional[SharedReranker]
|
| 70 |
+
embedding_model_name: str
|
| 71 |
+
reranker_model_name: str
|
| 72 |
+
embedding_device: str
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def load(
|
| 76 |
+
cls,
|
| 77 |
+
*,
|
| 78 |
+
embedding_model_name: str,
|
| 79 |
+
reranker_model_name: str,
|
| 80 |
+
use_gpu_for_embeddings: bool,
|
| 81 |
+
enable_reranker: bool,
|
| 82 |
+
) -> "ModelBundle":
|
| 83 |
+
device = "cpu"
|
| 84 |
+
if use_gpu_for_embeddings and torch.cuda.is_available():
|
| 85 |
+
device = "cuda"
|
| 86 |
+
elif use_gpu_for_embeddings:
|
| 87 |
+
logger.warning(
|
| 88 |
+
"[MODEL_BUNDLE] CUDA requested but unavailable; using CPU."
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
logger.info(
|
| 92 |
+
"[MODEL_BUNDLE] Loading embedding model %s on %s",
|
| 93 |
+
embedding_model_name,
|
| 94 |
+
device,
|
| 95 |
+
)
|
| 96 |
+
embeddings = ThreadSafeEmbeddings(
|
| 97 |
+
HuggingFaceEmbeddings(
|
| 98 |
+
model_name=embedding_model_name,
|
| 99 |
+
model_kwargs={"device": device},
|
| 100 |
+
encode_kwargs={"normalize_embeddings": True},
|
| 101 |
+
)
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
reranker: Optional[SharedReranker] = None
|
| 105 |
+
if enable_reranker:
|
| 106 |
+
try:
|
| 107 |
+
reranker = SharedReranker(reranker_model_name)
|
| 108 |
+
except Exception:
|
| 109 |
+
logger.exception(
|
| 110 |
+
"[MODEL_BUNDLE] Reranker failed to load; dense/lexical retrieval remains available."
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
return cls(
|
| 114 |
+
embeddings=embeddings,
|
| 115 |
+
reranker=reranker,
|
| 116 |
+
embedding_model_name=embedding_model_name,
|
| 117 |
+
reranker_model_name=reranker_model_name,
|
| 118 |
+
embedding_device=device,
|
| 119 |
+
)
|
sources/custom_quiz/aliases.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"badr": ["battle of badr", "ghazwah badr", "ghazwat badr", "بدر"]
|
| 3 |
+
}
|