intermine / json_gz2nt_gz.py
fbelleau's picture
Create json_gz2nt_gz.py
d498a53 verified
raw
history blame contribute delete
No virus
4.78 kB
# json_gz2nt_gz.py
import json
import gzip
import sys
from datetime import datetime
# Define the filename of the gzipped file (replace with your actual path)
def read_gz_by_row(FILENAME):
try:
# Open the file in 'rb' (read binary) mode with gzip decompression
with gzip.open(FILENAME, 'rb') as f:
# Iterate through each line in the file
for line in f:
# Decode the line from bytes to string (adjust encoding if needed)
decoded_line = line.decode('utf-8')
yield decoded_line.strip()
# Process the decoded line as needed
print(decoded_line.rstrip()) # Print the line with trailing whitespace removed
except FileNotFoundError:
print(f"Error: File '{FILENAME}' not found.")
def limit_string_size(text, max_size=1024, suffix="..."):
"""Limits the size of a string to a specified maximum, adding an optional suffix.
Args:
text: The string to limit.
max_size: The maximum allowed size (default: 1024 characters).
suffix: The suffix to add if the string is truncated (default: "...").
Returns:
The truncated string if it exceeds the limit, otherwise the original string.
"""
if len(text) > max_size:
# Truncate at the character boundary closest to max_size
truncated_text = text[:max_size - len(suffix)] # Exclude suffix length
return truncated_text + suffix # Add the suffix after truncation
else:
return text # Return original string if it's within the limit
def fix_string(string):
string = string.replace('\\','')
string = string.replace("'","")
string = string.replace('"','')
string = string.replace("\n",'')
string = limit_string_size(string)
return string
def object2nt(json_doc):
ntriples_str = ''
for key, value in json_doc.items():
#print(key, type(value), value)
if not value is None:
if isinstance(value, bool):
if value:
ntriple = f"<http://bio2rdf.org/{NAMESPACE}:{doc_id}> <http://bio2rdf.org/intermine_voc:{key}> true .\n"
else:
ntriple = f"<http://bio2rdf.org/{NAMESPACE}:{doc_id}> <http://bio2rdf.org/intermine_voc:{key}> false .\n"
elif isinstance(value, str):
value = fix_string(value)
ntriple = f"<http://bio2rdf.org/{NAMESPACE}:{doc_id}> <http://bio2rdf.org/intermine_voc:{key}> '{value}' .\n"
if key == 'class_name':
ntriple1 = f"<http://bio2rdf.org/{NAMESPACE}:{doc_id}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://bio2rdf.org/intermine_voc:{value}> .\n"
ntriple = ntriple1 + ntriple
else:
ntriple = f"<http://bio2rdf.org/{NAMESPACE}:{doc_id}> <http://bio2rdf.org/intermine_voc:{key}> {value} .\n"
#print(ntriple)
ntriples_str = ntriples_str + ntriple
return ntriples_str
def relation2nt(json_doc):
#print(json_doc, type(json_doc))
ntriple1 = f"<http://bio2rdf.org/{json_doc['namespace']}:{json_doc['class_name_from']}:{str(json_doc['id_from'])}> "
ntriple2 = f"<http://bio2rdf.org/intermine_voc:{json_doc['predicate'].replace('.id','_id')}> "
ntriple3 = f"<http://bio2rdf.org/{json_doc['namespace']}:{json_doc['class_name_to']}:{str(json_doc['id_to'])}> .\n"
ntriple = ntriple1 + ntriple2 + ntriple3
return ntriple
def ndjson2nt(TYPE, NAMESPACE, FOLDER):
file_nt_gz = gzip.open(f"{FOLDER}/{NAMESPACE}-{TYPE}.nt.gz2", "wb")
ctr = 0
str_len = 0
for json_str in read_gz_by_row(f"{FOLDER}/{NAMESPACE}-{TYPE}.ndjson.gz"):
ctr += 1
if ctr % 100000 == 0:
print(NAMESPACE, TYPE, datetime.utcnow().isoformat(), ctr, str_len)
json_dict = json.loads(json_str)
json_doc = json_dict['_source']
doc_id = json_doc['doc_id'].replace(NAMESPACE+'-','').replace('-',':')
#print(ctr, json_doc['class_name'], doc_id)
if TYPE == 'object':
ntriple_str = object2nt(json_doc)
else:
ntriple_str = relation2nt(json_doc)
str_len = str_len + len(ntriple_str)
file_nt_gz.write(ntriple_str.encode("utf-8"))
file_nt_gz.close()
print(NAMESPACE, TYPE, datetime.utcnow().isoformat(), ctr, str_len)
# python3 json_gz2nt_gz.py relation wormmine ../data
# python3 json_gz2nt_gz.py relation yeastmine ../data
NAMESPACE = 'flymine'
FOLDER = './'
# relation or object
TYPE = 'relation'
TYPE = 'object'
TYPE = sys.argv[1]
NAMESPACE = sys.argv[2]
FOLDER = sys.argv[3]
try:
ndjson2nt(TYPE, NAMESPACE, FOLDER)
except KeyboardInterrupt:
print("Stopping execution due to Ctrl+C...")