borgo9 commited on
Commit
77d88ce
Β·
verified Β·
1 Parent(s): de63609

Upload app (7).py

Browse files
Files changed (1) hide show
  1. app (7).py +77 -0
app (7).py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json
2
+ from typing import List
3
+ import numpy as np
4
+ import gradio as gr
5
+ import faiss
6
+ from sentence_transformers import SentenceTransformer
7
+
8
+ HF_TOKEN = os.getenv("HF_TOKEN")
9
+
10
+ # # ---------- Paths ----------
11
+ # APP_DIR = os.path.dirname(__file__)
12
+ # CORPUS_JSON = os.path.join(APP_DIR, "corpus.json")
13
+ # FAISS_MAIN = os.path.join(APP_DIR, "faiss_ip_768.index")
14
+
15
+ # # ---------- Load corpus ----------
16
+ # with open(CORPUS_JSON, "r", encoding="utf-8") as f:
17
+ # corpus = json.load(f) # [{"title", "text"}, ...]
18
+
19
+ # # ---------- Load FAISS index ----------
20
+ # if not os.path.exists(FAISS_MAIN):
21
+ # raise FileNotFoundError(f"Missing FAISS index at {FAISS_MAIN}")
22
+ # index = faiss.read_index(FAISS_MAIN)
23
+
24
+ # # Infer dimension from index
25
+ # EMB_DIM = index.d
26
+
27
+ # ---------- Model ----------
28
+ model = SentenceTransformer("google/embeddinggemma-300m", token=HF_TOKEN)
29
+
30
+ # ---------- 1. Display Similarity ----------
31
+ def do_similarity(text_a: str, text_b: str) -> float:
32
+ embeddings = model.encode(
33
+ [text_a, text_b],
34
+ normalize_embeddings=True,
35
+ convert_to_numpy=True
36
+ )
37
+
38
+ # The dot product of two normalized vectors is their cosine similarity.
39
+ similarity_score = np.dot(embeddings[0], embeddings[1])
40
+ return float(similarity_score)
41
+
42
+ # # ---------- 2. Semantic Search ----------
43
+ # def do_search(query: str, top_k: int = 5) -> List[List[str]]:
44
+ # if not query.strip():
45
+ # return []
46
+ # ##################################
47
+ # # INSERT YOUR CODE HERE
48
+ # ##################################
49
+ # rows = []
50
+ # for score, i in zip(scores[0], idxs[0]):
51
+ # if i == -1: continue
52
+ # item = corpus[i]
53
+ # snippet = item["text"][:380] + ("…" if len(item["text"]) > 380 else "")
54
+ # rows.append([f"{score:.4f}", item["title"], snippet])
55
+ # return rows
56
+
57
+ # ---------- UI ----------
58
+ with gr.Blocks(title="Embeddings Lab") as demo:
59
+ gr.Markdown("# Google Gemma")
60
+
61
+ with gr.Tabs():
62
+ with gr.TabItem("Display Similarity"):
63
+ a = gr.Textbox(lines=4, label="Text A")
64
+ b = gr.Textbox(lines=4, label="Text B")
65
+ sim_btn = gr.Button("Compute")
66
+ sim_out = gr.Number(label="Cosine similarity")
67
+ sim_btn.click(lambda x, y: do_similarity(x, y), [a, b], sim_out, api_name="similarity")
68
+
69
+ # with gr.TabItem("Semantic Search"):
70
+ # q = gr.Textbox(label="Query")
71
+ # topk = gr.Slider(1, 20, value=5, step=1, label="Top-K")
72
+ # run = gr.Button("Search")
73
+ # out = gr.Dataframe(headers=["score", "title", "snippet"], wrap=True)
74
+ # run.click(lambda query, k: do_search(query, int(k)), [q, topk], out, api_name="search")
75
+
76
+ if __name__ == "__main__":
77
+ demo.launch(server_name="0.0.0.0", server_port=7860)