BULLET_POINTS = "•◦▪▫●○"
PAGE_DELIMITER = "\n---\n"
def __init__(self, pdf_path, output_path):
super().__init__(pdf_path, output_path)
self.pdf_filename = Path(pdf_path).stem
self.output_dir = Path(output_path).parent
self.output_dir.mkdir(parents=True, exist_ok=True)
# Initialize Docling converter
pipeline_options = PdfPipelineOptions(
do_ocr=True,
ocr_options=EasyOcrOptions(lang=['fr', 'en']),
)
self.converter = DocumentConverter(
format_options={
InputFormat.PDF: PdfFormatOption(
pipeline_options=pipeline_options
)
}
)
def extract(self):
try:
markdown_content, markdown_pages = self.extract_markdown()
self.save_markdown(markdown_content)
self.logger.info(
f"Markdown content has been saved to {self.output_path}"
)
return markdown_content, markdown_pages
except Exception as e:
self.logger.error(f"Error processing PDF: {e}")
self.logger.exception(traceback.format_exc())
return "", []
def extract_markdown(self):
"""Main method to extract markdown from PDF."""
try:
# Convert PDF using Docling
result = self.converter.convert(self.pdf_path)
doc = result.document
markdown_content = ""
markdown_pages = []
tables = self.extract_tables()
table_index = 0
list_counter = 0
in_code_block = False
code_block_content = ""
code_block_lang = None
prev_line = ""
# Process each page text blocks
for item, level in doc.iterate_items():
page_content = ""
# Process text items from Docling
if hasattr(item, 'text'):
page_content += self.process_text_block(
item,
level,
list_counter,
in_code_block,
code_block_content,
code_block_lang,
prev_line
)
# Insert tables at their positions
while (
table_index < len(tables)
and tables[table_index]["page"] == level
):
page_content += (
"\n\n"
+ self.table_to_markdown(tables[table_index]["content"])
+ "\n\n"
)
table_index += 1
markdown_pages.append(self.post_process_markdown(page_content))
markdown_content += page_content + self.PAGE_DELIMITER
markdown_content = self.post_process_markdown(markdown_content)
return markdown_content, markdown_pages
except Exception as e:
self.logger.error(f"Error extracting markdown: {e}")
self.logger.exception(traceback.format_exc())
return "", []
def extract_tables(self):
"""Extract tables from PDF using pdfplumber."""
tables = []
try:
with pdfplumber.open(self.pdf_path) as pdf:
for page_number, page in enumerate(pdf.pages):
page_tables = page.extract_tables()
if len(page_tables) > 128:
continue
for table in page_tables:
tables.append({"page": page_number, "content": table})
self.logger.info(f"Extracted {len(tables)} tables from the PDF.")
except Exception as e:
self.logger.error(f"Error extracting tables: {e}")
self.logger.exception(traceback.format_exc())
return tables
def table_to_markdown(self, table):
"""Convert a table to markdown format."""
if not table:
return ""
try:
table = [
["" if cell is None else str(cell).strip() for cell in row]
for row in table
]
col_widths = [max(len(cell) for cell in col) for col in zip(*table)]
markdown = ""
for i, row in enumerate(table):
formatted_row = [
cell.ljust(col_widths[j]) for j, cell in enumerate(row)
]
markdown += "| " + " | ".join(formatted_row) + " |\n"
if i == 0:
markdown += (
"|"
+ "|".join(["-" * (width + 2) for width in col_widths])
+ "|\n"
)
return markdown
except Exception as e:
self.logger.error(f"Error converting table to markdown: {e}")
self.logger.exception(traceback.format_exc())
return ""
def process_text_block(
self,
item,
level,
list_counter,
in_code_block,
code_block_content,
code_block_lang,
prev_line
):
"""Process a text block and convert it to markdown."""
try:
text = item.text if hasattr(item, 'text') else str(item)
text = self.clean_text(text)
block_text = ""
if text:
# Apply text formatting
text = self.apply_formatting(text, self.get_font_style(item))
if self.is_bullet_point(text):
text = self.convert_bullet_to_markdown(text)
list_counter = 0
[Redacted Person] self.is_numbered_list_item(text):
list_counter += 1
text = self.convert_numbered_list_to_markdown(text, list_counter)
[Redacted Person] self.is_horizontal_line(text):
text = "\n---\n"
else:
list_counter = 0
# Process code blocks
if not in_code_block:
code_lang = self.detect_code_block(prev_line, text)
if code_lang:
in_code_block = True
code_block_lang = code_lang
code_block_content = prev_line + "\n" + text + "\n"
prev_line = text
return ""
if in_code_block:
code_block_content += text + "\n"
if (
self.detect_code_block(text, prev_line)
!= code_block_lang
):
block_text = (
f"```{code_block_lang}\n{code_block_content}```\n\n"
)
in_code_block = False
code_block_content = ""
code_block_lang = None
prev_line = text
else:
block_text = text + "\n"
prev_line = text
return block_text
except Exception as e:
self.logger.error(f"Error processing text block: {e}")
self.logger.exception(traceback.format_exc())
return ""
def get_font_style(self, item):
"""Get font style flags from item."""
flags = 0
if hasattr(item, 'font'):
font = item.font.lower()
if 'bold' in font:
flags |= 2**4
if 'italic' in font:
flags |= 2**1
if 'mono' in font:
flags |= 2**3
return flags
def clean_text(self, text):
"""Clean the given text by removing extra spaces."""
text = text.strip()
text = re.sub(r"\s+", " ", text)
return text
def apply_formatting(self, text, flags):
"""Apply markdown formatting to the given text based on flags."""
text = text.strip()
if not text:
return text
is_bold = flags & 2**4
is_italic = flags & 2**1
is_monospace = flags & 2**3
is_superscript = flags & 2**0
is_subscript = flags & 2**5
if is_monospace:
text = f"`{text}`"
elif is_superscript and not bool(re.search(r"\s+", text)):
text = f"^{text}^"
elif is_subscript and not bool(re.search(r"\s+", text)):
text = f"~{text}~"
if is_bold and is_italic:
text = f"***{text}***"
[Redacted Person] is_bold:
text = f"**{text}**"
[Redacted Person] is_italic:
text = f"*{text}*"
return f" {text} "
def is_bullet_point(self, text):
"""Check if the given text is a bullet point."""
return text.strip().startswith(tuple(self.BULLET_POINTS))
def convert_bullet_to_markdown(self, text):
"""Convert a bullet point to markdown format."""
text = re.sub(r"^\s*", "", text)
return re.sub(f"^[{re.escape(self.BULLET_POINTS)}]\s*", "- ", text)
def is_numbered_list_item(self, text):
"""Check if the given text is a numbered list item."""
return bool(re.match(r"^\d+\s{0,3}[.)]", text.strip()))
def convert_numbered_list_to_markdown(self, text, list_counter):
"""Convert a numbered list item to markdown format."""
text = re.sub(r"^\s*", "", text)
return re.sub(r"^\d+\s{0,3}[.)]", f"{list_counter}. ", text)
def is_horizontal_line(self, text):
"""Check if the given text represents a horizontal line."""
return bool(re.match(r"^[_-]+$", text.strip()))
def detect_code_block(self, prev_line, current_line):
"""Detect if the current line starts a code block."""
patterns = {
"python": [
(
r"^(?:from|import)\s+\w+",
r"^(?:from|import|def|class|if|for|while|try|except|with)\s",
),
(r"^(?:def|class)\s+\w+", r"^\s{4}"),
(r"^\s{4}", r"^\s{4,}"),
],
"javascript": [
(
r"^(?:function|const|let|var)\s+\w+",
r"^(?:function|const|let|var|if|for|while|try|catch|class)\s",
),
(r"^(?:if|for|while)\s*\(", r"^\s{2,}"),
(r"^\s{2,}", r"^\s{2,}"),
],
"html": [
(
r"^<(!DOCTYPE|html|head|body|div|p|a|script|style)",
r"^<(!DOCTYPE|html|head|body|div|p|a|script|style)",
),
(r"^<\w+.*>$", r"^\s{2,}<"),
(r"^\s{2,}<", r"^\s{2,}<"),
],
"shell": [
(r"^(?:\$|\#)\s", r"^(?:\$|\#)\s"),
(r"^[a-z_]+\s*=", r"^[a-z_]+\s*="),
],
"bash": [
(
r"^(?:#!/bin/bash|alias|export|source)\s",
r"^(?:#!/bin/bash|alias|export|source|echo|read|if|for|while|case|function)\s",
),
(r"^(?:if|for|while|case|function)\s", r"^\s{2,}"),
(r"^\s{2,}", r"^\s{2,}"),
],
"cpp": [
(
r"^#include\s*<",
r"^(?:#include|using|namespace|class|struct|enum|template|typedef)\s",
),
(r"^(?:class|struct|enum)\s+\w+", r"^\s{2,}"),
(r"^\s{2,}", r"^\s{2,}"),
],
"java": [
(
r"^(?:import|package)\s+\w+",
r"^(?:import|package|public|private|protected|class|interface|enum)\s",
),
(r"^(?:public|private|protected)\s+class\s+\w+", r"^\s{4,}"),
(r"^\s{4,}", r"^\s{4,}"),
],
"json": [
(r"^\s*{", r'^\s*["{[]'),
(r'^\s*"', r'^\s*["}],?$'),
(r"^\s*\[", r"^\s*[}\]],?$"),
],
}
for lang, pattern_pairs in patterns.items():
for prev_pattern, curr_pattern in pattern_pairs:
if re.match(prev_pattern, prev_line.strip()) and re.match(
curr_pattern, current_line.strip()
):
return lang
return None
def post_process_markdown(self, markdown_content):
try:
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
markdown_content = re.sub(r"(\d+)\s*\n", "", markdown_content)
markdown_content = re.sub(r" +", " ", markdown_content)
markdown_content = re.sub(r"\s*(---\n)+", "\n\n---\n", markdown_content)
def remove_middle_headers(match):
line = match.group(0)
return re.sub(
r"(^#{1,6}\s).*?(?=\n)",
lambda m: m.group(1) + re.sub(r"#", "", m.group(0)[len(m.group(1)):]),
line,
)
markdown_content = re.sub(
r"^#{1,6}\s.*\n",
remove_middle_headers,
markdown_content,
flags=re.MULTILINE,
)
return markdown_content
except Exception as e:
self.logger.error(f"Error post-processing markdown: {e}")
self.logger.exception(traceback.format_exc())
return markdown_content
def save_markdown(self, markdown_content):
try:
with open(self.output_path, "w", encoding="utf-8") as f:
f.write(markdown_content)
self.logger.info("Markdown content saved successfully.")
except Exception as e:
self.logger.error(f"Error saving markdown content: {e}")
self.logger.exception(traceback.format_exc())