| 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] |
| 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 |
| return text + '.' |
|
|
|
|
| def find_brief_title(d): |
| if isinstance(d, dict): |
| |
| if 'briefTitle' in d: |
| return d['briefTitle'] |
|
|
| |
| for key, value in d.items(): |
| result = find_brief_title(value) |
| if result: |
| return result |
|
|
| elif isinstance(d, list): |
| |
| for item in d: |
| result = find_brief_title(item) |
| if result: |
| return result |
| print("Didn't find the title!") |
| return None |
|
|
|
|
| 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) |
| text = re.sub(r'\.,', ',', text) |
| text = re.sub(r'\.(?=\.)', '', text) |
| text = re.sub(r',\.', '.', text) |
| return text.strip() |
|
|
|
|
| import os |
| import json |
|
|
| text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) |
|
|
| |
| folder_path = 'ctg-studies-json' |
|
|
| |
| files = os.listdir(folder_path) |
|
|
| |
| json_files = [f for f in files if f.endswith('.json')] |
|
|
| |
| 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) |
|
|
| |
| with open(json_file_path, 'r') as file: |
| data = json.load(file) |
|
|
| |
| 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)) |
|
|