Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from docling.document_converter import DocumentConverter, PdfFormatOption
|
| 3 |
+
from docling.datamodel.pipeline_options import PdfPipelineOptions
|
| 4 |
+
from docling_core.types.doc import ImageRefMode
|
| 5 |
+
from docx import Document as WordDocument
|
| 6 |
+
from docx.shared import Inches
|
| 7 |
+
import re
|
| 8 |
+
import io
|
| 9 |
+
import base64
|
| 10 |
+
import tempfile
|
| 11 |
+
|
| 12 |
+
def write_markdown_to_word(md_text: str, word_doc: WordDocument, include_images=False):
|
| 13 |
+
image_pattern = re.compile(r'!\[.*?\]\((data:image\/png;base64,[^\)]+)\)')
|
| 14 |
+
lines = md_text.splitlines()
|
| 15 |
+
i = 0
|
| 16 |
+
while i < len(lines):
|
| 17 |
+
line = lines[i].rstrip()
|
| 18 |
+
# Images (base64-encoded)
|
| 19 |
+
match = image_pattern.search(line)
|
| 20 |
+
if match:
|
| 21 |
+
if include_images:
|
| 22 |
+
image_data = match.group(1)
|
| 23 |
+
header, b64data = image_data.split(',', 1)
|
| 24 |
+
img_stream = io.BytesIO(base64.b64decode(b64data))
|
| 25 |
+
word_doc.add_picture(img_stream, width=Inches(4))
|
| 26 |
+
i += 1
|
| 27 |
+
continue
|
| 28 |
+
# Blank line
|
| 29 |
+
if not line:
|
| 30 |
+
word_doc.add_paragraph("")
|
| 31 |
+
i += 1
|
| 32 |
+
continue
|
| 33 |
+
# Headings
|
| 34 |
+
if line.startswith("#"):
|
| 35 |
+
level = min(line.count("#"), 4)
|
| 36 |
+
heading_text = line.lstrip("#").strip()
|
| 37 |
+
word_doc.add_heading(heading_text, level=level)
|
| 38 |
+
i += 1
|
| 39 |
+
continue
|
| 40 |
+
# Code blocks (fenced)
|
| 41 |
+
if line.startswith("```
|
| 42 |
+
code_lines = []
|
| 43 |
+
i += 1
|
| 44 |
+
while i < len(lines) and not lines[i].startswith("```"):
|
| 45 |
+
code_lines.append(lines[i])
|
| 46 |
+
i += 1
|
| 47 |
+
word_doc.add_paragraph("\n".join(code_lines))
|
| 48 |
+
if i < len(lines) and lines[i].startswith("```
|
| 49 |
+
i += 1
|
| 50 |
+
continue
|
| 51 |
+
# Unordered lists
|
| 52 |
+
if line.lstrip().startswith(("- ", "* ")):
|
| 53 |
+
while i < len(lines) and lines[i].lstrip().startswith(("- ", "* ")):
|
| 54 |
+
item = lines[i].lstrip()[2:].strip()
|
| 55 |
+
word_doc.add_paragraph(f" - {item}")
|
| 56 |
+
i += 1
|
| 57 |
+
continue
|
| 58 |
+
# Tables in Markdown
|
| 59 |
+
if "|" in line:
|
| 60 |
+
if i + 1 < len(lines) and set(lines[i + 1].replace("|", "").replace(" ", "")) <= set("-:"):
|
| 61 |
+
header_cells = [c.strip() for c in line.strip("|").split("|")]
|
| 62 |
+
i += 2
|
| 63 |
+
data_rows = []
|
| 64 |
+
while i < len(lines) and "|" in lines[i]:
|
| 65 |
+
row_cells = [c.strip() for c in lines[i].strip("|").split("|")]
|
| 66 |
+
data_rows.append(row_cells)
|
| 67 |
+
i += 1
|
| 68 |
+
n_cols = len(header_cells)
|
| 69 |
+
n_rows = len(data_rows)
|
| 70 |
+
tbl = word_doc.add_table(rows=n_rows + 1, cols=n_cols)
|
| 71 |
+
tbl.style = "Table Grid"
|
| 72 |
+
for c_idx, col_name in enumerate(header_cells):
|
| 73 |
+
tbl.cell(0, c_idx).text = str(col_name)
|
| 74 |
+
for r_idx, row in enumerate(data_rows):
|
| 75 |
+
for c_idx in range(n_cols):
|
| 76 |
+
val = row[c_idx] if c_idx < len(row) else ""
|
| 77 |
+
tbl.cell(r_idx + 1, c_idx).text = str(val)
|
| 78 |
+
word_doc.add_paragraph("")
|
| 79 |
+
continue
|
| 80 |
+
word_doc.add_paragraph(line)
|
| 81 |
+
i += 1
|
| 82 |
+
|
| 83 |
+
def pdf_to_word(pdf_file, include_images_radio):
|
| 84 |
+
try:
|
| 85 |
+
include_images = (include_images_radio == "Yes")
|
| 86 |
+
if include_images:
|
| 87 |
+
pipeline_options = PdfPipelineOptions()
|
| 88 |
+
pipeline_options.images_scale = 2.0
|
| 89 |
+
pipeline_options.generate_page_images = True
|
| 90 |
+
pipeline_options.generate_picture_images = True
|
| 91 |
+
converter = DocumentConverter(
|
| 92 |
+
format_options={
|
| 93 |
+
"pdf": PdfFormatOption(pipeline_options=pipeline_options)
|
| 94 |
+
}
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
converter = DocumentConverter()
|
| 98 |
+
# Accept file-like object and save to temp file
|
| 99 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf:
|
| 100 |
+
tmp_pdf.write(pdf_file.read())
|
| 101 |
+
pdf_path = tmp_pdf.name
|
| 102 |
+
result = converter.convert(pdf_path)
|
| 103 |
+
doc = result.document
|
| 104 |
+
# Export Markdown with or without embedded images
|
| 105 |
+
if include_images:
|
| 106 |
+
md = doc.export_to_markdown(image_mode=ImageRefMode.EMBEDDED)
|
| 107 |
+
else:
|
| 108 |
+
md = doc.export_to_markdown()
|
| 109 |
+
word_doc = WordDocument()
|
| 110 |
+
write_markdown_to_word(md, word_doc, include_images=include_images)
|
| 111 |
+
# Output docx as BytesIO
|
| 112 |
+
out_buf = io.BytesIO()
|
| 113 |
+
word_doc.save(out_buf)
|
| 114 |
+
out_buf.seek(0)
|
| 115 |
+
return out_buf
|
| 116 |
+
except Exception as e:
|
| 117 |
+
return f"Error: {e}"
|
| 118 |
+
|
| 119 |
+
with gr.Blocks() as demo:
|
| 120 |
+
gr.Markdown("## PDF to Word (Text, Tables, and Optional Images) via Docling")
|
| 121 |
+
pdf_input = gr.File(label="Upload PDF", type="binary")
|
| 122 |
+
include_images = gr.Radio(["Yes", "No"], label="Include Images", value="No")
|
| 123 |
+
btn = gr.Button("Convert and Download Word (.docx)")
|
| 124 |
+
output = gr.File(label="Download Word File (.docx)")
|
| 125 |
+
|
| 126 |
+
btn.click(fn=pdf_to_word, inputs=[pdf_input, include_images], outputs=output)
|
| 127 |
+
|
| 128 |
+
demo.launch()
|