fdaudens commited on
Commit
e1fe2e7
·
verified ·
1 Parent(s): fa2a1b1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -0
app.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json, re
2
+ from typing import List, Tuple
3
+
4
+ import numpy as np
5
+ import gradio as gr
6
+ import faiss
7
+ from sentence_transformers import SentenceTransformer
8
+
9
+ # ---------- Paths (expects files committed under ./assets) ----------
10
+ APP_DIR = os.path.dirname(__file__)
11
+ ASSETS_DIR = os.path.join(APP_DIR, "assets")
12
+ CACHE_DIR = "/mnt/data/eg_space_cache" # runtime cache
13
+ os.makedirs(CACHE_DIR, exist_ok=True)
14
+
15
+ CORPUS_JSON = os.path.join(ASSETS_DIR, "corpus.json")
16
+ EMB_FP32 = os.path.join(ASSETS_DIR, "doc_embs_fp32.npy")
17
+ EMB_FP16 = os.path.join(ASSETS_DIR, "doc_embs_fp16.npy")
18
+ FAISS_MAIN = os.path.join(ASSETS_DIR, "faiss_ip_768.index")
19
+
20
+ # ---------- Matryoshka dims ----------
21
+ MATRYOSHKA_DIMS = [768, 512, 256, 128]
22
+ DEFAULT_DIMS = 768
23
+
24
+ # ---------- Load corpus ----------
25
+ with open(CORPUS_JSON, "r", encoding="utf-8") as f:
26
+ corpus = json.load(f) # list of {"title","text"} in EXACT same order as embeddings
27
+
28
+ # ---------- Load embeddings ----------
29
+ if os.path.exists(EMB_FP32):
30
+ doc_embs = np.load(EMB_FP32).astype(np.float32, copy=False)
31
+ elif os.path.exists(EMB_FP16):
32
+ doc_embs = np.load(EMB_FP16).astype(np.float32) # cast back for FAISS
33
+ else:
34
+ raise FileNotFoundError("Expected assets/doc_embs_fp32.npy or assets/doc_embs_fp16.npy")
35
+
36
+ if doc_embs.ndim != 2 or doc_embs.shape[0] != len(corpus):
37
+ raise ValueError("Embeddings shape mismatch vs corpus length.")
38
+
39
+ EMB_DIM = doc_embs.shape[1] # should be 768
40
+
41
+ # ---------- Model (for queries + sentence-level ops) ----------
42
+ model = SentenceTransformer("google/embeddinggemma-300m") # CPU is fine for queries
43
+
44
+ # ---------- FAISS indexes ----------
45
+ # Option A: load a ready-made 768-dim index if provided
46
+ if os.path.exists(FAISS_MAIN):
47
+ base_index_768 = faiss.read_index(FAISS_MAIN)
48
+ else:
49
+ base_index_768 = faiss.IndexFlatIP(EMB_DIM)
50
+ base_index_768.add(doc_embs.astype(np.float32, copy=False))
51
+
52
+ # Build per-dimension flat IP indexes from the loaded embeddings
53
+ class MultiDimFaiss:
54
+ def __init__(self, doc_embs_full: np.ndarray):
55
+ self.full = doc_embs_full
56
+ self.indexes = {}
57
+ for d in MATRYOSHKA_DIMS:
58
+ if d == 768 and FAISS_MAIN and os.path.exists(FAISS_MAIN):
59
+ self.indexes[d] = base_index_768
60
+ else:
61
+ view = self.full[:, :d].astype(np.float32, copy=False)
62
+ idx = faiss.IndexFlatIP(d)
63
+ idx.add(view)
64
+ self.indexes[d] = idx
65
+
66
+ def search(self, q_vec: np.ndarray, top_k: int, dims: int) -> Tuple[np.ndarray, np.ndarray]:
67
+ q = q_vec[:dims].astype(np.float32, copy=False)[None, :]
68
+ idx = self.indexes[dims]
69
+ return idx.search(q, top_k)
70
+
71
+ faiss_md = MultiDimFaiss(doc_embs)
72
+
73
+ # ---------- Core ops ----------
74
+ def _format_snippet(text: str, max_len: int = 380) -> str:
75
+ return text[:max_len] + ("…" if len(text) > max_len else "")
76
+
77
+ def do_search(query: str, top_k: int = 5, dims: int = DEFAULT_DIMS) -> List[List[str]]:
78
+ if not query or not query.strip():
79
+ return []
80
+ q_emb = model.encode_query(
81
+ query.strip(),
82
+ normalize_embeddings=True,
83
+ convert_to_numpy=True
84
+ )
85
+ scores, idxs = faiss_md.search(q_emb, top_k=top_k, dims=dims)
86
+ rows = []
87
+ for s, i in zip(scores[0].tolist(), idxs[0].tolist()):
88
+ if i == -1:
89
+ continue
90
+ title = corpus[i]["title"]
91
+ snippet = _format_snippet(corpus[i]["text"])
92
+ rows.append([f"{s:.4f}", title, snippet])
93
+ return rows
94
+
95
+ def do_similarity(text_a: str, text_b: str, dims: int = DEFAULT_DIMS) -> float:
96
+ if not text_a or not text_b:
97
+ return 0.0
98
+ a = model.encode_document([text_a], normalize_embeddings=True, convert_to_numpy=True)[0][:dims]
99
+ b = model.encode_document([text_b], normalize_embeddings=True, convert_to_numpy=True)[0][:dims]
100
+ return float(np.dot(a, b))
101
+
102
+ # Extractive summarization using EmbeddingGemma's Summarization prompt
103
+ def _split_sents(text: str):
104
+ parts = re.split(r"(?<=[\.!?])\s+", text.strip())
105
+ return [p.strip() for p in parts if p.strip()]
106
+
107
+ def summarize_extractive(text: str, n: int, dims: int, lambda_diversity: float = 0.7) -> str:
108
+ sents = _split_sents(text)
109
+ if not sents:
110
+ return ""
111
+ embs = model.encode(
112
+ sents,
113
+ prompt_name="Summarization",
114
+ normalize_embeddings=True,
115
+ convert_to_numpy=True,
116
+ batch_size=128,
117
+ )[:, :dims]
118
+ centroid = embs.mean(axis=0)
119
+ base = embs @ centroid
120
+
121
+ picked = []
122
+ for _ in range(min(n, len(sents))):
123
+ if not picked:
124
+ i = int(np.argmax(base))
125
+ else:
126
+ sim_to_sel = np.max(embs[picked] @ embs.T, axis=0)
127
+ mmr = (1 - lambda_diversity) * base + lambda_diversity * (1 - sim_to_sel)
128
+ i = int(np.argmax(mmr))
129
+ picked.append(i)
130
+ base[i] = -1e9
131
+ # keep original order
132
+ ordered = [s for _, s in sorted(zip(picked, [sents[i] for i in picked]))]
133
+ return " ".join(ordered)
134
+
135
+ # ---------- Gradio UI ----------
136
+ with gr.Blocks(title="EmbeddingGemma × Wikipedia (EN corpus)") as demo:
137
+ gr.Markdown(
138
+ "# EmbeddingGemma × Wikipedia (EN corpus)\n"
139
+ "Search, cross-lingual retrieval (to EN), similarity, and extractive summarization.\n"
140
+ "Model: `google/embeddinggemma-300m` • Docs indexed from `corpus.json` • Precomputed embeddings loaded from assets."
141
+ )
142
+
143
+ with gr.Tabs():
144
+ # 1) Semantic Search (EN-only corpus)
145
+ with gr.TabItem("Semantic Search (EN corpus)"):
146
+ with gr.Row():
147
+ q = gr.Textbox(label="Query", value="Who discovered penicillin?")
148
+ topk = gr.Slider(1, 20, value=5, step=1, label="Top-K")
149
+ dims = gr.Dropdown([str(d) for d in MATRYOSHKA_DIMS], value=str(DEFAULT_DIMS), label="Embedding dims")
150
+ run = gr.Button("Search")
151
+ out = gr.Dataframe(headers=["score", "title", "snippet"], wrap=True)
152
+ run.click(lambda query, k, d: do_search(query, int(k), int(d)), [q, topk, dims], out)
153
+
154
+ # 2) Cross-Lingual (queries in FR/ES/etc → EN corpus)
155
+ with gr.TabItem("Cross-Lingual (EN corpus)"):
156
+ gr.Markdown("Type your query in **French/Spanish/Arabic**. Results come from the **English-only** corpus.")
157
+ with gr.Row():
158
+ qx = gr.Textbox(label="Query", value="¿Quién descubrió la penicilina?")
159
+ topkx = gr.Slider(1, 20, value=5, step=1, label="Top-K")
160
+ dimsx = gr.Dropdown([str(d) for d in MATRYOSHKA_DIMS], value=str(DEFAULT_DIMS), label="Embedding dims")
161
+ runx = gr.Button("Search")
162
+ outx = gr.Dataframe(headers=["score", "title", "snippet"], wrap=True)
163
+ runx.click(lambda query, k, d: do_search(query, int(k), int(d)), [qx, topkx, dimsx], outx)
164
+
165
+ # 3) Similarity
166
+ with gr.TabItem("Similarity"):
167
+ with gr.Row():
168
+ a = gr.Textbox(lines=5, label="Text A", value="Alexander Fleming observed a mold that killed bacteria in 1928.")
169
+ b = gr.Textbox(lines=5, label="Text B", value="La penicilina fue descubierta por Alexander Fleming en 1928.")
170
+ dims2 = gr.Dropdown([str(d) for d in MATRYOSHKA_DIMS], value=str(DEFAULT_DIMS), label="Embedding dims")
171
+ sim_btn = gr.Button("Compute Similarity")
172
+ sim_out = gr.Number(label="Cosine similarity (-1..1)")
173
+ sim_btn.click(lambda x, y, d: do_similarity(x, y, int(d)), [a, b, dims2], sim_out)
174
+
175
+ # 4) Summarization (extractive)
176
+ with gr.TabItem("Summarization"):
177
+ gr.Markdown("**Extractive summarization** using EmbeddingGemma's `Summarization` prompt. Paste any long text.")
178
+ with gr.Row():
179
+ sum_dims = gr.Dropdown([str(d) for d in MATRYOSHKA_DIMS], value=str(DEFAULT_DIMS), label="Embedding dims")
180
+ sum_n = gr.Slider(1, 10, value=5, step=1, label="Sentences in summary")
181
+ sum_text = gr.Textbox(lines=12, label="Text to summarize", value="Paste a Wikipedia article (or any text) here…")
182
+ sum_btn = gr.Button("Summarize")
183
+ sum_out = gr.Textbox(lines=10, label="Summary")
184
+ sum_btn.click(lambda t, n, d: summarize_extractive(t, int(n), int(d)), [sum_text, sum_n, sum_dims], sum_out)
185
+
186
+ if __name__ == "__main__":
187
+ demo.launch(server_name="0.0.0.0", server_port=7860)