Upload 2 files
#1
by
omeyb
- opened
- code/local-embedding.py +60 -0
- code/requirements.txt +3 -0
code/local-embedding.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
from neo4j import GraphDatabase
|
3 |
+
from tqdm import tqdm
|
4 |
+
import csv # Added for CSV handling
|
5 |
+
|
6 |
+
# ==== CONFIG ====
|
7 |
+
|
8 |
+
NEO4J_URI = "bolt://1.1.1.1:7687"
|
9 |
+
NEO4J_USER = "neo4j"
|
10 |
+
NEO4J_PASSWORD = "your_password"
|
11 |
+
CSV_FILENAME = "movie_embeddings.csv" # Output CSV file name
|
12 |
+
|
13 |
+
OLLAMA_EMBEDDING_MODEL = "nomic-embed-text:v1.5"
|
14 |
+
OLLAMA_ENDPOINT = "http://localhost:11434/api/embeddings"
|
15 |
+
|
16 |
+
# ==== FUNCTIONS ====
|
17 |
+
|
18 |
+
def get_movies(driver):
|
19 |
+
with driver.session() as session:
|
20 |
+
result = session.run("MATCH (m:Movie) RETURN m.movieId AS movieId, m.plot AS plot")
|
21 |
+
return [(record["movieId"], record["plot"]) for record in result if record["plot"]]
|
22 |
+
|
23 |
+
def get_embedding(text):
|
24 |
+
response = requests.post(OLLAMA_ENDPOINT, json={
|
25 |
+
"model": OLLAMA_EMBEDDING_MODEL,
|
26 |
+
"prompt": text # Fixed typo: "prompt" instead of "prompt"
|
27 |
+
})
|
28 |
+
response.raise_for_status()
|
29 |
+
return response.json()["embedding"]
|
30 |
+
|
31 |
+
# ==== MAIN ====
|
32 |
+
|
33 |
+
def main():
|
34 |
+
driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
|
35 |
+
|
36 |
+
print("Fetching movie plots from Neo4j...")
|
37 |
+
movies = get_movies(driver)
|
38 |
+
|
39 |
+
print(f"Embedding {len(movies)} plots with Ollama model `{OLLAMA_EMBEDDING_MODEL}`...")
|
40 |
+
print(f"Results will be saved to {CSV_FILENAME}")
|
41 |
+
|
42 |
+
# Open CSV file for writing
|
43 |
+
with open(CSV_FILENAME, 'w', newline='') as csvfile:
|
44 |
+
csv_writer = csv.writer(csvfile)
|
45 |
+
csv_writer.writerow(['movieId', 'embedding']) # Write header
|
46 |
+
|
47 |
+
for movie_id, plot in tqdm(movies):
|
48 |
+
try:
|
49 |
+
embedding = get_embedding(plot)
|
50 |
+
# Format embedding as string with brackets and commas
|
51 |
+
embedding_str = "[" + ",".join(map(str, embedding)) + "]"
|
52 |
+
csv_writer.writerow([movie_id, embedding_str])
|
53 |
+
except Exception as e:
|
54 |
+
print(f"Failed for movieId={movie_id}: {e}")
|
55 |
+
|
56 |
+
driver.close()
|
57 |
+
print("Embedding export complete!")
|
58 |
+
|
59 |
+
if __name__ == "__main__":
|
60 |
+
main()
|
code/requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
neo4j
|
2 |
+
requests
|
3 |
+
tqdm
|