-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
201 lines (164 loc) · 6.41 KB
/
server.py
File metadata and controls
201 lines (164 loc) · 6.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import jwt, datetime, os, time
from flask import Flask, request, jsonify
from sentence_transformers import SentenceTransformer
from dotenv import load_dotenv
from pinecone import Pinecone, ServerlessSpec
from pinecone_text.sparse import BM25Encoder
from pinecone.grpc import PineconeGRPC as Pinecone
# Load environment variables
load_dotenv()
server = Flask(__name__)
# Check if the Flask server is starting
print("Starting Flask server...")
# Initialize SentenceTransformer Model & PineCone Client
print("Initializing SentenceTransformer model and PineCone client...")
model = SentenceTransformer('all-MiniLM-L6-v2')
bm25 = BM25Encoder()
pineconeObj = Pinecone(api_key=os.getenv('PINECONE_API_KEY'))
# Create serverless index with dimension 384
index_name = "car-search-hybrid"
if index_name not in pineconeObj.list_indexes().names():
print("Index not found, creating index...")
pineconeObj.create_index(
name=index_name,
dimension=384,
metric="dotproduct",
spec=ServerlessSpec(
cloud="aws",
region="us-east-1"
)
)
while not pineconeObj.describe_index(index_name).status['ready']:
print("Waiting for index to be ready...")
time.sleep(1)
print("Connecting to the index...")
index = pineconeObj.Index(index_name)
index_stats = index.describe_index_stats()
print("Index connected and ready.")
# Dictionary to store the mapping from vector IDs to car objects
vector_id_to_car = {}
# Create sparse-dense vector embeddings for an array of car descriptions
@server.post('/embedDescriptions')
def embed_descriptions():
print("HIT PYTHON SERVICE!")
car_data = request.json.get('car_data', [])
print("Received car data: ", car_data)
if not car_data:
return jsonify({'error': 'No car data provided'}), 400
# These are dense vectors
dense_embeddings = model.encode(car_data)
print("The shape of the dense vector embeddings are ", dense_embeddings.shape)
# Dense Embeddings are created at this point so semantic part is half done. Now to create sparse vectors.
bm25.fit(car_data)
sparse_vectors = bm25.encode_documents(car_data)
print("Sparse vectors created.")
# Prepare vectors for upsert and map vector IDs to car objects
vectors = []
vector_ids = []
for i, (dense, sparse) in enumerate(zip(dense_embeddings, sparse_vectors)):
vector_id = f'vec{i}'
vector = {
'id': vector_id,
'values': dense.tolist(),
'metadata': {'description': car_data[i]},
'sparse_values': {
'indices': sparse['indices'],
'values': sparse['values']
}
}
vectors.append(vector)
vector_ids.append(vector_id)
vector_id_to_car[vector_id] = car_data[i] # Store the mapping
# Print the mapping for debugging
print("Vector ID to Car Mapping: ", vector_id_to_car)
# Upsert vectors into Pinecone index
upsert_response = index.upsert(
vectors=vectors,
namespace='cars-testing-namespace'
)
# Return the vector IDs
return jsonify({"vector_ids": vector_ids})
# Create a sparse-dense vector embedding of a single car description
@server.post('/embedDescription')
def embed_description():
print("Hit /embedDescription endpoint!")
car_data = request.json.get('car_data', '')
print("Received car data: ", car_data)
if not car_data:
return jsonify({'error': 'No car data provided'}), 400
# Make sure car_data is a list
car_data = [car_data]
# These are dense vectors
dense_embeddings = model.encode(car_data)
print("The shape of the dense vector embeddings are ", dense_embeddings.shape)
# Dense Embeddings are created at this point so semantic part is half done. Now to create sparse vectors.
bm25.fit(car_data)
sparse_vectors = bm25.encode_documents(car_data)
print("Sparse vectors created.")
# Prepare vectors for upsert and map vector IDs to car objects
vectors = []
vector_ids = []
for i, (dense, sparse) in enumerate(zip(dense_embeddings, sparse_vectors)):
vector_id = f'vec{i}'
vector = {
'id': vector_id,
'values': dense.tolist(),
'metadata': {'description': car_data[i]},
'sparse_values': {
'indices': sparse['indices'],
'values': sparse['values']
}
}
vectors.append(vector)
vector_ids.append(vector_id)
vector_id_to_car[vector_id] = car_data[i] # Store the mapping
# Print the mapping for debugging
print("Vector ID to Car Mapping: ", vector_id_to_car)
# Upsert vectors into Pinecone index
upsert_response = index.upsert(
vectors=vectors,
namespace='testing-namespace'
)
# Return the vector IDs
return jsonify({"vector_ids": vector_ids})
# Define the search endpoint
@server.get('/search')
def search():
query_text = request.args.get('query', '')
if not query_text:
return jsonify({'error': 'No query provided'}), 400
# Create dense vector
dense_vector = model.encode([query_text])[0]
print("Dense vector created!")
# Create sparse vector
bm25 = BM25Encoder()
bm25.fit([query_text])
sparse_vector = bm25.encode_queries([query_text])[0]
print("Sparse vector created!")
# Query the index
query_response = index.query(
namespace="cars-testing-namespace",
top_k=10,
vector=dense_vector,
sparse_vector=sparse_vector
)
print("Query response: ", query_response)
# Extract the vector IDs from the query response
vector_ids = [match['id'] for match in query_response['matches']]
print("Vector IDs: ", vector_ids)
# Retrieve the car objects based on the vector IDs
car_objects = [{"vector_id": vector_id, "car": vector_id_to_car.get(vector_id, "Car data not found")} for vector_id in vector_ids]
return jsonify({"results": car_objects})
# Endpoint to get namespaces and their stats
@server.get('/namespaces')
def get_namespaces():
namespaces = index_stats['namespaces']
print(namespaces)
namespace_list = []
for namespace, stats in namespaces.items():
namespace_list.append({"namespace": namespace, "vector_count": stats['vector_count']})
return jsonify({"namespaces": namespace_list})
# Run the Flask server
if __name__ == '__main__':
print("Running Flask server...")
server.run(host='0.0.0.0', port=5005)