ClinicalTrials.gov / processing.py
shuyuej's picture
Upload 2 files
c314bed verified
Raw
History Blame Contribute Delete
5.42 kB
import os
import json
import re
from langchain.text_splitter import RecursiveCharacterTextSplitter
import copy
def create_folder(folder_path):
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print(f"Folder '{folder_path}' created successfully.")
def shorten_filename(title, max_length=100):
"""Shorten a filename if it exceeds max_length by appending a hash."""
if len(title) > max_length:
title = title[:max_length - 9] # Truncate and add hash
return title
def ends_with_ending_punctuation(s):
ending_punctuation = ('.', '?', '!')
return any(s.endswith(char) for char in ending_punctuation)
def concat(title, content):
if ends_with_ending_punctuation(title.strip()):
return title.strip() + " " + content.strip()
else:
return title.strip() + ". " + content.strip()
def add_space_before_uppercase(text):
"""Add a space before each uppercase letter, except the first one."""
return re.sub(r'([a-z])([A-Z])', r'\1 \2', text)
def add_punctuation(text):
"""Ensure sentences and phrases end properly without adding unnecessary punctuation."""
text = text.strip()
if text.endswith((',', '.')):
return text # If it already ends with a period or comma, don't add another one
return text + '.'
def find_brief_title(d):
if isinstance(d, dict):
# If the key exists at the current level
if 'briefTitle' in d:
return d['briefTitle']
# Recursively search in the dictionary's values
for key, value in d.items():
result = find_brief_title(value)
if result:
return result
elif isinstance(d, list):
# If the value is a list, search in each item
for item in d:
result = find_brief_title(item)
if result:
return result
print("Didn't find the title!")
return None # Return None if not found
def json_to_sentence(json_data, level=0):
"""Convert JSON data to a meaningful sentence with proper handling of nested structures."""
if isinstance(json_data, dict):
sentence_parts = []
for key, value in json_data.items():
key = add_space_before_uppercase(key)
key_formatted = key.replace('_', ' ').capitalize()
if isinstance(value, (str, int, float, bool)):
sentence_parts.append(add_punctuation(f"{key_formatted} is {value}"))
elif isinstance(value, list):
list_items = ', '.join(
json_to_sentence(item, level + 1) if isinstance(item, dict) else str(item)
for item in value
)
sentence_parts.append(add_punctuation(f"{key_formatted} includes {list_items}"))
elif isinstance(value, dict):
sentence_parts.append(add_punctuation(f"{key_formatted} details: {json_to_sentence(value, level + 1)}"))
return ' '.join(sentence_parts)
elif isinstance(json_data, list):
return ', '.join(json_to_sentence(item, level + 1) for item in json_data)
return str(json_data)
def clean_text(text):
"""Remove extra spaces, newline characters, and fix redundant punctuation."""
text = re.sub(r'\s+', ' ', text) # Replace multiple spaces/newlines with a single space
text = re.sub(r'\.,', ',', text) # Remove redundant ".,"
text = re.sub(r'\.(?=\.)', '', text) # Remove extra periods (e.g., "...")
text = re.sub(r',\.', '.', text) # Fix ",."
return text.strip() # Remove leading/trailing spaces
import os
import json
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
# Specify the directory containing the JSON files
folder_path = 'ctg-studies-json'
# Get a list of all files in the folder
files = os.listdir(folder_path)
# Filter only JSON files
json_files = [f for f in files if f.endswith('.json')]
# Loop through each JSON file and read its contents
for json_file in json_files:
json_file_path = os.path.join(folder_path, json_file)
print(json_file_path)
file_name = os.path.basename(json_file_path)
# Open and read the JSON file
with open(json_file_path, 'r') as file:
data = json.load(file)
# if data["hasResults"] == True:
formatted_text = json_to_sentence(data)
if formatted_text is not None:
cleaned_text = clean_text(formatted_text)
title = find_brief_title(data)
if title is not None:
title = title.replace("/", " ").replace(":", " ")
title = shorten_filename(title)
title = re.sub(r'\s+', ' ', title).strip()
chunk_texts = text_splitter.split_text(cleaned_text)
saved_text = [
json.dumps(
{
"id": '_'.join([file_name.replace(".json", ""), str(i)]),
"title": title,
"content": re.sub("\s+", " ", chunk_texts[i]),
"contents": concat(title, re.sub("\s+", " ", chunk_texts[i])),
}, ensure_ascii=False
) for i in range(len(chunk_texts))
]
new_folder_path = "new_chunk"
create_folder(folder_path=new_folder_path)
with open(new_folder_path + "/{:s}".format(file_name.replace(".json", ".jsonl")), 'w') as f:
f.write('\n'.join(saved_text))