Spaces:
Runtime error
Runtime error
Download app.py from AIStockAdvisor/PDF_X_tract: direct link, hf CLI and curl.
- Browser
- Download file 5.47 kB
-
https://huggingface.co/spaces/AIStockAdvisor/PDF_X_tract/resolve/main/app.py
- Command line
-
hf download hf://spaces/AIStockAdvisor/PDF_X_tract/app.py
-
curl -L -o app.py https://huggingface.co/spaces/AIStockAdvisor/PDF_X_tract/resolve/main/app.py
5.47 kB
| import gradio as gr | |
| from docling.document_converter import DocumentConverter, PdfFormatOption | |
| from docling.datamodel.pipeline_options import PdfPipelineOptions | |
| from docling_core.types.doc import ImageRefMode | |
| from docx import Document as WordDocument | |
| from docx.shared import Inches | |
| import re | |
| import io | |
| import base64 | |
| import tempfile | |
| def write_markdown_to_word(md_text: str, word_doc: WordDocument, include_images=False): | |
| image_pattern = re.compile(r'!\[.*?\]\((data:image\/png;base64,[^\)]+)\)') | |
| lines = md_text.splitlines() | |
| i = 0 | |
| while i < len(lines): | |
| line = lines[i].rstrip() | |
| # -- NEW: REMOVE image placeholder tags if not including images <!-- image --> or <!-- image ... --> or embed image | |
| if not include_images and (line.strip() == "<!-- image -->" or line.strip().startswith("<!-- image")): | |
| i += 1 | |
| continue | |
| # Images (base64-encoded) | |
| match = image_pattern.search(line) | |
| if match: | |
| if include_images: | |
| image_data = match.group(1) | |
| header, b64data = image_data.split(',', 1) | |
| img_stream = io.BytesIO(base64.b64decode(b64data)) | |
| word_doc.add_picture(img_stream, width=Inches(4)) | |
| i += 1 | |
| continue | |
| if not line: | |
| word_doc.add_paragraph("") | |
| i += 1 | |
| continue | |
| if line.startswith("#"): | |
| level = min(line.count("#"), 4) | |
| heading_text = line.lstrip("#").strip() | |
| word_doc.add_heading(heading_text, level=level) | |
| i += 1 | |
| continue | |
| if line.startswith("```"): | |
| code_lines = [] | |
| i += 1 | |
| while i < len(lines) and not lines[i].startswith("```"): | |
| code_lines.append(lines[i]) | |
| i += 1 | |
| word_doc.add_paragraph("\n".join(code_lines)) | |
| if i < len(lines) and lines[i].startswith("```"): | |
| i += 1 | |
| continue | |
| if line.lstrip().startswith(("- ", "* ")): | |
| while i < len(lines) and lines[i].lstrip().startswith(("- ", "* ")): | |
| item = lines[i].lstrip()[2:].strip() | |
| word_doc.add_paragraph(f" - {item}") | |
| i += 1 | |
| continue | |
| if "|" in line: | |
| if i + 1 < len(lines) and set(lines[i + 1].replace("|", "").replace(" ", "")) <= set("-:"): | |
| header_cells = [c.strip() for c in line.strip("|").split("|")] | |
| i += 2 | |
| data_rows = [] | |
| while i < len(lines) and "|" in lines[i]: | |
| row_cells = [c.strip() for c in lines[i].strip("|").split("|")] | |
| data_rows.append(row_cells) | |
| i += 1 | |
| n_cols = len(header_cells) | |
| n_rows = len(data_rows) | |
| tbl = word_doc.add_table(rows=n_rows + 1, cols=n_cols) | |
| tbl.style = "Table Grid" | |
| for c_idx, col_name in enumerate(header_cells): | |
| tbl.cell(0, c_idx).text = str(col_name) | |
| for r_idx, row in enumerate(data_rows): | |
| for c_idx in range(n_cols): | |
| val = row[c_idx] if c_idx < len(row) else "" | |
| tbl.cell(r_idx + 1, c_idx).text = str(val) | |
| word_doc.add_paragraph("") | |
| continue | |
| word_doc.add_paragraph(line) | |
| i += 1 | |
| def pdf_to_word(pdf_file, include_images_radio): | |
| try: | |
| include_images = (include_images_radio == "Yes") | |
| if include_images: | |
| pipeline_options = PdfPipelineOptions() | |
| pipeline_options.images_scale = 2.0 | |
| pipeline_options.generate_page_images = True | |
| pipeline_options.generate_picture_images = True | |
| converter = DocumentConverter( | |
| format_options={ | |
| "pdf": PdfFormatOption(pipeline_options=pipeline_options) | |
| } | |
| ) | |
| else: | |
| converter = DocumentConverter() | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf: | |
| tmp_pdf.write(pdf_file) | |
| pdf_path = tmp_pdf.name | |
| result = converter.convert(pdf_path) | |
| doc = result.document | |
| if include_images: | |
| md = doc.export_to_markdown(image_mode=ImageRefMode.EMBEDDED) | |
| else: | |
| md = doc.export_to_markdown() | |
| word_doc = WordDocument() | |
| write_markdown_to_word(md, word_doc, include_images=include_images) | |
| # Write Word doc to temp file and return file path | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp_docx: | |
| word_doc.save(tmp_docx) | |
| docx_path = tmp_docx.name | |
| return docx_path, "" | |
| except Exception as e: | |
| # Return 'None' for the file, and the error message for the error component | |
| return (None, f"Error: {str(e)}") | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## PDF to Word (Text, Tables, and Optional Images) via Docling") | |
| pdf_input = gr.File(label="Upload PDF", type="binary") | |
| include_images = gr.Radio(["Yes", "No"], label="Include Images", value="No") | |
| btn = gr.Button("Convert and Download Word (.docx)") | |
| output = gr.File(label="Download Word File (.docx)") | |
| error_box = gr.Textbox(label="Error (if any)", interactive=False) | |
| btn.click(fn=pdf_to_word, inputs=[pdf_input, include_images], outputs=[output, error_box]) | |
| demo.launch() | |