m8than commited on
Commit
313a961
1 Parent(s): b1421d2

scripts/readme

Browse files
Files changed (3) hide show
  1. README.md +6 -1
  2. filter.py +129 -0
  3. process_metadata_PDFs.py +321 -0
README.md CHANGED
@@ -36,7 +36,7 @@ pretty_name: ArXiv-CC0
36
  ### Dataset Description
37
 
38
  *ArXiv CC0* is a cleaned dataset of a raw scrape of arXiv using the latest metadata from January 2024.
39
- Filtering to a total amount of tokens of **~-B** (llama-2-7b-chat-tokenizer) / **~-B** (RWKV Tokenizer) from primarily English language.
40
 
41
  - **Curated by:** M8than
42
  - **Funded by [optional]:** Recursal.ai
@@ -53,6 +53,11 @@ Filtering to a total amount of tokens of **~-B** (llama-2-7b-chat-tokenizer) / *
53
 
54
  The entries are filtered down to CC0 only, so these are all public domain. The PDF's have their text pulled from them (not via OCR, the text is embedded). The documents are then run through a filtering and text transformation process within our pipeline to produce readable outputs, filtering out excessive newlines or spaces and also converting to markdown.
55
 
 
 
 
 
 
56
  ### Data Splits
57
 
58
  - final
 
36
  ### Dataset Description
37
 
38
  *ArXiv CC0* is a cleaned dataset of a raw scrape of arXiv using the latest metadata from January 2024.
39
+ Filtering to a total amount of tokens of **~2.77B** (llama-2-7b-chat-tokenizer) / **~2.43B** (RWKV Tokenizer) from primarily English language.
40
 
41
  - **Curated by:** M8than
42
  - **Funded by [optional]:** Recursal.ai
 
53
 
54
  The entries are filtered down to CC0 only, so these are all public domain. The PDF's have their text pulled from them (not via OCR, the text is embedded). The documents are then run through a filtering and text transformation process within our pipeline to produce readable outputs, filtering out excessive newlines or spaces and also converting to markdown.
55
 
56
+ #### How to run the scripts:
57
+ - Download the metadata json file from kaggle
58
+ - Run process_metadata_PDFs.py (after adjusting the variables at the top)
59
+ - Run filter.py (after adjusting the variables at the top)
60
+
61
  ### Data Splits
62
 
63
  - final
