Subham9126 commited on
Commit
34ebb45
·
verified ·
1 Parent(s): e519146

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -36
app.py CHANGED
@@ -2,47 +2,68 @@ import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
  from sentence_transformers import SentenceTransformer
5
- from sklearn.metrics.pairwise import cosine_similarity
 
 
6
 
7
- # Load the model
8
- model = SentenceTransformer('all-MiniLM-L6-v2')
 
 
9
 
10
- def load_csv(file):
11
- df = pd.read_csv(file.name)
12
- return df
13
 
14
- def search_similar_queries(query, df, top_k=5):
15
- # Encode the query
16
- query_embedding = model.encode([query])
17
 
18
- # Encode all queries in the DataFrame
19
- all_embeddings = model.encode(df['query'].tolist())
20
-
21
- # Calculate cosine similarity
22
- similarities = cosine_similarity(query_embedding, all_embeddings)[0]
23
-
24
- # Get top-k similar queries
25
- top_indices = np.argsort(similarities)[-top_k:][::-1]
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- results = []
28
- for idx in top_indices:
 
 
 
 
 
 
 
29
  result = {
30
- 'query': df.iloc[idx]['query'],
31
- 'similarity': similarities[idx],
32
- 'uber_intent': df.iloc[idx]['uber_intent'],
33
- 'common_intent': df.iloc[idx]['common_intent'],
34
- 'sub_common_intent': df.iloc[idx]['sub_common_intent'],
35
- 'fsc': df.iloc[idx]['fsc'],
36
- 'language': df.iloc[idx]['language'],
37
- 'Name': df.iloc[idx]['Name']
38
  }
39
- results.append(result)
40
-
41
- return results
42
 
43
- def gradio_interface(csv_file, query, top_k):
44
- df = load_csv(csv_file)
45
- results = search_similar_queries(query, df, top_k)
46
 
47
  output = ""
48
  for i, result in enumerate(results, 1):
@@ -58,17 +79,19 @@ def gradio_interface(csv_file, query, top_k):
58
 
59
  return output
60
 
 
 
 
61
  # Create Gradio interface
62
  iface = gr.Interface(
63
  fn=gradio_interface,
64
  inputs=[
65
- gr.File(label="Upload CSV file"),
66
  gr.Textbox(label="Enter your query"),
67
  gr.Slider(minimum=1, maximum=10, step=1, label="Top-K results", value=5)
68
  ],
69
  outputs=gr.Textbox(label="Results"),
70
- title="Query Similarity Search",
71
- description="Upload a CSV file, enter a query, and find similar queries with associated metadata."
72
  )
73
 
74
  # Launch the interface
 
2
  import pandas as pd
3
  import numpy as np
4
  from sentence_transformers import SentenceTransformer
5
+ import chromadb
6
+ from chromadb.config import Settings
7
+ from chromadb.utils import embedding_functions
8
 
9
+ # Constants
10
+ CSV_PATH = "path/to/your/csv/file.csv" # Replace with your actual CSV file path
11
+ COLLECTION_NAME = "query_embeddings"
12
+ EMBEDDING_MODEL = 'all-MiniLM-L6-v2'
13
 
14
+ # Initialize embedding model
15
+ embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(model_name=EMBEDDING_MODEL)
 
16
 
17
+ # Initialize Chroma client
18
+ chroma_client = chromadb.Client(Settings(persist_directory="./chroma_db"))
 
19
 
20
+ def load_and_embed_data():
21
+ # Load CSV
22
+ df = pd.read_csv(CSV_PATH)
23
+
24
+ # Create or get collection
25
+ collection = chroma_client.get_or_create_collection(name=COLLECTION_NAME, embedding_function=embedding_function)
26
+
27
+ # Check if collection is empty
28
+ if collection.count() == 0:
29
+ print("Embedding and storing data. This may take a while...")
30
+ # Embed and store data
31
+ collection.add(
32
+ documents=df['query'].tolist(),
33
+ metadatas=df.to_dict('records'),
34
+ ids=[str(i) for i in range(len(df))]
35
+ )
36
+ print("Data embedded and stored.")
37
+ else:
38
+ print("Data already embedded and stored.")
39
+
40
+ return collection
41
 
42
+ def search_similar_queries(query, collection, top_k=5):
43
+ results = collection.query(
44
+ query_texts=[query],
45
+ n_results=top_k,
46
+ include=["metadatas", "distances"]
47
+ )
48
+
49
+ formatted_results = []
50
+ for i in range(len(results['ids'][0])):
51
  result = {
52
+ 'query': results['metadatas'][0][i]['query'],
53
+ 'similarity': 1 - results['distances'][0][i], # Convert distance to similarity
54
+ 'uber_intent': results['metadatas'][0][i]['uber_intent'],
55
+ 'common_intent': results['metadatas'][0][i]['common_intent'],
56
+ 'sub_common_intent': results['metadatas'][0][i]['sub_common_intent'],
57
+ 'fsc': results['metadatas'][0][i]['fsc'],
58
+ 'language': results['metadatas'][0][i]['language'],
59
+ 'Name': results['metadatas'][0][i]['Name']
60
  }
61
+ formatted_results.append(result)
62
+
63
+ return formatted_results
64
 
65
+ def gradio_interface(query, top_k):
66
+ results = search_similar_queries(query, collection, top_k)
 
67
 
68
  output = ""
69
  for i, result in enumerate(results, 1):
 
79
 
80
  return output
81
 
82
+ # Load and embed data
83
+ collection = load_and_embed_data()
84
+
85
  # Create Gradio interface
86
  iface = gr.Interface(
87
  fn=gradio_interface,
88
  inputs=[
 
89
  gr.Textbox(label="Enter your query"),
90
  gr.Slider(minimum=1, maximum=10, step=1, label="Top-K results", value=5)
91
  ],
92
  outputs=gr.Textbox(label="Results"),
93
+ title="Optimized Query Similarity Search",
94
+ description="Enter a query to find similar queries with associated metadata."
95
  )
96
 
97
  # Launch the interface