-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdateAbstractsWith_Avg'edEmbeds.py
More file actions
84 lines (65 loc) · 2.78 KB
/
Copy pathupdateAbstractsWith_Avg'edEmbeds.py
File metadata and controls
84 lines (65 loc) · 2.78 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
import json
import ijson
from tqdm import tqdm
import gc
import numpy as np
from decimal import Decimal
def decimal_default(obj):
if isinstance(obj, Decimal):
return float(obj)
raise TypeError
def update_abstracts_with_averaged_embeddings(input_file, universal_embeddings_file, output_file):
# Load universal term embeddings
print("Loading universal term embeddings...")
with open(universal_embeddings_file, 'r') as f:
universal_embeddings = json.load(f)
print("Starting to update abstracts...")
# Count abstracts for progress bar
print("Counting total abstracts...")
with open(input_file, 'rb') as f:
total_abstracts = sum(1 for _ in ijson.items(f, 'item'))
processed = 0
updated = 0
with open(output_file, 'w') as outf:
outf.write('[') # Start JSON array
# Process abstracts in streaming fashion
with open(input_file, 'rb') as f:
parser = ijson.items(f, 'item')
for abstract in tqdm(parser, total=total_abstracts, desc="Updating abstracts"):
processed += 1
# Update key_embeddings if present
if abstract['key_embeddings']:
updated += 1
new_key_embeddings = []
for term_data in abstract['key_embeddings']:
term = list(term_data.keys())[0]
if term in universal_embeddings:
new_key_embeddings.append({term: [universal_embeddings[term]]})
abstract['key_embeddings'] = new_key_embeddings
if processed > 1:
outf.write(',')
# Use custom encoder for Decimal objects
json.dump(abstract, outf, default=decimal_default)
if processed % 1000 == 0:
gc.collect()
outf.write(']')
print(f"\nProcessed {processed} abstracts")
print(f"Updated {updated} abstracts with terms")
# Verify file was created
import os
file_size = os.path.getsize(output_file)
print(f"Output file size: {file_size/1024/1024:.2f} MB")
def print_memory_usage():
import psutil
process = psutil.Process()
print(f"Memory usage: {process.memory_info().rss / 1024 / 1024:.2f} MB")
print("Initial memory usage:")
print_memory_usage()
update_abstracts_with_averaged_embeddings(
input_file=r'PATH_TO_YOUR_INPUT_FILE.json',
universal_embeddings_file=r'PATH_TO_YOUR_UNIVERSAL_EMBEDDINGS_FILE.json',
output_file=r'PATH_TO_YOUR_OUTPUT_FILE.json'
)
print("\nFinal memory usage:")
print_memory_usage()
print("Done!")