peS2o_v3_metadata / extract_metadata.py
jackkuo's picture
Upload folder using huggingface_hub
eb8ec0b verified
import zstandard as zstd
import json
import csv
import os
def decompress_zst_file(zst_filename, output_filename):
# 打开 .zst 文件并解压
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):
# 打开 .jsonl 文件并解析其中的每行 JSON 数据
with open(jsonl_filename, 'r') as jsonl_file:
# 创建 CSV 文件来存储解析的数据
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) # 解析每一行的 JSON 数据
metadata = data.get('metadata', {})
# 将 metadata 的值提取并写入 CSV 文件
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):
# 获取目录下所有 .zst 文件
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')
# 解压 .zst 文件
print(f"Decompressing {zst_filepath}...")
decompress_zst_file(zst_filepath, jsonl_filename)
# 提取 metadata 并保存到 CSV
print(f"Extracting metadata from {jsonl_filename} and saving to {csv_filename}...")
extract_metadata_from_jsonl(jsonl_filename, csv_filename)
# 删除解压后的 .jsonl 文件(可选)
os.remove(jsonl_filename)
done_file.append(filename)
print("done_file = ", done_file)
if __name__ == '__main__':
# 设置您的 .zst 文件目录路径
input_directory = 'my_data/peS2o_v3/data/v3'
# 设置您想要保存 CSV 文件的输出目录路径
output_directory = 'my_data/peS2o_v3/data/metadata'
# 确保输出目录存在
if not os.path.exists(output_directory):
os.makedirs(output_directory)
# 处理目录中的所有 .zst 文件
process_zst_files(input_directory, output_directory)