nikolltt commited on
Commit
149c7e4
·
verified ·
1 Parent(s): a5a9c98

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -26
app.py CHANGED
@@ -1,38 +1,57 @@
1
- import gradio as gr
 
2
  import pandas as pd
 
3
  from sentence_transformers import SentenceTransformer
4
  import faiss
 
 
 
 
 
 
 
 
 
5
 
6
- # 1. Dataset replace or load from CSV
7
- texts = [
8
- "Creativity is intelligence having fun.",
9
- "Simplicity is the ultimate sophistication.",
10
- "Innovation distinguishes between a leader and a follower.",
11
- # Add more...
12
- ]
13
- df = pd.DataFrame({"text": texts})
14
 
15
- # 2. Embeddings + FAISS index
16
- model = SentenceTransformer("all-MiniLM-L6-v2")
17
- emb = model.encode(df["text"].tolist(), convert_to_numpy=True).astype("float32")
18
- faiss.normalize_L2(emb)
19
- index = faiss.IndexFlatIP(emb.shape[1])
20
- index.add(emb)
 
 
 
 
 
21
 
22
- # 3. Search function
23
- def search(query):
 
 
24
  qv = model.encode([query], convert_to_numpy=True).astype("float32")
25
  faiss.normalize_L2(qv)
26
- D, I = index.search(qv, 3) # top 3
27
- return "\n".join([df.iloc[i]["text"] for i in I[0]])
 
 
 
28
 
29
- # 4. Gradio UI
 
30
  demo = gr.Interface(
31
- fn=search,
32
- inputs=gr.Textbox(lines=2, placeholder="Type something..."),
33
- outputs="text",
34
- title="Mini Quote Finder",
35
- description="Type a phrase, get similar quotes."
 
36
  )
37
 
38
- demo.launch()
 
 
1
+ # app.py
2
+ import os
3
  import pandas as pd
4
+ import numpy as np
5
  from sentence_transformers import SentenceTransformer
6
  import faiss
7
+ import gradio as gr
8
+
9
+ # --- 1) Load the CSV you just uploaded ---
10
+ df = pd.read_csv("quotes.csv")
11
+ corpus = df["text"].astype(str).tolist()
12
+
13
+ # --- 2) Prepare embedding model ---
14
+ MODEL_NAME = "all-MiniLM-L6-v2"
15
+ model = SentenceTransformer(MODEL_NAME)
16
 
17
+ # --- 3) Build or load embeddings + FAISS index (cached if already computed) ---
18
+ EMB_FILE = "embeddings.npy"
19
+ IDX_FILE = "index.faiss"
 
 
 
 
 
20
 
21
+ if os.path.exists(EMB_FILE) and os.path.exists(IDX_FILE):
22
+ corpus_embeddings = np.load(EMB_FILE)
23
+ index = faiss.read_index(IDX_FILE)
24
+ else:
25
+ corpus_embeddings = model.encode(corpus, convert_to_numpy=True).astype("float32")
26
+ # normalize for cosine
27
+ faiss.normalize_L2(corpus_embeddings)
28
+ index = faiss.IndexFlatIP(corpus_embeddings.shape[1])
29
+ index.add(corpus_embeddings)
30
+ np.save(EMB_FILE, corpus_embeddings)
31
+ faiss.write_index(index, IDX_FILE)
32
 
33
+ # --- 4) Search function ---
34
+ def get_top3(query):
35
+ if not query or query.strip()=="":
36
+ return "Type something to see 3 similar quotes."
37
  qv = model.encode([query], convert_to_numpy=True).astype("float32")
38
  faiss.normalize_L2(qv)
39
+ D, I = index.search(qv, 3)
40
+ res = []
41
+ for idx in I[0]:
42
+ res.append(corpus[idx])
43
+ return "\n\n".join([f"{i+1}. {r}" for i,r in enumerate(res)])
44
 
45
+ # --- 5) Gradio UI ---
46
+ examples = [["creativity"], ["return process"], ["make returns effortless"]]
47
  demo = gr.Interface(
48
+ fn=get_top3,
49
+ inputs=gr.Textbox(lines=2, placeholder="Type a phrase (e.g., 'make returns easy')"),
50
+ outputs=gr.Textbox(label="Top 3 similar quotes"),
51
+ title="Quote Finder (semantic search)",
52
+ description="Type something and get 3 similar quotes from the dataset.",
53
+ examples=examples
54
  )
55
 
56
+ if __name__ == "__main__":
57
+ demo.launch()