paper-reading-assistant / pdf_preprocessing.py
yikic's picture
bug fixed
3d9d194
Raw History Blame Contribute Delete
6.8 kB
import re
from pathlib import Path
import pymupdf as PyMuPDF
import requests
def download_pdf_from_arxiv(arxiv_id):
if Path(f'arxiv_archive/{arxiv_id}.pdf').exists():
print(f"PDF for arXiv id {arxiv_id} already exists")
return
url = f'http://export.arxiv.org/pdf/{arxiv_id}'
response = requests.get(url)
if response.status_code == 200:
pdf_content = response.content
with open(f"arxiv_archive/{arxiv_id}.pdf", "wb") as f:
f.write(pdf_content)
else:
raise Exception(f"Failed to download pdf for arXiv id {arxiv_id}")
def extract_all_titles(pdf_path):
doc = PyMuPDF.open(pdf_path)
titles = []
should_break = False
for page_num in range(len(doc)):
if should_break:
break
page = doc.load_page(page_num)
blocks = page.get_text("dict")["blocks"]
page_titles = []
for block in blocks:
if 'image' in block:
continue
text = " ".join([span["text"] for line in block["lines"] for span in line["spans"]])
if_obvious_title, if_end = is_obvious_title(text)
if (if_obvious_title and title_len_constraint(text) and not if_double_space(text) and
not if_paper_header(text) and not is_formula(text) and not is_url(text)):
page_titles.append(text.strip())
if if_end:
should_break = True
break
titles += page_titles
return titles
def extract_bodies(pdf_path, all_chap_titles, all_titles):
doc = PyMuPDF.open(pdf_path)
bodies = []
is_body = False
chapter_body = []
should_break = False
for page_num in range(len(doc)):
if should_break:
break
page = doc.load_page(page_num)
blocks = page.get_text("dict")["blocks"]
for block in blocks:
if 'image' in block:
continue
text = " ".join([span["text"] for line in block["lines"] for span in line["spans"]])
if text in all_chap_titles:
if is_body:
bodies.append("\n".join(chapter_body))
chapter_body = []
if text == all_chap_titles[-1]:
should_break = True
break
is_body = True
if (is_body and is_body_text(text) and not is_table(text) and not is_image(text) and not is_formula(text)
and not is_url(text)) or text in all_titles:
chapter_body.append(text.strip())
return bodies
def extract_paper_title(pdf_path):
doc = PyMuPDF.open(pdf_path)
page = doc.load_page(0)
blocks = page.get_text("dict")["blocks"]
for block in blocks:
if 'image' in block:
continue
text = " ".join([span["text"] for line in block["lines"] for span in line["spans"]])
if (not is_body_text(text) and not is_table(text) and not is_image(text) and not is_formula(text)
and not is_url(text) and paper_title_len_constraint(text)):
return text.strip()
def select_chaptitle_from_alltitles(all_titles):
chap_titles = []
add = False
# extract intro pattern
for title in all_titles:
intro_pattern = check_intro_pattern(title)
if intro_pattern:
if intro_pattern == 2:
add = True
break
for title in all_titles:
if is_obvious_chapter_title(title, add):
chap_titles.append(title)
chap_titles.append(title)
return chap_titles
def is_obvious_title(text):
title_arabia_pattern = r'^\d[\.]?\d?[\.]?\s.+'
title_rome_pattern = r'^[IVABCDEF]+[\.]?\s.+'
# Acknowledgements or References
end_title = (r"^(a\s?cknowledgements|r\s?eferences|r\s?eference|a\s?cknowledgement|appendix|appendices|appendixes"
r"|appendixs|b\s?ibliography|biblio|a\s?cknowledgments|a\s?cknowledgment)$")
if_end = True if bool(re.match(end_title, text, re.IGNORECASE)) else False
return bool(re.match(title_arabia_pattern, text)) or bool(re.match(title_rome_pattern, text)) or if_end, if_end
def if_double_space(text):
flag = False
if " " in text:
# might occur some misformat title
pattern = r"^[\da-zA-Z\s\:'\?]+"
if not re.match(pattern, text):
flag = True
return flag
def if_paper_header(text):
pattern = r'^\d[\.]?\s.+(?:et.\sal)$'
return bool(re.match(pattern, text))
def is_obvious_chapter_title(text, add=False):
# add: True if the title has pattern like "1. introduction"
if add:
title_arabia_pattern = r'^\d\.\s.+'
title_rome_pattern = r'^[IV]+\.\s.+'
else:
title_arabia_pattern = r'^\d\s.+'
title_rome_pattern = r'^[IV]+\s.+'
return bool(re.match(title_arabia_pattern, text)) or bool(re.match(title_rome_pattern, text))
def check_intro_pattern(text):
ara_intro_pattern = r'^\d[\.]?\s\s?i\s?ntroduction'
rom_intro_pattern = r'^[IVABCDEF]+[\.]?\s\s?i\s?ntroduction'
if bool(re.match(ara_intro_pattern, text, re.IGNORECASE)) or bool(re.match(rom_intro_pattern, text, re.IGNORECASE)):
add_ara_intro_pattern = r'^\d\.\s\s?i\s?ntroduction'
add_rom_intro_pattern = r'^[IVABCDEF]+\.\s\s?i\s?ntroduction'
if bool(re.match(add_ara_intro_pattern, text, re.IGNORECASE)) or bool(re.match(add_rom_intro_pattern, text, re.IGNORECASE)):
return 2
return 1
return 0
def title_len_constraint(text):
return 5 < len(text) < 55
def paper_title_len_constraint(text):
return 10 < len(text) <= 100
def is_body_text(text):
return len(text) > 200 or text.endswith(".") or text.endswith("?") or text.endswith("!") or text.endswith("-")
def is_table(text):
# table_pattern = r"^Table\s\d+\."
return "\t" in text or " | " in text
def is_image(text):
# figure_pattern = r"^Figure\s\d+\."
return text.startswith("Image:") or text.startswith("Figure:")
def is_formula(text):
# ignore numbers
all_num_pattern = r"^[\.\d\−\s]+$"
return text.startswith("Formula:") or text.startswith("Equation:") or bool(re.match(all_num_pattern, text))
def is_url(text):
url_pattern = r"^(?:\d*\s)?https?://\S+"
return bool(re.match(url_pattern, text)) or text.startswith('arXiv:')
# Examples:
# arxiv_id = "./arxiv_archive/2106.09685.pdf"
# download_pdf_from_arxiv(1811.09243)
# all_titles = extract_all_titles(arxiv_id)
# all_chap_titles = select_chaptitle_from_alltitles(all_titles)
# bodies = extract_bodies(arxiv_id, all_chap_titles, all_titles)
# arxiv_id = "2106.09685"
# path = f"arxiv_archive/{arxiv_id}.pdf"
# download_pdf_from_arxiv(arxiv_id)
# paper_title = extract_paper_title(path)
# print(paper_title)