arXiv-CC0-v0.5 / process_metadata_PDFs.py
m8than's picture
scripts/readme
313a961
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)