import gradio as gr import subprocess import tempfile from pathlib import Path def convert_to_image(docx_file, output_format): try: with tempfile.TemporaryDirectory() as tmpdir: # Step 1: Save uploaded file docx_path = Path(tmpdir) / "input.docx" with open(docx_path, "wb") as f: f.write(docx_file.read()) # Step 2: Convert DOCX → PDF pdf_path = Path(tmpdir) / "output.pdf" subprocess.run([ "soffice", "--headless", "--convert-to", "pdf", "--outdir", tmpdir, str(docx_path) ], check=True, timeout=30) # Step 3: Convert PDF → Image img_path = Path(tmpdir) / f"output.{output_format}" subprocess.run([ "pdftoppm", "-singlefile", "-jpeg" if output_format == "jpg" else "-png", "-r", "150", # DPI (150 for free tier) str(pdf_path), str(img_path.with_suffix('')) ], check=True) return str(img_path) if img_path.exists() else "Conversion failed" except Exception as e: return f"Error: {str(e)}" with gr.Blocks() as app: gr.Markdown("## 📄 DOCX to Image Converter") with gr.Row(): file_input = gr.File(label="Upload DOCX", file_types=[".docx"]) format_radio = gr.Radio(["jpg", "png"], label="Output Format", value="jpg") output_image = gr.Image(label="Result", type="filepath") gr.Button("Convert").click( fn=convert_to_image, inputs=[file_input, format_radio], outputs=output_image ) app.launch()