|
import zstandard as zstd |
|
import json |
|
import csv |
|
import os |
|
|
|
def decompress_zst_file(zst_filename, output_filename): |
|
|
|
with open(zst_filename, 'rb') as zst_file: |
|
dctx = zstd.ZstdDecompressor() |
|
with open(output_filename, 'wb') as out_file: |
|
dctx.copy_stream(zst_file, out_file) |
|
|
|
def extract_metadata_from_jsonl(jsonl_filename, csv_filename): |
|
|
|
with open(jsonl_filename, 'r') as jsonl_file: |
|
|
|
with open(csv_filename, 'w', newline='', encoding='utf-8') as csv_file: |
|
csv_writer = csv.DictWriter(csv_file, fieldnames=['id', 'source', 'version', 'added', 'created', 'title', 'abstract', 'sha1', 'sources', 's2fieldsofstudy', 'extfieldsofstudy', 'external_ids']) |
|
csv_writer.writeheader() |
|
|
|
for line in jsonl_file: |
|
try: |
|
data = json.loads(line) |
|
metadata = data.get('metadata', {}) |
|
|
|
|
|
csv_writer.writerow({ |
|
'id': data.get('id', ''), |
|
'source': data.get('source', ''), |
|
'version': data.get('version', ''), |
|
'added': data.get('added', ''), |
|
'created': data.get('created', ''), |
|
'title': metadata.get('title', ''), |
|
'abstract': metadata.get('abstract', ''), |
|
'sha1': metadata.get('sha1', ''), |
|
'sources': ', '.join(metadata.get('sources', [])), |
|
's2fieldsofstudy': ', '.join(metadata.get('s2fieldsofstudy', [])), |
|
'extfieldsofstudy': ', '.join(metadata.get('extfieldsofstudy', [])), |
|
'external_ids': ', '.join([f"{eid['source']}:{eid['id']}" for eid in metadata.get('external_ids', [])]) |
|
}) |
|
except json.JSONDecodeError: |
|
print(f"Error decoding JSON in line: {line}") |
|
except Exception as e: |
|
print(f"Error processing line: {line}, Error: {e}") |
|
|
|
def process_zst_files(directory, output_directory): |
|
|
|
done_file = [] |
|
for filename in os.listdir(directory): |
|
if filename.endswith('.zst') and filename not in done_file: |
|
zst_filepath = os.path.join(directory, filename) |
|
jsonl_filename = os.path.splitext(zst_filepath)[0] + '.jsonl' |
|
csv_filename = os.path.join(output_directory, os.path.splitext(filename)[0] + '.csv') |
|
|
|
|
|
print(f"Decompressing {zst_filepath}...") |
|
decompress_zst_file(zst_filepath, jsonl_filename) |
|
|
|
|
|
print(f"Extracting metadata from {jsonl_filename} and saving to {csv_filename}...") |
|
extract_metadata_from_jsonl(jsonl_filename, csv_filename) |
|
|
|
|
|
os.remove(jsonl_filename) |
|
done_file.append(filename) |
|
print("done_file = ", done_file) |
|
|
|
if __name__ == '__main__': |
|
|
|
input_directory = 'my_data/peS2o_v3/data/v3' |
|
|
|
|
|
output_directory = 'my_data/peS2o_v3/data/metadata' |
|
|
|
|
|
if not os.path.exists(output_directory): |
|
os.makedirs(output_directory) |
|
|
|
|
|
process_zst_files(input_directory, output_directory) |
|
|