File size: 9,844 Bytes
313a961
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
dir = "20-Jan-2024"
chunk_doc_size = 100000
remove_every_word_over_x_characters = 16
ignore_first_page = True
ignore_last_page = True
max_processes = 12
attempt_resume = True
remove_false_newlines = True

import re
import requests
import threading
import PyPDF2
from io import BytesIO
import time

def remove_single_newlines_with_space(text):
    new_text = []
    i = 0

    def is_valid_char(c):
        # Check if the character is a letter, space, quote or closing parenthesis
        return c.isalpha() or c in {' ', '"', "'", ')', ']', '(' , '[', '-', ',', '.', '!', '?', ';', ':'} or c.isdigit()

    while i < len(text):
        if i > 0 and i < len(text) - 1 and text[i] == '\n':
            # Check if the characters before and after the newline are valid
            if is_valid_char(text[i-1]) and is_valid_char(text[i+1]):
                new_text.append(' ')  # Add a space instead of the newline
                i += 1
                continue
        new_text.append(text[i])
        i += 1

    return ''.join(new_text)

def extract_text_from_pdf_url(pdf_url):
    # Send a GET request to the URL
    response = requests.get(pdf_url)
    
    # Check if the request was successful
    if response.status_code == 200:
        # Read the PDF file from the response
        file = BytesIO(response.content)
        
        # Create a PDF reader object
        reader = PyPDF2.PdfReader(file)
        
        # Initialize a variable to store extracted text
        text = ""
        
        # Loop through each page in the PDF
        for page in range(len(reader.pages)):
            if page == 0 and ignore_first_page:
                continue
            
            if page == len(reader.pages) - 1 and ignore_last_page:
                continue

            # Get a specific page
            pdf_page = reader.pages[page]
            
            # Extract text from the page
            text += pdf_page.extract_text()
        
        return text
    else:
        return ""


# read json file
import json

print("Loading arxiv metadata")

file = open(f"{dir}/arxiv-metadata-oai-snapshot.json", "r")
# read it line by line because its a jsonl
data = []
for line in file.readlines():
    # load the json
    data.append(json.loads(line))
file.close()

print(f"Loaded {len(data)} documents from metadata")


to_skip = 0
chunk = 0
count = 0

print("Reading previous data to resume progress")

if attempt_resume:
    # count how many lines in jsonl folder
    import os
    for filename in os.listdir('jsonl'):
        if filename.endswith(".jsonl"):
            chunk += 1
            count += sum(1 for line in open(f'jsonl/{filename}', 'r'))
            count -= 1 # remove the last line because it is empty
            
    # count how many lines in failed.txt
    count += sum(1 for line in open('failed.txt', 'r'))
    
    # count how many lines in failed.jsonl
    count += sum(1 for line in open('failed.jsonl', 'r'))
    
    
    count -= 2 # remove the last lines because it is empty
    chunk -= 1
    to_skip = count
    
print(f"Skipping {to_skip} documents (to resume progress)")

# # id: ArXiv ID (can be used to access the paper, see below)
# # submitter: Who submitted the paper
# # authors: Authors of the paper
# # title: Title of the paper
# # comments: Additional info, such as number of pages and figures
# # journal-ref: Information about the journal the paper was published in
# # doi: [https://www.doi.org](Digital Object Identifier)
# # abstract: The abstract of the paper
# # categories: Categories / tags in the ArXiv system
# # versions: A version history
# with open(f'jsonl/arxiv_{chunk}.jsonl', 'w') as f:
#     for i in range(len(data)):
#         print(f"Processing {i} of {len(data)}")
#         row = data[i]

        
        
#         # extract text from pdf file
#         text = extract_text_from_pdf_url("https://arxiv.org/pdf/" + row['id'])

#         if text == "":
#             with open(f'failed.txt') as w:
#                 w.write(row['id'] + '\n')

#         f.write(json.dumps({"text": text.encode('utf-8').decode('unicode_escape')} + row) + '\n')
#         if count % 100000 == 0:
#             print(text)
#         count+=1
#         if count % chunk_doc_size == 0:
#             f.close()
#             chunk += 1
#             f = open(f'jsonl/arxiv_{chunk}.jsonl', 'w')

import threading
import json
from unidecode import unidecode
import multiprocessing

