AzizTh commited on
Commit
2fe3a1c
·
verified ·
1 Parent(s): 8f3349b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import faiss
4
+ import gradio as gr
5
+ from sentence_transformers import SentenceTransformer
6
+
7
+ # Load the CSV file with embeddings
8
+ csv_path = 'df_after_rec_embedding.csv' # Update with your actual CSV path
9
+ df = pd.read_csv(csv_path)
10
+ data = df.to_numpy().astype('float32')
11
+
12
+ # Create a FAISS index
13
+ dimension = data.shape[1]
14
+ index = faiss.IndexFlatL2(dimension) # L2 distance metric
15
+ index.add(data) # Add data to the index
16
+
17
+ # Load the nomic-ai/nomic-embed-text-v1 model
18
+ model = SentenceTransformer('nomic-ai/nomic-embed-text-v1',device='cpu', trust_remote_code=True)
19
+
20
+
21
+ # Function to embed query and search using FAISS
22
+ def search(query):
23
+ # Embed the query using the model
24
+ query_vector = model.encode([query])[0].astype('float32')
25
+
26
+ # Search the FAISS index
27
+ distances, indices = index.search(np.array([query_vector]), k=5) # Search for top 5 closest vectors
28
+
29
+ # Return results with indices and distances
30
+ return [f"Index: {i}, Distance: {d:.4f}" for i, d in zip(indices[0], distances[0])]
31
+
32
+
33
+ # Create the Gradio interface
34
+ def gradio_app():
35
+ with gr.Blocks() as demo:
36
+ gr.Markdown("## FAISS Search Interface with Nomic Embedder")
37
+
38
+ with gr.Row():
39
+ with gr.Column():
40
+ query_input = gr.Textbox(
41
+ label="Search Query",
42
+ placeholder="Type your search query here"
43
+ )
44
+ search_button = gr.Button("Search")
45
+
46
+ with gr.Column():
47
+ search_results = gr.Textbox(label="Search Results")
48
+
49
+ search_button.click(
50
+ fn=search,
51
+ inputs=[query_input],
52
+ outputs=[search_results]
53
+ )
54
+
55
+ return demo
56
+
57
+
58
+ # Launch the Gradio app
59
+ demo = gradio_app()
60
+ demo.launch()