-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLLM as RecSys (1).py
230 lines (114 loc) · 3.48 KB
/
LLM as RecSys (1).py
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
import pandas as pd
# In[3]:
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm
import pickle
# In[4]:
import os
print(os.getcwd())
# In[5]:
# Get the path to the user's home directory
home_dir = os.path.expanduser("~")
# Construct the path to the Downloads folder
downloads_path = os.path.join(home_dir, "Downloads")
# Construct the full path to the CSV file
file_path = os.path.join(downloads_path, "netflix_titles.csv")
# In[6]:
df = pd.read_csv(file_path)
# In[7]:
print (df.head())
# In[8]:
df
# In[9]:
def create_textual_representation(row):
textual_representation = f"""Type: {row['type']},
Title: {row['title']},
Director: {row['director']},
Cast: {row['cast']},
Released: {row['release_year']},
Genres: {row['listed_in']},
Description: {row['description']}"""
return textual_representation
# In[10]:
df['textual_representation'] = df.apply(create_textual_representation, axis=1)
# In[11]:
df
# In[12]:
print (df['textual_representation'].values[1])
# In[13]:
import faiss
# In[14]:
import requests
import numpy as np
dim = 4096
index = faiss.IndexFlatL2(dim)
X = np.zeros((len(df['textual_representation']), dim), dtype= 'float32')
# In[15]:
X
# In[16]:
def get_embedding(text):
res = requests.post('http://localhost:11434/api/embeddings',
json={
'model': 'llama2',
'prompt': text
})
return res.json()['embedding']
# Function to process a batch of items
def process_batch(batch):
return [get_embedding(text) for text in batch]
# Check if cached embeddings exist
cache_file = 'embeddings_cache.pkl'
if os.path.exists(cache_file):
with open(cache_file, 'rb') as f:
X = pickle.load(f)
print("Loaded embeddings from cache.")
else:
# Batch size and number of workers
batch_size = 10
num_workers = 5
# Create batches
batches = [df['textual_representation'][i:i+batch_size] for i in range(0, len(df), batch_size)]
# Process batches in parallel
with ThreadPoolExecutor(max_workers=num_workers) as executor:
futures = [executor.submit(process_batch, batch) for batch in batches]
# Use tqdm for a progress bar
for i, future in enumerate(tqdm(as_completed(futures), total=len(futures), desc="Generating Embeddings")):
start_idx = i * batch_size
end_idx = min((i + 1) * batch_size, len(df))
X[start_idx:end_idx] = future.result()
# Cache the embeddings
with open(cache_file, 'wb') as f:
pickle.dump(X, f)
print("Saved embeddings to cache.")
# Add vectors to the index
index.add(X)
# In[51]:
index= faiss.write_index(index, 'index')
# In[69]:
df [df.title.str.contains ('Unbroken')]
# In[70]:
favorite_movie = df.iloc[3595]
# In[71]:
res = requests.post('http://localhost:11434/api/embeddings',
json={
'model': 'llama2',
'prompt': favorite_movie ['textual_representation']
})
# In[75]:
embedding = np.array([res.json()['embedding']], dtype = 'float32')
D, I = index.search(embedding, 5)
# In[76]:
best_matches = np.array(df['textual_representation']) [I.flatten()]
# In[64]:
for match in best_matches :
print('Next Movie')
print(match)
print()
#
# In[ ]:
# In[ ]: