Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,143 +1,93 @@
|
|
| 1 |
-
# import faiss
|
| 2 |
-
# import json
|
| 3 |
-
# import gradio as gr
|
| 4 |
-
# from sentence_transformers import SentenceTransformer
|
| 5 |
-
|
| 6 |
-
# # ----------------------------------------------------
|
| 7 |
-
# # 1. Load FAISS Index (Prebuilt)
|
| 8 |
-
# # ----------------------------------------------------
|
| 9 |
-
# # This index already contains all document embeddings.
|
| 10 |
-
# INDEX_PATH = "assets/faiss_ip_768.index"
|
| 11 |
-
# index = faiss.read_index(INDEX_PATH)
|
| 12 |
-
|
| 13 |
-
# # ----------------------------------------------------
|
| 14 |
-
# # 2. Load Text Corpus (ID → Content Mapping)
|
| 15 |
-
# # ----------------------------------------------------
|
| 16 |
-
# # corpus.json should be a list where each position aligns
|
| 17 |
-
# # with the embedding index used in FAISS.
|
| 18 |
-
# # Example: ["Text 1", "Text 2", "Text 3", ...]
|
| 19 |
-
# CORPUS_PATH = "assets/corpus.json"
|
| 20 |
-
# with open(CORPUS_PATH, "r", encoding="utf-8") as f:
|
| 21 |
-
# CORPUS = json.load(f)
|
| 22 |
-
|
| 23 |
-
# # ----------------------------------------------------
|
| 24 |
-
# # 3. Load Sentence Transformer Model for Query Encoding
|
| 25 |
-
# # ----------------------------------------------------
|
| 26 |
-
# # ⚠️ IMPORTANT: Must be the SAME model that was used
|
| 27 |
-
# HF_TOKEN = os.getenv("HF_TOKEN")
|
| 28 |
-
# EMBEDDING_MODEL_NAME = "google/embeddinggemma-300m" # ← Change if you used another model
|
| 29 |
-
# model = SentenceTransformer(EMBEDDING_MODEL_NAME, HF_TOKEN)
|
| 30 |
-
|
| 31 |
-
# # ----------------------------------------------------
|
| 32 |
-
# # 4. Search Function: Query → Top K Results
|
| 33 |
-
# # ----------------------------------------------------
|
| 34 |
-
# def search_faiss(query, top_k=5):
|
| 35 |
-
# """
|
| 36 |
-
# Takes a text query, embeds it, searches FAISS index,
|
| 37 |
-
# and returns top-k most similar corpus entries.
|
| 38 |
-
# """
|
| 39 |
-
# # Encode query text into a vector
|
| 40 |
-
# query_embedding = model.encode([query], convert_to_numpy=True)
|
| 41 |
-
|
| 42 |
-
# # Perform similarity search (returns distances and indices)
|
| 43 |
-
# distances, indices = index.search(query_embedding, top_k)
|
| 44 |
-
|
| 45 |
-
# # Collect matching corpus entries
|
| 46 |
-
# results = []
|
| 47 |
-
# for rank, idx in enumerate(indices[0]):
|
| 48 |
-
# results.append(
|
| 49 |
-
# f"#{rank+1} | Score: {distances[0][rank]:.4f}\n{CORPUS[idx]}"
|
| 50 |
-
# )
|
| 51 |
-
|
| 52 |
-
# return "\n\n".join(results)
|
| 53 |
-
|
| 54 |
-
# # ----------------------------------------------------
|
| 55 |
-
# # 5. Build Gradio Interface
|
| 56 |
-
# # ----------------------------------------------------
|
| 57 |
-
# def gradio_search(query, top_k):
|
| 58 |
-
# if not query.strip():
|
| 59 |
-
# return "Please enter a search query."
|
| 60 |
-
# return search_faiss(query, top_k)
|
| 61 |
-
|
| 62 |
-
# demo = gr.Interface(
|
| 63 |
-
# fn=gradio_search,
|
| 64 |
-
# inputs=[
|
| 65 |
-
# gr.Textbox(label="Enter your search query"),
|
| 66 |
-
# gr.Slider(1, 20, value=5, step=1, label="Number of results"),
|
| 67 |
-
# ],
|
| 68 |
-
# outputs=gr.Textbox(label="Search Results"),
|
| 69 |
-
# title="FAISS Semantic Search",
|
| 70 |
-
# description="A simple search engine powered by FAISS + Sentence Transformers."
|
| 71 |
-
# )
|
| 72 |
-
|
| 73 |
-
# # ----------------------------------------------------
|
| 74 |
-
# # 6. Run App (for local testing or Spaces deployment)
|
| 75 |
-
# # ----------------------------------------------------
|
| 76 |
-
# if __name__ == "__main__":
|
| 77 |
-
# demo.launch()
|
| 78 |
-
|
| 79 |
-
|
| 80 |
import os
|
|
|
|
|
|
|
| 81 |
import gradio as gr
|
| 82 |
from transformers import AutoTokenizer, AutoModel
|
| 83 |
import torch
|
| 84 |
import numpy as np
|
| 85 |
|
| 86 |
# ----------------------------------------------------
|
| 87 |
-
# 1. HF_TOKEN (
|
| 88 |
# ----------------------------------------------------
|
| 89 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 90 |
|
| 91 |
# ----------------------------------------------------
|
| 92 |
-
# 2. Load EmbeddingGemma-300M
|
| 93 |
# ----------------------------------------------------
|
| 94 |
MODEL_NAME = "google/embeddinggemma-300m"
|
| 95 |
|
| 96 |
-
# Load tokenizer and model
|
| 97 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_auth_token=HF_TOKEN)
|
| 98 |
model = AutoModel.from_pretrained(MODEL_NAME, use_auth_token=HF_TOKEN)
|
| 99 |
|
| 100 |
-
# Function to encode
|
| 101 |
def encode(texts):
|
| 102 |
"""
|
| 103 |
Encode a list of texts into vector embeddings using EmbeddingGemma-300M.
|
| 104 |
-
Mean pooling over token embeddings is
|
| 105 |
"""
|
| 106 |
inputs = tokenizer(
|
| 107 |
-
texts,
|
| 108 |
)
|
| 109 |
with torch.no_grad():
|
| 110 |
outputs = model(**inputs)
|
| 111 |
-
# Mean pooling
|
| 112 |
embeddings = outputs.last_hidden_state.mean(dim=1)
|
| 113 |
-
# Convert to numpy float32
|
| 114 |
return embeddings.cpu().numpy().astype(np.float32)
|
| 115 |
|
| 116 |
# ----------------------------------------------------
|
| 117 |
-
# 3.
|
| 118 |
# ----------------------------------------------------
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
"""
|
| 121 |
-
|
| 122 |
-
Returns the shape of the resulting embedding vector.
|
| 123 |
"""
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
# ----------------------------------------------------
|
| 128 |
-
#
|
| 129 |
# ----------------------------------------------------
|
| 130 |
demo = gr.Interface(
|
| 131 |
-
fn=
|
| 132 |
-
inputs=
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
| 136 |
)
|
| 137 |
|
| 138 |
# ----------------------------------------------------
|
| 139 |
-
#
|
| 140 |
# ----------------------------------------------------
|
| 141 |
if __name__ == "__main__":
|
| 142 |
demo.launch()
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import faiss
|
| 3 |
+
import json
|
| 4 |
import gradio as gr
|
| 5 |
from transformers import AutoTokenizer, AutoModel
|
| 6 |
import torch
|
| 7 |
import numpy as np
|
| 8 |
|
| 9 |
# ----------------------------------------------------
|
| 10 |
+
# 1. HF_TOKEN (for private models, optional)
|
| 11 |
# ----------------------------------------------------
|
| 12 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
|
| 14 |
# ----------------------------------------------------
|
| 15 |
+
# 2. Load EmbeddingGemma-300M
|
| 16 |
# ----------------------------------------------------
|
| 17 |
MODEL_NAME = "google/embeddinggemma-300m"
|
| 18 |
|
| 19 |
+
# Load tokenizer and model from Hugging Face
|
| 20 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_auth_token=HF_TOKEN)
|
| 21 |
model = AutoModel.from_pretrained(MODEL_NAME, use_auth_token=HF_TOKEN)
|
| 22 |
|
| 23 |
+
# Function to encode a list of texts
|
| 24 |
def encode(texts):
|
| 25 |
"""
|
| 26 |
Encode a list of texts into vector embeddings using EmbeddingGemma-300M.
|
| 27 |
+
Mean pooling over token embeddings is applied.
|
| 28 |
"""
|
| 29 |
inputs = tokenizer(
|
| 30 |
+
texts, padding=True, truncation=True, return_tensors="pt"
|
| 31 |
)
|
| 32 |
with torch.no_grad():
|
| 33 |
outputs = model(**inputs)
|
| 34 |
+
# Mean pooling
|
| 35 |
embeddings = outputs.last_hidden_state.mean(dim=1)
|
|
|
|
| 36 |
return embeddings.cpu().numpy().astype(np.float32)
|
| 37 |
|
| 38 |
# ----------------------------------------------------
|
| 39 |
+
# 3. Load FAISS index
|
| 40 |
# ----------------------------------------------------
|
| 41 |
+
INDEX_PATH = "assets/faiss_ip_768.index"
|
| 42 |
+
index = faiss.read_index(INDEX_PATH)
|
| 43 |
+
|
| 44 |
+
# ----------------------------------------------------
|
| 45 |
+
# 4. Load corpus
|
| 46 |
+
# ----------------------------------------------------
|
| 47 |
+
CORPUS_PATH = "assets/corpus.json"
|
| 48 |
+
with open(CORPUS_PATH, "r", encoding="utf-8") as f:
|
| 49 |
+
CORPUS = json.load(f) # List of strings or dicts
|
| 50 |
+
|
| 51 |
+
# ----------------------------------------------------
|
| 52 |
+
# 5. FAISS search function
|
| 53 |
+
# ----------------------------------------------------
|
| 54 |
+
def search_faiss(query, top_k=5):
|
| 55 |
"""
|
| 56 |
+
Encode the query, search FAISS index, and return top-k results.
|
|
|
|
| 57 |
"""
|
| 58 |
+
if not query.strip():
|
| 59 |
+
return "Please enter a search query."
|
| 60 |
+
|
| 61 |
+
# Encode the query
|
| 62 |
+
query_embedding = encode([query])
|
| 63 |
+
|
| 64 |
+
# Search FAISS
|
| 65 |
+
distances, indices = index.search(query_embedding, top_k)
|
| 66 |
+
|
| 67 |
+
# Map results to corpus
|
| 68 |
+
results = []
|
| 69 |
+
for rank, idx in enumerate(indices[0]):
|
| 70 |
+
# If corpus is a dict, use: CORPUS[idx]['title'] + "\n" + CORPUS[idx]['text']
|
| 71 |
+
results.append(f"#{rank+1} | Score: {distances[0][rank]:.4f}\n{CORPUS[idx]}")
|
| 72 |
+
|
| 73 |
+
return "\n\n".join(results)
|
| 74 |
|
| 75 |
# ----------------------------------------------------
|
| 76 |
+
# 6. Gradio interface
|
| 77 |
# ----------------------------------------------------
|
| 78 |
demo = gr.Interface(
|
| 79 |
+
fn=search_faiss,
|
| 80 |
+
inputs=[
|
| 81 |
+
gr.Textbox(label="Search Query"),
|
| 82 |
+
gr.Slider(1, 20, value=5, step=1, label="Top-K Results")
|
| 83 |
+
],
|
| 84 |
+
outputs=gr.Textbox(label="Results"),
|
| 85 |
+
title="FAISS Semantic Search (EmbeddingGemma-300M)",
|
| 86 |
+
description="Semantic search over a corpus using EmbeddingGemma-300M + FAISS."
|
| 87 |
)
|
| 88 |
|
| 89 |
# ----------------------------------------------------
|
| 90 |
+
# 7. Launch the app
|
| 91 |
# ----------------------------------------------------
|
| 92 |
if __name__ == "__main__":
|
| 93 |
demo.launch()
|
|
|