filter.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+
5
+ dir_in = "raw_jsonl"
6
+ dir_out = "jsonl"
7
+
8
+ def remove_single_newlines_with_space(text):
9
+ new_text = []
10
+ i = 0
11
+
12
+ def is_valid_char(c):
13
+ # Check if the character is a letter, space, quote or closing parenthesis
14
+ return c.isalpha() or c in {' ', '"', "'", ')', ']', '(' , '[', '-', ',', '.', '!', '?', ';', ':'} or c.isdigit()
15
+
16
+ while i < len(text):
17
+ if i > 0 and i < len(text) - 1 and text[i] == '\n':
18
+ # Check if the characters before and after the newline are valid
19
+ if is_valid_char(text[i-1]) and is_valid_char(text[i+1]):
20
+ new_text.append(' ') # Add a space instead of the newline
21
+ i += 1
22
+ continue
23
+ new_text.append(text[i])
24
+ i += 1
25
+
26
+ return ''.join(new_text)
27
+
28
+ char_count_per_chunk = 10737418240
29
+ cur_dir = os.path.dirname(os.path.realpath(__file__))
30
+
31
+ allowed_licenses = [
32
+ "https://creativecommons.org/share-your-work/public-domain/cc0/",
33
+ "http://creativecommons.org/share-your-work/public-domain/cc0/",
34
+ "http://creativecommons.org/publicdomain/zero/1.0/",
35
+ "http://creativecommons.org/licenses/publicdomain/",
36
+ ]
37
+
38
+ disallowed_licenses = [
39
+ "https://creativecommons.org/licenses/by/4.0/",
40
+ "http://creativecommons.org/licenses/by/4.0/",
41
+ "http://creativecommons.org/licenses/by/3.0/",
42
+
43
+
44
+ "https://creativecommons.org/licenses/by-sa/4.0/",
45
+ "http://creativecommons.org/licenses/by-sa/4.0/",
46
+
47
+ "https://creativecommons.org/licenses/by-nc-sa/4.0/",
48
+ "http://creativecommons.org/licenses/by-nc-sa/4.0/",
49
+ "http://creativecommons.org/licenses/by-nc-sa/3.0/",
50
+
51
+ "https://creativecommons.org/licenses/by-nc/4.0/",
52
+ "http://creativecommons.org/licenses/by-nc/4.0/",
53
+
54
+ "https://creativecommons.org/licenses/by-nc-nd/4.0/",
55
+ "http://creativecommons.org/licenses/by-nc-nd/4.0/",
56
+
57
+ "https://arxiv.org/licenses/nonexclusive-distrib/1.0/",
58
+ "http://arxiv.org/licenses/nonexclusive-distrib/1.0/",
59
+ ]
60
+
61
+ # generate a list of file paths from raw_jsonl
62
+ file_paths = os.listdir(cur_dir + '/' + dir_in)
63
+
64
+ # sort file paths in alphanumeric order
65
+ def alphanumeric_sort(file_paths):
66
+ # Function to convert text to integer if possible
67
+ convert = lambda text: int(text) if text.isdigit() else text.lower()
68
+ # Function to split the file path into parts and convert numbers
69
+ alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
70
+ # Sort the list with the custom key
71
+ return sorted(file_paths, key=alphanum_key)
72
+
73
+ file_paths = alphanumeric_sort(file_paths)
74
+
75
+ file_paths = [cur_dir + f'/{dir_in}/' + file for file in file_paths]
76
+
77
+
78
+ buffer = []
79
+ current_char_count = 0
80
+ chunk_id = 0
81
+ # loop through each file path building up the buffer till its over the char count
82
+ print("Processing files...")
83
+ line_count = 0
84
+ for file in file_paths:
85
+ print("Processing file " + file + "...")
86
+ with open(file) as f:
87
+ for line in f.readlines():
88
+ line_json = json.loads(line)
89
+ if line_json['license'] == None:
90
+ continue
91
+ elif line_json['license'] not in allowed_licenses:
92
+ if line_json['license'] not in disallowed_licenses:
93
+ # log the license
94
+ print("License not in allowed licenses or disallowed licenses: " + line_json['license'])
95
+ continue
96
+
97
+
98
+ current_char_count += len(line)
99
+
100
+ # filter line text here
101
+
102
+ line_json['text'] = line_json['text'].replace('\\"', '')
103
+ line_json['text'] = line_json['text'].replace('\"', '')
104
+ line_json['text'] = line_json['text'].replace('\\', '')
105
+ line_json['text'] = line_json['text'].replace('\f', '')
106
+ line_json['text'] = remove_single_newlines_with_space(line_json['text'])
107
+
108
+ buffer.append(line_json)
109
+ line_count += 1
110
+
111
+ if current_char_count > char_count_per_chunk:
112
+ # write buffer to file
113
+ with open(cur_dir + f'/{dir_out}/' + "arxiv_" + str(chunk_id) + ".jsonl", 'w') as f:
114
+ for line in buffer:
115
+ f.write(json.dumps(line) + '\n')
116
+
117
+ # reset buffer and char count
118
+ buffer = []
119
+ current_char_count = 0
120
+ chunk_id += 1
121
+
122
+ if line_count % 1000 == 0:
123
+ print("Found " + str(line_count) + " copyright-free lines...")
124
+
125
+
126
+
127
+ with open(cur_dir + f'/{dir_out}/' + "arxiv_" + str(chunk_id) + ".jsonl", 'w') as f:
128
+ for line in buffer:
129
+ f.write(json.dumps(line) + '\n')
process_metadata_PDFs.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dir = "20-Jan-2024"
2
+ chunk_doc_size = 100000
3
+ remove_every_word_over_x_characters = 16
4
+ ignore_first_page = True
5
+ ignore_last_page = True
6
+ max_processes = 12
7
+ attempt_resume = True
8
+ remove_false_newlines = True
9
+
10
+ import re
11
+ import requests
12
+ import threading
13
+ import PyPDF2
14
+ from io import BytesIO
15
+ import time
16
+
17
+ def remove_single_newlines_with_space(text):
18
+ new_text = []
19
+ i = 0
20
+
21
+ def is_valid_char(c):
22
+ # Check if the character is a letter, space, quote or closing parenthesis
23
+ return c.isalpha() or c in {' ', '"', "'", ')', ']', '(' , '[', '-', ',', '.', '!', '?', ';', ':'} or c.isdigit()
24
+
25
+ while i < len(text):
26
+ if i > 0 and i < len(text) - 1 and text[i] == '\n':
27
+ # Check if the characters before and after the newline are valid
28
+ if is_valid_char(text[i-1]) and is_valid_char(text[i+1]):
29
+ new_text.append(' ') # Add a space instead of the newline
30
+ i += 1
31
+ continue
32
+ new_text.append(text[i])
33
+ i += 1
34
+
35
+ return ''.join(new_text)
36
+
37
+ def extract_text_from_pdf_url(pdf_url):
38
+ # Send a GET request to the URL
39
+ response = requests.get(pdf_url)
40
+
41
+ # Check if the request was successful
42
+ if response.status_code == 200:
43
+ # Read the PDF file from the response
44
+ file = BytesIO(response.content)
45
+
46
+ # Create a PDF reader object
47
+ reader = PyPDF2.PdfReader(file)
48
+
49
+ # Initialize a variable to store extracted text
50
+ text = ""
51
+
52
+ # Loop through each page in the PDF
53
+ for page in range(len(reader.pages)):
54
+ if page == 0 and ignore_first_page:
55
+ continue
56
+
57
+ if page == len(reader.pages) - 1 and ignore_last_page:
58
+ continue
59
+
60
+ # Get a specific page
61
+ pdf_page = reader.pages[page]
62
+
63
+ # Extract text from the page
64
+ text += pdf_page.extract_text()
65
+
66
+ return text
67
+ else:
68
+ return ""
69
+
70
+
71
+ # read json file
72
+ import json
73
+
74
+ print("Loading arxiv metadata")
75
+
76
+ file = open(f"{dir}/arxiv-metadata-oai-snapshot.json", "r")
77
+ # read it line by line because its a jsonl
78
+ data = []
79
+ for line in file.readlines():
80
+ # load the json
81
+ data.append(json.loads(line))
82
+ file.close()
83
+
84
+ print(f"Loaded {len(data)} documents from metadata")
85
+
86
+
87
+ to_skip = 0
88
+ chunk = 0
89
+ count = 0
90
+
91
+ print("Reading previous data to resume progress")
92
+
93
+ if attempt_resume:
94
+ # count how many lines in jsonl folder
95
+ import os
96
+ for filename in os.listdir('jsonl'):
97
+ if filename.endswith(".jsonl"):
98
+ chunk += 1
99
+ count += sum(1 for line in open(f'jsonl/{filename}', 'r'))
100
+ count -= 1 # remove the last line because it is empty
101
+
102
+ # count how many lines in failed.txt
103
+ count += sum(1 for line in open('failed.txt', 'r'))
104
+
105
+ # count how many lines in failed.jsonl
106
+ count += sum(1 for line in open('failed.jsonl', 'r'))
107
+
108
+
109
+ count -= 2 # remove the last lines because it is empty
110
+ chunk -= 1
111
+ to_skip = count
112
+
113
+ print(f"Skipping {to_skip} documents (to resume progress)")
114
+
115
+ # # id: ArXiv ID (can be used to access the paper, see below)
116
+ # # submitter: Who submitted the paper
117
+ # # authors: Authors of the paper
118
+ # # title: Title of the paper
119
+ # # comments: Additional info, such as number of pages and figures
120
+ # # journal-ref: Information about the journal the paper was published in
121
+ # # doi: [https://www.doi.org](Digital Object Identifier)
122
+ # # abstract: The abstract of the paper
123
+ # # categories: Categories / tags in the ArXiv system
124
+ # # versions: A version history
125
+ # with open(f'jsonl/arxiv_{chunk}.jsonl', 'w') as f:
126
+ # for i in range(len(data)):
127
+ # print(f"Processing {i} of {len(data)}")
128
+ # row = data[i]
129
+
130
+
131
+
132
+ # # extract text from pdf file
133
+ # text = extract_text_from_pdf_url("https://arxiv.org/pdf/" + row['id'])
134
+
135
+ # if text == "":
136
+ # with open(f'failed.txt') as w:
137
+ # w.write(row['id'] + '\n')
138
+
139
+ # f.write(json.dumps({"text": text.encode('utf-8').decode('unicode_escape')} + row) + '\n')
140
+ # if count % 100000 == 0:
141
+ # print(text)
142
+ # count+=1
143
+ # if count % chunk_doc_size == 0:
144
+ # f.close()
145
+ # chunk += 1
146
+ # f = open(f'jsonl/arxiv_{chunk}.jsonl', 'w')
147
+
148
+ import threading
149
+ import json
150
+ from unidecode import unidecode
151
+ import multiprocessing
152
+
153
+ def filter_text(text):
154
+ final_text = text.encode('utf-8', errors='replace').decode('unicode_escape', errors='ignore')
155
+ final_text = re.sub(r'\\U[\da-fA-F]{8}', '', final_text)
156
+
157
+ # remove_every_word_over_x_characters
158
+ words = final_text.split(' ')
159
+ for word in words:
160
+ if len(word) > remove_every_word_over_x_characters:
161
+ final_text = final_text.replace(word, '')
162
+ if word.count('\\') > len(word) * 0.25:
163
+ final_text = final_text.replace(word, '')
164
+
165
+
166
+ # remove_false_newlines
167
+ if remove_false_newlines:
168
+ final_text = remove_single_newlines_with_space(final_text)
169
+
170
+
171
+ final_text = final_text.replace('\\"', '')
172
+ final_text = final_text.replace('\"', '')
173
+ final_text = final_text.replace('\\', '')
174
+ final_text = final_text.replace('\f', '')
175
+ return final_text
176
+
177
+
178
+ def extract_text_process(row):
179
+ text = extract_text_from_pdf_url("https://arxiv.org/pdf/" + row['id'])
180
+
181
+
182
+ return filter_text(text)
183
+
184
+ def extract_text_process_safe(row):
185
+ try:
186
+ return extract_text_process(row)
187
+ except Exception as e:
188
+ print(e)
189
+ return ""
190
+
191
+
192
+ from queue import Empty
193
+ def process_queue(queue, count, chunk, chunk_doc_size, stop_event):
194
+ output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'a')
195
+ failed_file = open('failed.jsonl', 'a')
196
+
197
+ print("Starting queue process")
198
+ print(stop_event.is_set())
199
+
200
+ while not stop_event.is_set():
201
+ while not queue.empty():
202
+ try:
203
+ row, text = queue.get(timeout=0.5) # Timeout to check for stop event
204
+ except Empty as e:
205
+ print(e)
206
+ continue
207
+ print("Looping queue process " + str(chunk) + " " + str(queue.qsize()))
208
+
209
+ row['title'] = filter_text(row['title'])
210
+ row['abstract'] = filter_text(row['abstract'])
211
+
212
+ if len(text) < 1000:
213
+ failed_file.write(json.dumps(row) + '\n')
214
+ else:
215
+ output_file.write(json.dumps({**{"text": text}, **row}) + '\n')
216
+
217
+ count += 1
218
+ if count % chunk_doc_size == 0:
219
+ output_file.close()
220
+ chunk += 1
221
+ output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'w')
222
+ time.sleep(0.005) # Sleep
223
+ time.sleep(0.005) # Sleep
224
+
225
+ output_file.close()
226
+ failed_file.close()
227
+
228
+ def process_worker(queue, count, chunk, chunk_doc_size, stop_event):
229
+ try:
230
+ process_queue(queue, count, chunk, chunk_doc_size, stop_event)
231
+ except Exception as e:
232
+ print(f"Error in worker process: {e}")
233
+ # exit whole app
234
+ os._exit(1)
235
+
236
+ def worker(i, row, queue):
237
+ try:
238
+ text = extract_text_process_safe(row)
239
+ queue.put((row, text))
240
+ print(f"Processed {i} of {len(data)}") # Adjust this line as needed
241
+ except Exception as e:
242
+ print(f"Error in worker process: {e}")
243
+ time.sleep(0.5) # Sleep to avoid spamming requests
244
+
245
+
246
+ from concurrent.futures import ThreadPoolExecutor
247
+
248
+ def process_data(data, chunk_doc_size):
249
+ global to_skip, count, chunk
250
+ queue = multiprocessing.Manager().Queue()
251
+ stop_event = multiprocessing.Event()
252
+
253
+ stop_event.clear()
254
+
255
+ # Start the thread for processing the queue
256
+ queue_process = multiprocessing.Process(target=process_worker, args=(queue, count, chunk, chunk_doc_size, stop_event))
257
+ queue_process.start()
258
+
259
+ # Create a pool of worker threads
260
+ # with ThreadPoolExecutor(max_workers=max_processes) as executor:
261
+ # for i, row in enumerate(data):
262
+ # if i < to_skip:
263
+ # continue
264
+
265
+ # executor.submit(worker, i, row, queue)
266
+ # time.sleep(0.0001)
267
+
268
+ # Create a pool of worker processes
269
+ with multiprocessing.Pool(max_processes) as pool:
270
+ for i, row in enumerate(data):
271
+ if i < to_skip:
272
+ continue
273
+
274
+ pool.apply_async(worker, args=(i, row, queue))
275
+ time.sleep(0.0001)
276
+
277
+ # Close the pool and wait for the work to finish
278
+ pool.close()
279
+ pool.join()
280
+
281
+ # Signal the queue processing thread to stop and wait for it to finish
282
+ stop_event.set()
283
+ queue_process.join()
284
+
285
+ # output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'a')
286
+ # failed_file = open('failed.txt', 'a')
287
+
288
+ # def process_results(result):
289
+ # global count, chunk, failed_file, output_file, chunk_doc_size
290
+ # row, text = result
291
+ # if text == "":
292
+ # failed_file.write(row['id'] + '\n')
293
+ # else:
294
+ # output_file.write(json.dumps({**{"text": text}, **row}) + '\n')
295
+
296
+ # if count % 100 == 0:
297
+ # print(f"Processed {count} of {len(data)}")
298
+
299
+ # count += 1
300
+
301
+ # if count % chunk_doc_size == 0:
302
+ # output_file.close()
303
+ # chunk += 1
304
+ # output_file = open(f'jsonl/arxiv_{chunk}.jsonl', 'w')
305
+
306
+
307
+
308
+ # def process_data(data, chunk_doc_size, pool_size=20):
309
+ # global output_file, failed_file
310
+
311
+ # with multiprocessing.Pool(pool_size) as pool:
312
+ # results = [pool.apply_async(extract_text_process, args=(data[i],), callback=lambda res: process_results(res)) for i in range(to_skip, len(data))]
313
+
314
+ # for result in results:
315
+ # result.wait()
316
+
317
+ # failed_file.close()
318
+ # output_file.close()
319
+
320
+ # Example usage
321
+ process_data(data, chunk_doc_size)