File size: 1,777 Bytes
7cce8c1
 
 
 
 
8afc243
7cce8c1
 
 
8afc243
 
 
7cce8c1
8afc243
 
 
7cce8c1
 
8afc243
7cce8c1
8afc243
 
7cce8c1
8afc243
 
 
 
 
 
 
 
 
 
7cce8c1
8afc243
7cce8c1
 
 
 
8afc243
 
7cce8c1
8afc243
 
 
7cce8c1
 
8afc243
 
 
7cce8c1
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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()