|
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): |
|
|
|
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': |
|
|
|
if is_valid_char(text[i-1]) and is_valid_char(text[i+1]): |
|
new_text.append(' ') |
|
i += 1 |
|
continue |
|
new_text.append(text[i]) |
|
i += 1 |
|
|
|
return ''.join(new_text) |
|
|
|
def extract_text_from_pdf_url(pdf_url): |
|
|
|
response = requests.get(pdf_url) |
|
|
|
|
|
if response.status_code == 200: |
|
|
|
file = BytesIO(response.content) |
|
|
|
|
|
reader = PyPDF2.PdfReader(file) |
|
|
|
|
|
text = "" |
|
|
|
|
|
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 |
|
|
|
|
|
pdf_page = reader.pages[page] |
|
|
|
|
|
text += pdf_page.extract_text() |
|
|
|
return text |
|
else: |
|
return "" |
|
|
|
|
|
|
|
import json |
|
|
|
print("Loading arxiv metadata") |
|
|
|
file = open(f"{dir}/arxiv-metadata-oai-snapshot.json", "r") |
|
|
|
data = [] |
|
for line in file.readlines(): |
|
|
|
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: |
|
|
|
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 |
|
|
|
|
|
count += sum(1 for line in open('failed.txt', 'r')) |
|
|
|
|
|
count += sum(1 for line in open('failed.jsonl', 'r')) |
|
|
|
|
|
count -= 2 |
|
chunk -= 1 |
|
to_skip = count |
|
|
|
print(f"Skipping {to_skip} documents (to resume progress)") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
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, '') |
|
|
|
|
|
|
|
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) |
|
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) |
|
time.sleep(0.005) |
|
|
|
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}") |
|
|
|
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)}") |
|
except Exception as e: |
|
print(f"Error in worker process: {e}") |
|
time.sleep(0.5) |
|
|
|
|
|
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() |
|
|
|
|
|
queue_process = multiprocessing.Process(target=process_worker, args=(queue, count, chunk, chunk_doc_size, stop_event)) |
|
queue_process.start() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
pool.close() |
|
pool.join() |
|
|
|
|
|
stop_event.set() |
|
queue_process.join() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
process_data(data, chunk_doc_size) |
|
|