-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat-raw-data.py
More file actions
506 lines (423 loc) Β· 18.1 KB
/
Copy pathformat-raw-data.py
File metadata and controls
506 lines (423 loc) Β· 18.1 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
"""Process ndjson files from datacite-slim-records and emdb-slim-records and create NDJSON files with processed datasets."""
import contextlib
import json
import re
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
from tqdm import tqdm
RECORDS_PER_FILE = 10000 # Records per output file
def natural_sort_key(path: Path) -> tuple:
"""Generate a sort key for natural sorting (alphabetical then numerical)."""
name = path.name
# Split filename into text and numeric parts
parts = re.split(r"(\d+)", name)
# Convert numeric parts to int, keep text parts as strings
return tuple(int(part) if part.isdigit() else part.lower() for part in parts)
def clean_string(s: Optional[str]) -> str:
"""Clean string to remove bad characters."""
if not s:
return ""
# Remove replacement characters (\uFFFD) and control characters (\x00-\x1F and \x7F-\x9F)
result = s.replace("\ufffd", "")
# Remove control characters: 0x00-0x1F and 0x7F-0x9F
cleaned = ""
for char in result:
code = ord(char)
if code < 0x20 or (0x7F <= code < 0xA0): # Remove control chars
continue
cleaned += char
return cleaned
def parse_publication_date(record: Dict[str, Any]) -> Optional[datetime]:
"""Parse publication date from record."""
if not record.get("publication_date"):
return None
with contextlib.suppress(ValueError, AttributeError, TypeError):
date_str = record["publication_date"]
if isinstance(date_str, str):
# Handle ISO format with Z suffix
if date_str.endswith("Z"):
date_str = f"{date_str[:-1]}+00:00"
return datetime.fromisoformat(date_str)
return None
def clean_subjects(record: Dict[str, Any]) -> List[str]:
"""Clean subjects from record."""
subjects = []
if subjects_raw := record.get("subjects", []):
for subject in subjects_raw:
if isinstance(subject, str):
if cleaned_subject := clean_string(subject):
subjects.append(cleaned_subject)
return subjects
def extract_pub_year(record: Dict[str, Any]) -> int:
"""Extract pubYear from record, defaulting to 0 if missing."""
raw_pubyear = record.get("pubyear")
if raw_pubyear is not None:
with contextlib.suppress(ValueError, TypeError):
return int(raw_pubyear)
return 0
def extract_publisher_id(record: Dict[str, Any]) -> str:
"""Extract publisherId from record, defaulting to 'unknown' if missing."""
return clean_string(record.get("publisher_id")) or "unknown"
def clean_authors(record: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Clean authors from record."""
authors = []
if authors_raw := record.get("creators", []):
for author in authors_raw:
if isinstance(author, dict):
name_type = author.get("name_type", "")
name = author.get("name", "")
name_identifiers = author.get("identifiers", [])
affiliations = author.get("affiliations", [])
cleaned_author = {
"nameType": name_type,
"name": clean_string(name),
"nameIdentifiers": [
clean_string(identifier) for identifier in name_identifiers
],
"affiliations": [
clean_string(affiliation) for affiliation in affiliations
],
}
authors.append(cleaned_author)
return authors
def parse_datacite_record(record: Dict[str, Any], dataset_id: int) -> Dict[str, Any]:
"""Parse a datacite record into dataset format (db insert ready)."""
source = record.get("source", "")
title = record.get("title", "")
description = (
clean_string(record.get("description")) if record.get("description") else None
)
publisher = record.get("publisher") or None
publisher_id = extract_publisher_id(record)
version = record.get("version") or None
published_at = parse_publication_date(record)
pub_year = extract_pub_year(record)
# Clean subjects
subjects = clean_subjects(record)
# Clean authors - keep as list of dicts, clean name and nameIdentifiers
authors = clean_authors(record)
identifiers = []
if identifiers_raw := record.get("identifiers", []):
# {"identifier": "10.1000/187", "identifierType": "doi"}
for identifier in identifiers_raw:
iv = identifier.get("identifier", "")
identifier_value = iv.lower() if iv else None
it = identifier.get("identifier_type", "") or identifier.get(
"identifierType", ""
)
identifier_type = it.lower() if it else None
if identifier_value and identifier_type:
identifiers.append(
{"identifier": identifier_value, "identifierType": identifier_type}
)
# remove duplicates from identifiers
# Convert to tuples for deduplication (dicts are unhashable)
seen = set()
unique_identifiers = []
for identifier in identifiers:
identifier_tuple = (identifier["identifier"], identifier["identifierType"])
if identifier_tuple not in seen:
seen.add(identifier_tuple)
unique_identifiers.append(identifier)
identifiers = unique_identifiers
else:
identifiers = []
main_identifier = identifiers[0].get("identifier", "")
main_identifier_type = identifiers[0].get("identifierType", "")
if main_identifier_type in ["doi", "emdb_id"]:
main_identifier = main_identifier.lower()
return {
"id": dataset_id,
"source": source,
"identifier": main_identifier,
"identifierType": main_identifier_type,
"title": title,
"extractedIdentifiers": identifiers,
"description": description,
"version": version,
"publisher": publisher,
"publisherId": publisher_id,
"publishedAt": published_at.isoformat() if published_at else None,
"pubYear": pub_year,
"subjects": subjects,
"authors": authors,
}
def parse_emdb_record(record: Dict[str, Any], dataset_id: int) -> Dict[str, Any]:
"""Parse an EMDB record into dataset format (db insert ready)."""
source = record.get("source", "")
title = record.get("title", "")
description = (
clean_string(record.get("description")) if record.get("description") else None
)
publisher = record.get("publisher") or None
publisher_id = extract_publisher_id(record)
version = record.get("version") or None
published_at = parse_publication_date(record)
pub_year = extract_pub_year(record)
# Clean subjects
subjects = clean_subjects(record)
# Clean authors - keep as list of dicts, clean name and nameIdentifiers
authors = clean_authors(record)
# There is only one identifier in EMDB, so we can use it as the main identifier
identifiers_raw = record.get("identifiers", [])
main_identifier = identifiers_raw[0].get("identifier", "").lower()
main_identifier_type = identifiers_raw[0].get(
"identifier_type", ""
) or identifiers_raw[0].get("identifierType", "")
main_identifier_type = (main_identifier_type or "").lower()
identifiers = [
{
"identifier": main_identifier,
"identifierType": main_identifier_type,
}
]
return {
"id": dataset_id,
"source": source,
"identifier": main_identifier,
"identifierType": "emdb",
"title": title,
"extractedIdentifiers": identifiers,
"description": description,
"version": version,
"publisher": publisher,
"publisherId": publisher_id,
"publishedAt": published_at.isoformat() if published_at else None,
"pubYear": pub_year,
"subjects": subjects,
"authors": authors,
}
def count_lines_in_files(ndjson_files: List[Path], source_dir: Path) -> int:
"""Count total number of non-empty lines across all ndjson files."""
total_lines = 0
print(" Counting lines in input files...")
for file_path in tqdm(ndjson_files, desc=" Counting", unit="file"):
full_path = source_dir / file_path
try:
with open(full_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
total_lines += 1
except Exception:
# Skip files that can't be read, will be handled in processing
continue
return total_lines
def write_batch_to_file(
batch: List[Dict[str, Any]],
file_number: int,
output_dir: Path,
prefix: Optional[str] = None,
) -> None:
"""Write a batch of processed records to a numbered NDJSON file."""
file_name = f"{prefix}{file_number}.ndjson" if prefix else f"{file_number}.ndjson"
file_path = output_dir / file_name
with open(file_path, "w", encoding="utf-8") as f:
for record in batch:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
def process_record_line(
raw_line: str,
dataset_id: int,
parser_func: Callable[[Dict[str, Any], int], Dict[str, Any]],
file_name: Optional[str] = None,
) -> Tuple[Optional[Dict[str, Any]], int, bool]:
"""Process a single record line.
Args:
raw_line: Raw JSON line to process
dataset_id: Current dataset ID
parser_func: Function to parse records
file_name: Optional file name for error messages
Returns:
Tuple of (processed_dataset or None, next_dataset_id, success)
"""
try:
record = json.loads(raw_line)
processed_dataset = parser_func(record, dataset_id)
return processed_dataset, dataset_id + 1, True
except (json.JSONDecodeError, KeyError, TypeError) as error:
if file_name:
tqdm.write(f" β οΈ Failed to parse line in {file_name}: {error}")
else:
tqdm.write(f" β οΈ Failed to parse line: {error}")
return None, dataset_id + 1, False
def process_all_files(
ndjson_files: List[Path],
source_dir: Path,
output_dir: Path,
total_lines: int,
parser_func: Callable[[Dict[str, Any], int], Dict[str, Any]],
starting_dataset_id: int = 1,
starting_file_number: int = 1,
prefix: Optional[str] = None,
) -> int:
"""Process all ndjson files and create new NDJSON files with processed records.
Args:
ndjson_files: List of ndjson file paths to process
source_dir: Directory containing the ndjson files
output_dir: Directory to write output JSON files
total_lines: Total number of lines to process (for progress bar)
parser_func: Function to parse records (parse_datacite_record or parse_emdb_record)
starting_dataset_id: Starting dataset ID (default: 1)
Returns:
Final dataset_id after processing all records
"""
dataset_id = starting_dataset_id
file_number = starting_file_number
current_batch: List[str] = [] # Store raw lines until we have enough
total_records_processed = 0
total_records_skipped = 0
# Create progress bar for overall processing
pbar = tqdm(total=total_lines, desc=" Processing", unit="record", unit_scale=True)
# Process files sequentially
for file_path in ndjson_files:
file_name = file_path.name
full_path = source_dir / file_path
with open(full_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
# Add raw line to batch
current_batch.append(line)
pbar.update(1)
# When batch reaches RECORDS_PER_FILE, process and write
if len(current_batch) >= RECORDS_PER_FILE:
processed_batch = []
for raw_line in current_batch:
processed_dataset, dataset_id, success = process_record_line(
raw_line, dataset_id, parser_func, file_name
)
if success:
processed_batch.append(processed_dataset)
total_records_processed += 1
else:
total_records_skipped += 1
# Write the processed batch
write_batch_to_file(
processed_batch, file_number, output_dir, prefix
)
file_number += 1
current_batch = []
pbar.close()
# Process and write any remaining records as the final file
if current_batch:
processed_batch = []
for raw_line in current_batch:
processed_dataset, dataset_id, success = process_record_line(
raw_line, dataset_id, parser_func
)
if success:
processed_batch.append(processed_dataset)
total_records_processed += 1
else:
total_records_skipped += 1
write_batch_to_file(processed_batch, file_number, output_dir, prefix)
print(f"\n π Total records processed: {total_records_processed:,}")
if total_records_skipped > 0:
print(f" β οΈ Total records skipped: {total_records_skipped:,}")
print(f" π Total output files created: {file_number}")
return dataset_id
def main() -> None:
"""Main function to process ndjson files and create NDJSON output files."""
print("π Starting database preparation process...")
datacite_source_folder_name = "datacite-slim-records"
emdb_source_folder_name = "emdb-slim-records"
output_folder_name = "dataset"
# Step 1: Get OS-agnostic path to Downloads/datacite-slim-records
print("π Step 1: Locating source directory...")
home_dir = Path.home()
downloads_dir = home_dir / "Downloads"
datacite_source_dir = downloads_dir / "slim-records" / datacite_source_folder_name
emdb_source_dir = downloads_dir / "slim-records" / emdb_source_folder_name
output_dir = downloads_dir / "database" / output_folder_name
print(f"Reading ndjson files from: {datacite_source_dir}")
print(f"Reading ndjson files from: {emdb_source_dir}")
print(f"Output directory: {output_dir}")
# Check if source directory exists
if not datacite_source_dir.exists():
raise FileNotFoundError(
f"Directory not found: {datacite_source_dir}. "
f"Please ensure the {datacite_source_folder_name} folder exists in your Downloads directory."
)
print("β Datacite source directory found")
if not emdb_source_dir.exists():
raise FileNotFoundError(
f"Directory not found: {emdb_source_dir}. "
f"Please ensure the {emdb_source_folder_name} folder exists in your Downloads directory."
)
print("β EMDB source directory found")
# Clean output directory
if output_dir.exists():
import shutil
shutil.rmtree(output_dir)
print("β Output directory cleaned")
else:
print("β Output directory not found")
# Create output directory if it doesn't exist
output_dir.mkdir(parents=True, exist_ok=True)
print("β Created output directory")
# Step 2: Find all ndjson files in datacite source directory
print("\nπ Step 2: Finding ndjson files...")
ndjson_files = list(datacite_source_dir.glob("*.ndjson"))
# sort by filename using natural sort (alphabetical then numerical)
ndjson_files = sorted(ndjson_files, key=natural_sort_key)
print(f" Found {len(ndjson_files)} .ndjson file(s) to process")
if not ndjson_files:
raise FileNotFoundError("No .ndjson files found in source directory")
# Step 3: Count total lines in all files
print("\nπ Step 3: Counting total lines in input files...")
total_lines = count_lines_in_files(ndjson_files, datacite_source_dir)
print(f" Found {total_lines:,} total lines to process")
# Step 4: Process all files and create new files with processed records
print(
f"\nβοΈ Step 4: Processing files and creating new files "
f"(~{RECORDS_PER_FILE:,} records each)..."
)
final_dataset_id = process_all_files(
ndjson_files,
datacite_source_dir,
output_dir,
total_lines,
parse_datacite_record,
starting_dataset_id=49061168,
starting_file_number=4902,
prefix="datacite-",
)
print("\nβ
Datacite files have been processed successfully!")
print(f"π Processed files are available in: {output_dir}")
# Step 5: Find all ndjson files in emdb source directory
print("\nπ Step 5: Finding ndjson files...")
emdb_ndjson_files = list(emdb_source_dir.glob("*.ndjson"))
print(f" Found {len(emdb_ndjson_files)} .ndjson file(s) to process")
if not emdb_ndjson_files:
raise FileNotFoundError("No .ndjson files found in EMDB source directory")
# Step 6: Count total lines in all files
print("\nπ Step 6: Counting total lines in input files...")
emdb_total_lines = count_lines_in_files(emdb_ndjson_files, emdb_source_dir)
print(f" Found {emdb_total_lines:,} total lines to process")
# Step 7: Process all files and create new files with processed records
# Continue dataset_id from where datacite left off
print(
f"\nβοΈ Step 7: Processing files and creating new files "
f"(~{RECORDS_PER_FILE:,} records each)..."
)
print(f" Continuing dataset_id from {final_dataset_id}...")
process_all_files(
emdb_ndjson_files,
emdb_source_dir,
output_dir,
emdb_total_lines,
parse_emdb_record,
starting_dataset_id=final_dataset_id,
starting_file_number=7,
prefix="emdb-",
)
print("\nβ
All files have been processed successfully!")
print(f"π Processed files are available in: {output_dir}")
if __name__ == "__main__":
try:
main()
except Exception as e:
print("\nβ Error occurred during database preparation:")
print(e)
exit(1)