def filter_text(text):
    final_text = text.encode('utf-8', errors='replace').decode('unicode_escape', errors='ignore')
    final_text = re.sub(r'\\U[\da-fA-F]{8}', '', final_text)

    # remove_every_word_over_x_characters
    words = final_text.split(' ')
    for word in words:
        if len(word) > remove_every_word_over_x_characters:
            final_text = final_text.replace(word, '')
        if word.count('\\') > len(word) * 0.25:
            final_text = final_text.replace(word, '')
            
            
    # remove_false_newlines
    if remove_false_newlines:
        final_text = remove_single_newlines_with_space(final_text)
        
        
    final_text = final_text.replace('\\"', '')
    final_text = final_text.replace('\"', '')
    final_text = final_text.replace('\\', '')
    final_text = final_text.replace('\f', '')
    return final_text
    

def extract_text_process(row):
    text = extract_text_from_pdf_url("https://arxiv.org/pdf/" + row['id'])

            
    return filter_text(text)
    
def extract_text_process_safe(row):
    try:
        return extract_text_process(row)
    except Exception as e:
        print(e)
        return "" 


from queue import Empty
def process_queue(queue, count, chunk, chunk_doc_size, stop_event):
    output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'a')
    failed_file = open('failed.jsonl', 'a')
    
    print("Starting queue process")
    print(stop_event.is_set())
    
    while not stop_event.is_set():
        while not queue.empty():
            try:
                row, text = queue.get(timeout=0.5)  # Timeout to check for stop event
            except Empty as e:
                print(e)
                continue
            print("Looping queue process " + str(chunk) + "  " + str(queue.qsize()))

            row['title'] = filter_text(row['title'])
            row['abstract'] = filter_text(row['abstract'])
            
            if len(text) < 1000:
                failed_file.write(json.dumps(row) + '\n')
            else:
                output_file.write(json.dumps({**{"text": text}, **row}) + '\n')
            
            count += 1
            if count % chunk_doc_size == 0:
                output_file.close()
                chunk += 1
                output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'w')
            time.sleep(0.005)  # Sleep 
        time.sleep(0.005)  # Sleep 

    output_file.close()
    failed_file.close()

def process_worker(queue, count, chunk, chunk_doc_size, stop_event):
    try:
        process_queue(queue, count, chunk, chunk_doc_size, stop_event)
    except Exception as e:
        print(f"Error in worker process: {e}")
        # exit whole app
        os._exit(1)
        
def worker(i, row, queue):
    try:
        text = extract_text_process_safe(row) 
        queue.put((row, text))
        print(f"Processed {i} of {len(data)}") # Adjust this line as needed
    except Exception as e:
        print(f"Error in worker process: {e}")
    time.sleep(0.5)  # Sleep to avoid spamming requests

    
from concurrent.futures import ThreadPoolExecutor

def process_data(data, chunk_doc_size):
    global to_skip, count, chunk
    queue = multiprocessing.Manager().Queue()
    stop_event = multiprocessing.Event()
    
    stop_event.clear()

    # Start the thread for processing the queue
    queue_process = multiprocessing.Process(target=process_worker, args=(queue, count, chunk, chunk_doc_size, stop_event))
    queue_process.start()

    # Create a pool of worker threads
    # with ThreadPoolExecutor(max_workers=max_processes) as executor:
    #     for i, row in enumerate(data):
    #         if i < to_skip:
    #             continue

    #         executor.submit(worker, i, row, queue)
    #         time.sleep(0.0001)

    # Create a pool of worker processes
    with multiprocessing.Pool(max_processes) as pool:
        for i, row in enumerate(data):
            if i < to_skip:
                continue

            pool.apply_async(worker, args=(i, row, queue))
            time.sleep(0.0001)

        # Close the pool and wait for the work to finish
        pool.close()
        pool.join()

    # Signal the queue processing thread to stop and wait for it to finish
    stop_event.set()
    queue_process.join()

# output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'a')
# failed_file = open('failed.txt', 'a')

# def process_results(result):
#     global count, chunk, failed_file, output_file, chunk_doc_size
#     row, text = result
#     if text == "":
#         failed_file.write(row['id'] + '\n')
#     else:
#         output_file.write(json.dumps({**{"text": text}, **row}) + '\n')
        
#     if count % 100 == 0:
#         print(f"Processed {count} of {len(data)}")

#     count += 1
        
#     if count % chunk_doc_size == 0:
#         output_file.close()
#         chunk += 1
#         output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'w')
        
    

# def process_data(data, chunk_doc_size, pool_size=20):
#     global output_file, failed_file

#     with multiprocessing.Pool(pool_size) as pool:
#         results = [pool.apply_async(extract_text_process, args=(data[i],), callback=lambda res: process_results(res)) for i in range(to_skip, len(data))]

#         for result in results:
#             result.wait()

#     failed_file.close()
#     output_file.close()

# Example usage
process_data(data, chunk_doc_size)