# 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" true .\n" else: ntriple = f" false .\n" elif isinstance(value, str): value = fix_string(value) ntriple = f" '{value}' .\n" if key == 'class_name': ntriple1 = f" .\n" ntriple = ntriple1 + ntriple else: ntriple = f" {value} .\n" #print(ntriple) ntriples_str = ntriples_str + ntriple return ntriples_str def relation2nt(json_doc): #print(json_doc, type(json_doc)) ntriple1 = f" " ntriple2 = f" " ntriple3 = f" .\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...")