File size: 5,417 Bytes
c314bed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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))