-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembed.py
More file actions
executable file
·73 lines (66 loc) · 1.95 KB
/
embed.py
File metadata and controls
executable file
·73 lines (66 loc) · 1.95 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
#!/usr/bin/env python3
import subprocess
import json
import numpy as np
import cohere
import os
import sys
# Initialize Cohere client
co = cohere.Client(os.getenv("COHERE_API_KEY"))
# Get LIBRARY_ID from environment
LIBRARY_ID = os.getenv("LIBRARY_ID")
if not LIBRARY_ID:
print("Error: LIBRARY_ID environment variable not set", file=sys.stderr)
exit(1)
# Run testSearch.sh with LIBRARY_ID
try:
result = subprocess.run(
["./testSearch.sh"],
capture_output=True,
text=True,
env={**os.environ, "LIBRARY_ID": LIBRARY_ID},
check=True
)
search_output = result.stdout
except subprocess.CalledProcessError as e:
print(f"Error running testSearch.sh for library {LIBRARY_ID}: {e}", file=sys.stderr)
exit(1)
# Parse search output
try:
chunks = json.loads(search_output)
if not isinstance(chunks, list):
chunks = []
except json.JSONDecodeError:
print(f"Error: Invalid JSON from testSearch.sh for library {LIBRARY_ID}", file=sys.stderr)
exit(1)
# Extract texts
texts = [chunk["text"] for chunk in chunks if "text" in chunk]
if not texts:
print(f"Error: No texts found in testSearch.sh output for library {LIBRARY_ID}", file=sys.stderr)
exit(1)
# Generate embeddings
try:
response = co.embed(
texts=texts,
model="embed-english-v3.0",
input_type="search_document"
)
embeddings = response.embeddings
except cohere.CohereAPIError as e:
print(f"Cohere API error: {e}", file=sys.stderr)
exit(1)
# Save embeddings
output = [
{
"chunk_id": chunk["chunk_id"],
"text": chunk["text"],
"metadata": chunk["metadata"],
"embedding": embedding
}
for chunk, embedding in zip(chunks, embeddings)
]
with open("embedded_output.json", "a") as f: # Append to accumulate embeddings
json.dump(output, f, indent=2)
f.write("\n")
np.save("embeddings.npy", output)
print(f"Successfully generated embeddings for library {LIBRARY_ID}")