Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- README.md +13 -0
- app.py +464 -0
- requirements.txt +7 -0
README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: MarisTest
|
| 3 |
+
emoji: 🏢
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: gray
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.44.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import pathlib
|
| 5 |
+
import shutil
|
| 6 |
+
from typing import List, Tuple, Dict
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import numpy as np
|
| 10 |
+
import faiss
|
| 11 |
+
from sentence_transformers import SentenceTransformer
|
| 12 |
+
from pypdf import PdfReader
|
| 13 |
+
import fitz # PyMuPDF
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
from openai import OpenAI
|
| 16 |
+
|
| 17 |
+
# =========================
|
| 18 |
+
# LLM Endpoint (NVIDIA Integrate via OpenAI SDK; non-streaming)
|
| 19 |
+
# =========================
|
| 20 |
+
|
| 21 |
+
API_KEY = os.environ.get("NVAPI_KEY")
|
| 22 |
+
|
| 23 |
+
if not API_KEY:
|
| 24 |
+
raise RuntimeError("Missing NVAPI_KEY (set it in Hugging Face: Settings → Variables and secrets).")
|
| 25 |
+
|
| 26 |
+
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=API_KEY)
|
| 27 |
+
|
| 28 |
+
MODEL_NAME = "openai/gpt-oss-120b:free"
|
| 29 |
+
GEN_TEMPERATURE = 0.2
|
| 30 |
+
GEN_TOP_P = 0.95
|
| 31 |
+
GEN_MAX_TOKENS = 1024
|
| 32 |
+
|
| 33 |
+
# =========================
|
| 34 |
+
# Vector Retrieval/Persistence (prefer /data; otherwise ./store)
|
| 35 |
+
# =========================
|
| 36 |
+
|
| 37 |
+
EMB_MODEL_NAME = "intfloat/multilingual-e5-base" # Supports both Chinese and English
|
| 38 |
+
|
| 39 |
+
def choose_store_dir() -> Tuple[str, bool]:
|
| 40 |
+
"""Return (store_dir, is_persistent). Prefer /data/rag_store if writable."""
|
| 41 |
+
data_root = "/data"
|
| 42 |
+
if os.path.isdir(data_root) and os.access(data_root, os.W_OK):
|
| 43 |
+
d = os.path.join(data_root, "rag_store")
|
| 44 |
+
try:
|
| 45 |
+
os.makedirs(d, exist_ok=True)
|
| 46 |
+
testf = os.path.join(d, ".write_test")
|
| 47 |
+
with open(testf, "w", encoding="utf-8") as f:
|
| 48 |
+
f.write("ok")
|
| 49 |
+
os.remove(testf)
|
| 50 |
+
return d, True
|
| 51 |
+
except Exception:
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
d = os.path.join(os.getcwd(), "store")
|
| 55 |
+
os.makedirs(d, exist_ok=True)
|
| 56 |
+
return d, False
|
| 57 |
+
|
| 58 |
+
STORE_DIR, IS_PERSISTENT = choose_store_dir()
|
| 59 |
+
META_PATH = os.path.join(STORE_DIR, "meta.json")
|
| 60 |
+
INDEX_PATH = os.path.join(STORE_DIR, "faiss.index")
|
| 61 |
+
|
| 62 |
+
# One-time migration from old ./store to /data/rag_store (if not yet exists)
|
| 63 |
+
LEGACY_STORE_DIR = os.path.join(os.getcwd(), "store")
|
| 64 |
+
|
| 65 |
+
def migrate_legacy_if_any():
|
| 66 |
+
try:
|
| 67 |
+
if IS_PERSISTENT:
|
| 68 |
+
legacy_meta = os.path.join(LEGACY_STORE_DIR, "meta.json")
|
| 69 |
+
legacy_index = os.path.join(LEGACY_STORE_DIR, "faiss.index")
|
| 70 |
+
|
| 71 |
+
if (not os.path.exists(META_PATH) or not os.path.exists(INDEX_PATH)) \
|
| 72 |
+
and os.path.isdir(LEGACY_STORE_DIR) \
|
| 73 |
+
and os.path.exists(legacy_meta) and os.path.exists(legacy_index):
|
| 74 |
+
shutil.copyfile(legacy_meta, META_PATH)
|
| 75 |
+
shutil.copyfile(legacy_index, INDEX_PATH)
|
| 76 |
+
except Exception:
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
migrate_legacy_if_any()
|
| 80 |
+
|
| 81 |
+
_emb_model = None
|
| 82 |
+
_index: faiss.Index = None
|
| 83 |
+
_meta: Dict[str, Dict] = {}
|
| 84 |
+
|
| 85 |
+
# ========== Adjustable Parameter Defaults ==========
|
| 86 |
+
DEFAULT_TOP_K = 6
|
| 87 |
+
DEFAULT_POOL_K = 40
|
| 88 |
+
DEFAULT_PER_SOURCE_CAP = 2
|
| 89 |
+
DEFAULT_STRATEGY = "mmr" # "mmr" or "round_robin"
|
| 90 |
+
DEFAULT_MMR_LAMBDA = 0.5
|
| 91 |
+
|
| 92 |
+
# ---------- Basic Tools ----------
|
| 93 |
+
|
| 94 |
+
def get_emb_model():
|
| 95 |
+
global _emb_model
|
| 96 |
+
if _emb_model is None:
|
| 97 |
+
_emb_model = SentenceTransformer(EMB_MODEL_NAME)
|
| 98 |
+
return _emb_model
|
| 99 |
+
|
| 100 |
+
def _ensure_index(dim: int):
|
| 101 |
+
global _index
|
| 102 |
+
if _index is None:
|
| 103 |
+
_index = faiss.IndexFlatIP(dim) # Normalize vectors first → inner product = cosine
|
| 104 |
+
|
| 105 |
+
def _persist():
|
| 106 |
+
faiss.write_index(_index, INDEX_PATH)
|
| 107 |
+
with open(META_PATH, "w", encoding="utf-8") as f:
|
| 108 |
+
json.dump(_meta, f, ensure_ascii=False)
|
| 109 |
+
|
| 110 |
+
def _load_if_any():
|
| 111 |
+
global _index, _meta
|
| 112 |
+
if os.path.exists(INDEX_PATH) and os.path.exists(META_PATH):
|
| 113 |
+
_index = faiss.read_index(INDEX_PATH)
|
| 114 |
+
with open(META_PATH, "r", encoding="utf-8") as f:
|
| 115 |
+
_meta = json.load(f)
|
| 116 |
+
|
| 117 |
+
def _chunk_text(text: str, chunk_size: int = 800, overlap: int = 120) -> List[str]:
|
| 118 |
+
text = text.replace("\u0000", "")
|
| 119 |
+
res, i, n = [], 0, len(text)
|
| 120 |
+
while i < n:
|
| 121 |
+
j = min(i + chunk_size, n)
|
| 122 |
+
seg = text[i:j].strip()
|
| 123 |
+
if seg:
|
| 124 |
+
res.append(seg)
|
| 125 |
+
i = max(0, j - overlap)
|
| 126 |
+
if j >= n:
|
| 127 |
+
break
|
| 128 |
+
return res
|
| 129 |
+
|
| 130 |
+
# ---------- Robust File Reading ----------
|
| 131 |
+
|
| 132 |
+
def _read_bytes(file) -> bytes:
|
| 133 |
+
if isinstance(file, dict):
|
| 134 |
+
p = file.get("path") or file.get("name")
|
| 135 |
+
if p and os.path.exists(p):
|
| 136 |
+
with open(p, "rb") as f:
|
| 137 |
+
return f.read()
|
| 138 |
+
if "data" in file and isinstance(file["data"], (bytes, bytearray)):
|
| 139 |
+
return bytes(file["data"])
|
| 140 |
+
|
| 141 |
+
if isinstance(file, (str, pathlib.Path)):
|
| 142 |
+
with open(file, "rb") as f:
|
| 143 |
+
return f.read()
|
| 144 |
+
|
| 145 |
+
if hasattr(file, "read"):
|
| 146 |
+
try:
|
| 147 |
+
if hasattr(file, "seek"):
|
| 148 |
+
try:
|
| 149 |
+
file.seek(0)
|
| 150 |
+
except Exception:
|
| 151 |
+
pass
|
| 152 |
+
return file.read()
|
| 153 |
+
finally:
|
| 154 |
+
try:
|
| 155 |
+
file.close()
|
| 156 |
+
except Exception:
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
raise ValueError("Unsupported file type from gr.File")
|
| 160 |
+
|
| 161 |
+
def _decode_best_effort(raw: bytes) -> str:
|
| 162 |
+
for enc in ["utf-8", "cp932", "shift_jis", "cp950", "big5", "gb18030", "latin-1"]:
|
| 163 |
+
try:
|
| 164 |
+
return raw.decode(enc)
|
| 165 |
+
except Exception:
|
| 166 |
+
continue
|
| 167 |
+
return raw.decode("utf-8", errors="ignore")
|
| 168 |
+
|
| 169 |
+
def _read_pdf(file_bytes: bytes) -> str:
|
| 170 |
+
# 1) PyMuPDF
|
| 171 |
+
try:
|
| 172 |
+
with fitz.open(stream=file_bytes, filetype="pdf") as doc:
|
| 173 |
+
if doc.is_encrypted:
|
| 174 |
+
try:
|
| 175 |
+
doc.authenticate("") # Try empty password
|
| 176 |
+
except Exception:
|
| 177 |
+
pass
|
| 178 |
+
texts = [(page.get_text("text") or "") for page in doc]
|
| 179 |
+
txt = "\n".join(texts)
|
| 180 |
+
if txt.strip():
|
| 181 |
+
return txt
|
| 182 |
+
except Exception:
|
| 183 |
+
pass
|
| 184 |
+
|
| 185 |
+
# 2) fallback: pypdf
|
| 186 |
+
try:
|
| 187 |
+
reader = PdfReader(io.BytesIO(file_bytes))
|
| 188 |
+
pages = []
|
| 189 |
+
for p in reader.pages:
|
| 190 |
+
try:
|
| 191 |
+
pages.append(p.extract_text() or "")
|
| 192 |
+
except Exception:
|
| 193 |
+
pages.append("")
|
| 194 |
+
return "\n".join(pages)
|
| 195 |
+
except Exception:
|
| 196 |
+
return ""
|
| 197 |
+
|
| 198 |
+
def _read_any(file) -> str:
|
| 199 |
+
if isinstance(file, dict):
|
| 200 |
+
name = (file.get("orig_name") or file.get("name") or file.get("path") or "upload").lower()
|
| 201 |
+
else:
|
| 202 |
+
name = getattr(file, "name", None) or (str(file) if isinstance(file, (str, pathlib.Path)) else "upload")
|
| 203 |
+
name = name.lower()
|
| 204 |
+
|
| 205 |
+
raw = _read_bytes(file)
|
| 206 |
+
if name.endswith(".pdf"):
|
| 207 |
+
return _read_pdf(raw).replace("\u0000", "")
|
| 208 |
+
return _decode_best_effort(raw).replace("\u0000", "")
|
| 209 |
+
|
| 210 |
+
# ---------- Build Corpus ----------
|
| 211 |
+
|
| 212 |
+
def build_corpus(files) -> str:
|
| 213 |
+
if not files:
|
| 214 |
+
return "No files selected."
|
| 215 |
+
|
| 216 |
+
emb_model = get_emb_model()
|
| 217 |
+
chunks, sources, failed = [], [], []
|
| 218 |
+
total_chars = 0
|
| 219 |
+
|
| 220 |
+
for f in files:
|
| 221 |
+
if isinstance(f, dict):
|
| 222 |
+
fname = f.get("orig_name") or f.get("name") or f.get("path") or "uploaded"
|
| 223 |
+
else:
|
| 224 |
+
fname = getattr(f, "name", None) or (os.path.basename(f) if isinstance(f, (str, pathlib.Path)) else "uploaded")
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
text = _read_any(f) or ""
|
| 228 |
+
total_chars += len(text)
|
| 229 |
+
parts = _chunk_text(text)
|
| 230 |
+
if not parts:
|
| 231 |
+
failed.append(fname)
|
| 232 |
+
continue
|
| 233 |
+
chunks.extend(parts)
|
| 234 |
+
sources.extend([fname] * len(parts))
|
| 235 |
+
except Exception as e:
|
| 236 |
+
failed.append(f"{fname} (err: {e})")
|
| 237 |
+
|
| 238 |
+
if not chunks:
|
| 239 |
+
tier = "Persistent (/data)" if IS_PERSISTENT else "Ephemeral (./store)"
|
| 240 |
+
return f"No text extracted (please check file type/encoding; read {total_chars} characters this time).\nCurrent storage path: {STORE_DIR} [{tier}]"
|
| 241 |
+
|
| 242 |
+
passages = [f"passage: {c}" for c in chunks] # e5 prefix
|
| 243 |
+
vec = emb_model.encode(passages, batch_size=64, convert_to_numpy=True, normalize_embeddings=True)
|
| 244 |
+
|
| 245 |
+
_ensure_index(vec.shape[1])
|
| 246 |
+
_index.add(vec)
|
| 247 |
+
|
| 248 |
+
base = len(_meta)
|
| 249 |
+
for i, (src, c) in enumerate(zip(sources, chunks)):
|
| 250 |
+
_meta[str(base + i)] = {"source": src, "text": c}
|
| 251 |
+
|
| 252 |
+
_persist()
|
| 253 |
+
|
| 254 |
+
msg = f"Indexing complete: added {len(chunks)} chunks; current total chunks in corpus ≈ {_index.ntotal}."
|
| 255 |
+
if failed:
|
| 256 |
+
preview = ", ".join(failed[:5])
|
| 257 |
+
more = "" if len(failed) <= 5 else f" (and {len(failed)-5} more not shown)"
|
| 258 |
+
msg += f"\nNote: {len(failed)} files failed to extract text or were empty: {preview}{more}"
|
| 259 |
+
|
| 260 |
+
tier = "Persistent (/data)" if IS_PERSISTENT else "Ephemeral (./store)"
|
| 261 |
+
msg += f"\nCurrent storage path: {STORE_DIR} [{tier}]"
|
| 262 |
+
|
| 263 |
+
return msg
|
| 264 |
+
|
| 265 |
+
# ---------- Retrieval (Candidate Pool) ----------
|
| 266 |
+
|
| 267 |
+
def _encode_query_vec(query: str) -> np.ndarray:
|
| 268 |
+
return get_emb_model().encode([f"query: {query}"], convert_to_numpy=True, normalize_embeddings=True)
|
| 269 |
+
|
| 270 |
+
def retrieve_candidates(qvec: np.ndarray, pool_k: int = DEFAULT_POOL_K) -> List[Tuple[str, float]]:
|
| 271 |
+
if _index is None or _index.ntotal == 0:
|
| 272 |
+
return []
|
| 273 |
+
|
| 274 |
+
pool_k = min(pool_k, _index.ntotal)
|
| 275 |
+
D, I = _index.search(qvec, pool_k)
|
| 276 |
+
return [(str(idx), float(score)) for idx, score in zip(I[0], D[0]) if idx != -1]
|
| 277 |
+
|
| 278 |
+
# ---------- Diversification Strategies ----------
|
| 279 |
+
|
| 280 |
+
def select_diverse_by_source(cands: List[Tuple[str, float]], top_k: int = DEFAULT_TOP_K, per_source_cap: int = DEFAULT_PER_SOURCE_CAP) -> List[Tuple[str, float]]:
|
| 281 |
+
if not cands:
|
| 282 |
+
return []
|
| 283 |
+
|
| 284 |
+
by_src: Dict[str, List[Tuple[str, float]]] = defaultdict(list)
|
| 285 |
+
for cid, s in cands:
|
| 286 |
+
m = _meta.get(cid)
|
| 287 |
+
if not m:
|
| 288 |
+
continue
|
| 289 |
+
by_src[m["source"]].append((cid, s))
|
| 290 |
+
|
| 291 |
+
for src in by_src:
|
| 292 |
+
by_src[src] = by_src[src][:per_source_cap]
|
| 293 |
+
|
| 294 |
+
picked, src_items, ptrs = [], [(s, it) for s, it in by_src.items()], {s: 0 for s in by_src}
|
| 295 |
+
while len(picked) < top_k:
|
| 296 |
+
advanced = False
|
| 297 |
+
for src, items in src_items:
|
| 298 |
+
i = ptrs[src]
|
| 299 |
+
if i < len(items):
|
| 300 |
+
picked.append(items[i])
|
| 301 |
+
ptrs[src] = i + 1
|
| 302 |
+
advanced = True
|
| 303 |
+
if len(picked) >= top_k:
|
| 304 |
+
break
|
| 305 |
+
if not advanced:
|
| 306 |
+
break
|
| 307 |
+
|
| 308 |
+
if len(picked) < top_k:
|
| 309 |
+
seen = {cid for cid, _ in picked}
|
| 310 |
+
for cid, s in cands:
|
| 311 |
+
if cid not in seen:
|
| 312 |
+
picked.append((cid, s))
|
| 313 |
+
seen.add(cid)
|
| 314 |
+
if len(picked) >= top_k:
|
| 315 |
+
break
|
| 316 |
+
|
| 317 |
+
return picked[:top_k]
|
| 318 |
+
|
| 319 |
+
def _encode_chunks_text(cids: List[str]) -> np.ndarray:
|
| 320 |
+
texts = [f"passage: {(_meta.get(cid) or {}).get('text','')}" for cid in cids]
|
| 321 |
+
return get_emb_model().encode(texts, convert_to_numpy=True, normalize_embeddings=True)
|
| 322 |
+
|
| 323 |
+
def select_diverse_mmr(cands: List[Tuple[str, float]], qvec: np.ndarray, top_k: int = DEFAULT_TOP_K, mmr_lambda: float = DEFAULT_MMR_LAMBDA) -> List[Tuple[str, float]]:
|
| 324 |
+
if not cands:
|
| 325 |
+
return []
|
| 326 |
+
|
| 327 |
+
cids = [cid for cid, _ in cands]
|
| 328 |
+
cvecs = _encode_chunks_text(cids)
|
| 329 |
+
sim_to_q = (cvecs @ qvec.T).reshape(-1)
|
| 330 |
+
|
| 331 |
+
selected, remaining = [], set(range(len(cids)))
|
| 332 |
+
while len(selected) < min(top_k, len(cids)):
|
| 333 |
+
if not selected:
|
| 334 |
+
i = int(np.argmax(sim_to_q))
|
| 335 |
+
selected.append(i)
|
| 336 |
+
remaining.remove(i)
|
| 337 |
+
continue
|
| 338 |
+
|
| 339 |
+
S = cvecs[selected]
|
| 340 |
+
sim_to_S = (cvecs[list(remaining)] @ S.T)
|
| 341 |
+
max_sim_to_S = sim_to_S.max(axis=1) if sim_to_S.size > 0 else np.zeros((len(remaining),), dtype=np.float32)
|
| 342 |
+
|
| 343 |
+
sim_q_rem = sim_to_q[list(remaining)]
|
| 344 |
+
mmr_scores = mmr_lambda * sim_q_rem - (1.0 - mmr_lambda) * max_sim_to_S
|
| 345 |
+
|
| 346 |
+
j_rel = int(np.argmax(mmr_scores))
|
| 347 |
+
j = list(remaining)[j_rel]
|
| 348 |
+
selected.append(j)
|
| 349 |
+
remaining.remove(j)
|
| 350 |
+
|
| 351 |
+
return [(cids[i], float(sim_to_q[i])) for i in selected][:top_k]
|
| 352 |
+
|
| 353 |
+
def retrieve_diverse(query: str,
|
| 354 |
+
top_k: int = DEFAULT_TOP_K,
|
| 355 |
+
pool_k: int = DEFAULT_POOL_K,
|
| 356 |
+
per_source_cap: int = DEFAULT_PER_SOURCE_CAP,
|
| 357 |
+
strategy: str = DEFAULT_STRATEGY,
|
| 358 |
+
mmr_lambda: float = DEFAULT_MMR_LAMBDA) -> List[Tuple[str, float]]:
|
| 359 |
+
qvec = _encode_query_vec(query)
|
| 360 |
+
cands = retrieve_candidates(qvec, pool_k=pool_k)
|
| 361 |
+
|
| 362 |
+
if strategy == "mmr":
|
| 363 |
+
return select_diverse_mmr(cands, qvec, top_k=top_k, mmr_lambda=mmr_lambda)
|
| 364 |
+
return select_diverse_by_source(cands, top_k=top_k, per_source_cap=per_source_cap)
|
| 365 |
+
|
| 366 |
+
# ---------- Format Chunks ----------
|
| 367 |
+
|
| 368 |
+
def _format_ctx(hits: List[Tuple[str, float]]) -> str:
|
| 369 |
+
if not hits:
|
| 370 |
+
return ""
|
| 371 |
+
|
| 372 |
+
lines = []
|
| 373 |
+
for cid, _ in hits:
|
| 374 |
+
m = _meta.get(cid)
|
| 375 |
+
if not m:
|
| 376 |
+
continue
|
| 377 |
+
source_clean = m.get("source", "")
|
| 378 |
+
text_clean = (m.get("text", "") or "").replace("\n", " ")
|
| 379 |
+
lines.append(f"[{cid}] ({source_clean}) " + text_clean)
|
| 380 |
+
|
| 381 |
+
return "\n".join(lines[:10])
|
| 382 |
+
|
| 383 |
+
# =========================
|
| 384 |
+
# LLM Conversation (non-streaming → avoid StopAsyncIteration)
|
| 385 |
+
# =========================
|
| 386 |
+
|
| 387 |
+
def chat_fn(message, history, strategy, top_k, pool_k, per_source_cap, mmr_lambda):
|
| 388 |
+
hits = retrieve_diverse(
|
| 389 |
+
message,
|
| 390 |
+
top_k=int(top_k),
|
| 391 |
+
pool_k=int(pool_k),
|
| 392 |
+
per_source_cap=int(per_source_cap),
|
| 393 |
+
strategy=str(strategy),
|
| 394 |
+
mmr_lambda=float(mmr_lambda),
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
ctx = _format_ctx(hits) if hits else "(Current index is empty or no matching chunks found)"
|
| 398 |
+
|
| 399 |
+
sys_blocks = [
|
| 400 |
+
"You are a rigorous real estate market research assistant. Your answers must be based on retrieved content with evidence and source numbers cited. If retrieval is insufficient, please clearly explain the shortcomings.",
|
| 401 |
+
f"Below are the available reference chunks (with numbers and sources). When answering, please cite the numbers, e.g., [3].\n\n{ctx}",
|
| 402 |
+
]
|
| 403 |
+
|
| 404 |
+
messages = [{"role": "system", "content": "\n\n".join(sys_blocks)}]
|
| 405 |
+
for u, a in history:
|
| 406 |
+
messages.append({"role": "user", "content": u})
|
| 407 |
+
messages.append({"role": "assistant", "content": a})
|
| 408 |
+
messages.append({"role": "user", "content": message})
|
| 409 |
+
|
| 410 |
+
try:
|
| 411 |
+
resp = client.chat.completions.create(
|
| 412 |
+
model=MODEL_NAME,
|
| 413 |
+
messages=messages,
|
| 414 |
+
temperature=GEN_TEMPERATURE,
|
| 415 |
+
top_p=GEN_TOP_P,
|
| 416 |
+
max_tokens=GEN_MAX_TOKENS,
|
| 417 |
+
stream=False, # Non-streaming, most stable
|
| 418 |
+
)
|
| 419 |
+
return resp.choices[0].message.content
|
| 420 |
+
except Exception as e:
|
| 421 |
+
return f"[Exception] {repr(e)}"
|
| 422 |
+
|
| 423 |
+
# =========================
|
| 424 |
+
# Gradio Interface (Slider/Dropdown takes effect immediately)
|
| 425 |
+
# =========================
|
| 426 |
+
|
| 427 |
+
with gr.Blocks(title="RAG (Candidate Pool + Diversification) | NVIDIA Integrate (Non-streaming)") as demo:
|
| 428 |
+
tier = "Persistent `/data`" if IS_PERSISTENT else "Ephemeral `./store` (may be lost on restart)"
|
| 429 |
+
gr.Markdown(
|
| 430 |
+
f"### RAG (Plain text, no OCR)\n"
|
| 431 |
+
f"- Current storage path: `{STORE_DIR}` [{tier}]\n"
|
| 432 |
+
"- Full corpus retrieval + MMR / Round-Robin diversification; chunks are labeled with source filename and chunk id.\n"
|
| 433 |
+
f"- LLM: `{MODEL_NAME}` (non-streaming, avoids StopAsyncIteration)."
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
with gr.Row():
|
| 437 |
+
with gr.Column(scale=1):
|
| 438 |
+
files = gr.File(file_count="multiple", file_types=[".pdf", ".txt"], label="Upload Corpus (multiple files allowed)")
|
| 439 |
+
out = gr.Textbox(label="Index Status", interactive=False)
|
| 440 |
+
gr.Button("Build/Update Index", variant="primary").click(build_corpus, inputs=files, outputs=out)
|
| 441 |
+
|
| 442 |
+
gr.Markdown("#### Retrieval Parameters (adjustable based on data volume)")
|
| 443 |
+
strategy = gr.Dropdown(choices=["mmr", "round_robin"], value=DEFAULT_STRATEGY, label="Diversification Strategy")
|
| 444 |
+
top_k = gr.Slider(1, 12, value=DEFAULT_TOP_K, step=1, label="Number of chunks for model (top_k)")
|
| 445 |
+
pool_k = gr.Slider(10, 200, value=DEFAULT_POOL_K, step=5, label="Candidate pool size (pool_k)")
|
| 446 |
+
per_source_cap = gr.Slider(1, 5, value=DEFAULT_PER_SOURCE_CAP, step=1, label="Per-source limit (for round_robin)")
|
| 447 |
+
mmr_lambda = gr.Slider(0.0, 1.0, value=DEFAULT_MMR_LAMBDA, step=0.05, label="MMR λ (higher = closer to query)")
|
| 448 |
+
|
| 449 |
+
with gr.Column(scale=2):
|
| 450 |
+
gr.ChatInterface(
|
| 451 |
+
fn=chat_fn, # Non-streaming function
|
| 452 |
+
additional_inputs=[strategy, top_k, pool_k, per_source_cap, mmr_lambda],
|
| 453 |
+
title="Chat (RAG)",
|
| 454 |
+
description=f"First retrieve from full corpus → diversify chunk selection → generate answer with {MODEL_NAME}.",
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
# Cold start: load existing index
|
| 458 |
+
try:
|
| 459 |
+
_load_if_any()
|
| 460 |
+
except Exception:
|
| 461 |
+
pass
|
| 462 |
+
|
| 463 |
+
if __name__ == "__main__":
|
| 464 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
openai>=1.40.0
|
| 3 |
+
faiss-cpu>=1.7.4
|
| 4 |
+
sentence-transformers>=2.7.0
|
| 5 |
+
pypdf>=4.2.0
|
| 6 |
+
pymupdf>=1.24.9
|
| 7 |
+
numpy>=1.26.0
|