Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -40,8 +40,6 @@ try:
|
|
| 40 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, TextIteratorStreamer
|
| 41 |
|
| 42 |
# 🔥 STRICT NO-TRAINING LOCK 🔥
|
| 43 |
-
# Yeh ensure karta hai ki PyTorch gradients calculate na kare.
|
| 44 |
-
# AI 100% pre-trained inference mode me chalega. Cost aur RAM dono bachenge.
|
| 45 |
torch.set_num_threads(1)
|
| 46 |
torch.set_grad_enabled(False)
|
| 47 |
|
|
@@ -140,6 +138,17 @@ def cosine_similarity(vec_a, mat_b):
|
|
| 140 |
def detect_language(text):
|
| 141 |
return "English"
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
def build_searchable_text(doc):
|
| 144 |
parts = [doc.get("title", ""), doc.get("description", ""), doc.get("tag", "")]
|
| 145 |
for k, v in doc.get("meta_tags", {}).items():
|
|
@@ -150,13 +159,16 @@ def build_searchable_text(doc):
|
|
| 150 |
|
| 151 |
def build_runtime_record(doc):
|
| 152 |
r = doc.copy()
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
r["
|
| 156 |
-
r["
|
| 157 |
-
r["
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
r["tag"] = doc.get("tag", "general")
|
| 159 |
-
r["specific_data"] = doc.get("specific_data", {})
|
| 160 |
r["searchable_text"] = build_searchable_text(r)
|
| 161 |
|
| 162 |
r["human_opens"] = r.get("human_opens", 0)
|
|
@@ -185,11 +197,24 @@ def init_system():
|
|
| 185 |
|
| 186 |
if not os.path.exists(CACHE_FILE):
|
| 187 |
hf_token = os.getenv("HF_TOKEN")
|
| 188 |
-
if not hf_token:
|
| 189 |
-
print("⚠️ HF_TOKEN environment variable is missing. Required if dataset is private.")
|
| 190 |
print("☁️ Downloading dataset from Hugging Face...")
|
| 191 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
print("✅ Dataset successfully cached locally.")
|
| 194 |
|
| 195 |
if os.path.exists(CACHE_FILE):
|
|
@@ -198,14 +223,18 @@ def init_system():
|
|
| 198 |
with open(CACHE_FILE, "r", encoding="utf-8") as f:
|
| 199 |
for line in f:
|
| 200 |
if line.strip():
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
bm25_index = BM25Okapi(corpus_tokens)
|
| 211 |
|
|
@@ -217,20 +246,19 @@ def init_system():
|
|
| 217 |
print("💾 [3/4] Loading Precomputed Embeddings...")
|
| 218 |
with open("embeddings.bin", "rb") as fb: doc_embeddings = pickle.load(fb)
|
| 219 |
else:
|
| 220 |
-
# Yeh sirf text ko numbers me convert kar raha hai search ke liye (Training nahi hai)
|
| 221 |
print("���️ [3/4] Converting Text to Vector Embeddings (One-Time Inference)...")
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
|
|
|
| 225 |
|
| 226 |
# =============== PRE-TRAINED TRANSFORMERS BASED SMOLLM2 ===============
|
| 227 |
print("🔥 [4/4] Loading Pre-trained SmolLM2 (360M Params)...")
|
| 228 |
try:
|
| 229 |
model_id = "HuggingFaceTB/SmolLM2-360M-Instruct"
|
| 230 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 231 |
-
# Model is loaded strictly for inference
|
| 232 |
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32)
|
| 233 |
-
model.eval() # Puts the model in
|
| 234 |
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=-1)
|
| 235 |
print("✅ Model successfully loaded in INFERENCE mode.")
|
| 236 |
except Exception as e:
|
|
@@ -247,7 +275,7 @@ def get_ranked_results(query: str):
|
|
| 247 |
bm25_scores = bm25_index.get_scores(q_tokens) if bm25_index else np.zeros(len(raw_data))
|
| 248 |
semantic_scores = np.zeros(len(raw_data))
|
| 249 |
|
| 250 |
-
if text_embedder and doc_embeddings is not None:
|
| 251 |
q_vec = text_embedder.encode([query])[0]
|
| 252 |
semantic_scores = cosine_similarity(q_vec, doc_embeddings)
|
| 253 |
|
|
|
|
| 40 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, TextIteratorStreamer
|
| 41 |
|
| 42 |
# 🔥 STRICT NO-TRAINING LOCK 🔥
|
|
|
|
|
|
|
| 43 |
torch.set_num_threads(1)
|
| 44 |
torch.set_grad_enabled(False)
|
| 45 |
|
|
|
|
| 138 |
def detect_language(text):
|
| 139 |
return "English"
|
| 140 |
|
| 141 |
+
def parse_json_field(val):
|
| 142 |
+
"""Safely converts stringified JSONs to dicts if dataset schema changed."""
|
| 143 |
+
if isinstance(val, dict):
|
| 144 |
+
return val
|
| 145 |
+
if isinstance(val, str):
|
| 146 |
+
try:
|
| 147 |
+
return json.loads(val)
|
| 148 |
+
except:
|
| 149 |
+
return {}
|
| 150 |
+
return {}
|
| 151 |
+
|
| 152 |
def build_searchable_text(doc):
|
| 153 |
parts = [doc.get("title", ""), doc.get("description", ""), doc.get("tag", "")]
|
| 154 |
for k, v in doc.get("meta_tags", {}).items():
|
|
|
|
| 159 |
|
| 160 |
def build_runtime_record(doc):
|
| 161 |
r = doc.copy()
|
| 162 |
+
|
| 163 |
+
# Safe JSON parsing to prevent crashes from schema changes
|
| 164 |
+
r["meta_tags"] = parse_json_field(doc.get("meta_tags"))
|
| 165 |
+
r["og_tags"] = parse_json_field(doc.get("og_tags"))
|
| 166 |
+
r["specific_data"] = parse_json_field(doc.get("specific_data"))
|
| 167 |
+
|
| 168 |
+
r["images"] = doc.get("images") or []
|
| 169 |
+
r["videos"] = doc.get("videos") or []
|
| 170 |
+
r["documents"] = doc.get("documents") or []
|
| 171 |
r["tag"] = doc.get("tag", "general")
|
|
|
|
| 172 |
r["searchable_text"] = build_searchable_text(r)
|
| 173 |
|
| 174 |
r["human_opens"] = r.get("human_opens", 0)
|
|
|
|
| 197 |
|
| 198 |
if not os.path.exists(CACHE_FILE):
|
| 199 |
hf_token = os.getenv("HF_TOKEN")
|
|
|
|
|
|
|
| 200 |
print("☁️ Downloading dataset from Hugging Face...")
|
| 201 |
+
|
| 202 |
+
try:
|
| 203 |
+
# Attempt 1: Standard load
|
| 204 |
+
dataset = load_dataset("Nebulixlabs/Ultimate-Search-Engine-Dataset", split="train", token=hf_token)
|
| 205 |
+
dataset.to_json(CACHE_FILE)
|
| 206 |
+
except Exception as e:
|
| 207 |
+
print(f"⚠️ Standard load failed due to schema mismatch ({e}). Trying fallback raw JSON loader...")
|
| 208 |
+
try:
|
| 209 |
+
# Attempt 2: Force raw JSON inference (bypasses broken schemas)
|
| 210 |
+
dataset = load_dataset("json", data_files="hf://datasets/Nebulixlabs/Ultimate-Search-Engine-Dataset/**/*.json*", split="train", token=hf_token)
|
| 211 |
+
dataset.to_json(CACHE_FILE)
|
| 212 |
+
except Exception as e2:
|
| 213 |
+
print(f"⚠️ Raw JSON load failed. Trying Parquet loader... ({e2})")
|
| 214 |
+
# Attempt 3: Parquet fallback
|
| 215 |
+
dataset = load_dataset("parquet", data_files="hf://datasets/Nebulixlabs/Ultimate-Search-Engine-Dataset/**/*.parquet", split="train", token=hf_token)
|
| 216 |
+
dataset.to_json(CACHE_FILE)
|
| 217 |
+
|
| 218 |
print("✅ Dataset successfully cached locally.")
|
| 219 |
|
| 220 |
if os.path.exists(CACHE_FILE):
|
|
|
|
| 223 |
with open(CACHE_FILE, "r", encoding="utf-8") as f:
|
| 224 |
for line in f:
|
| 225 |
if line.strip():
|
| 226 |
+
try:
|
| 227 |
+
doc = build_runtime_record(json.loads(line))
|
| 228 |
+
raw_data.append(doc)
|
| 229 |
+
url_to_data[doc["url"]] = doc
|
| 230 |
+
|
| 231 |
+
tokens = tokenize(doc["searchable_text"])
|
| 232 |
+
corpus_tokens.append(tokens)
|
| 233 |
+
texts_to_embed.append(doc["searchable_text"])
|
| 234 |
+
for t in tokens: add_to_trie(t)
|
| 235 |
+
except Exception as parse_e:
|
| 236 |
+
# Ignore highly corrupted single lines
|
| 237 |
+
pass
|
| 238 |
|
| 239 |
bm25_index = BM25Okapi(corpus_tokens)
|
| 240 |
|
|
|
|
| 246 |
print("💾 [3/4] Loading Precomputed Embeddings...")
|
| 247 |
with open("embeddings.bin", "rb") as fb: doc_embeddings = pickle.load(fb)
|
| 248 |
else:
|
|
|
|
| 249 |
print("���️ [3/4] Converting Text to Vector Embeddings (One-Time Inference)...")
|
| 250 |
+
if texts_to_embed:
|
| 251 |
+
doc_embeddings = text_embedder.encode(texts_to_embed, convert_to_numpy=True)
|
| 252 |
+
with open("embeddings.bin", "wb") as fb: pickle.dump(doc_embeddings, fb)
|
| 253 |
+
with open("metadata.json", "w") as fm: json.dump({"count": len(doc_embeddings)}, fm)
|
| 254 |
|
| 255 |
# =============== PRE-TRAINED TRANSFORMERS BASED SMOLLM2 ===============
|
| 256 |
print("🔥 [4/4] Loading Pre-trained SmolLM2 (360M Params)...")
|
| 257 |
try:
|
| 258 |
model_id = "HuggingFaceTB/SmolLM2-360M-Instruct"
|
| 259 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
|
|
|
| 260 |
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32)
|
| 261 |
+
model.eval() # Puts the model in strict inference mode
|
| 262 |
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=-1)
|
| 263 |
print("✅ Model successfully loaded in INFERENCE mode.")
|
| 264 |
except Exception as e:
|
|
|
|
| 275 |
bm25_scores = bm25_index.get_scores(q_tokens) if bm25_index else np.zeros(len(raw_data))
|
| 276 |
semantic_scores = np.zeros(len(raw_data))
|
| 277 |
|
| 278 |
+
if text_embedder and doc_embeddings is not None and len(doc_embeddings) > 0:
|
| 279 |
q_vec = text_embedder.encode([query])[0]
|
| 280 |
semantic_scores = cosine_similarity(q_vec, doc_embeddings)
|
| 281 |
|