Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import shutil
|
| 6 |
+
|
| 7 |
+
def convert_to_image(docx_file, output_format):
|
| 8 |
+
try:
|
| 9 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 10 |
+
tmpdir = Path(tmpdir)
|
| 11 |
+
|
| 12 |
+
# 1. Save uploaded file
|
| 13 |
+
docx_path = tmpdir / "input.docx"
|
| 14 |
+
with open(docx_path, "wb") as f:
|
| 15 |
+
f.write(open(docx_file.name, "rb").read()) # Fixed file handling
|
| 16 |
+
|
| 17 |
+
# 2. Convert DOCX β PDF
|
| 18 |
+
pdf_path = tmpdir / "output.pdf"
|
| 19 |
+
subprocess.run([
|
| 20 |
+
"soffice", "--headless",
|
| 21 |
+
"--convert-to", "pdf",
|
| 22 |
+
"--outdir", str(tmpdir),
|
| 23 |
+
str(docx_path)
|
| 24 |
+
], check=True, timeout=30)
|
| 25 |
+
|
| 26 |
+
# 3. Convert PDF β Image
|
| 27 |
+
img_path = tmpdir / f"output.{output_format}"
|
| 28 |
+
subprocess.run([
|
| 29 |
+
"pdftoppm",
|
| 30 |
+
"-singlefile",
|
| 31 |
+
"-jpeg" if output_format == "jpg" else "-png",
|
| 32 |
+
"-r", "150",
|
| 33 |
+
str(pdf_path),
|
| 34 |
+
str(img_path.with_suffix('')) # Remove extension for pdftoppm
|
| 35 |
+
], check=True)
|
| 36 |
+
|
| 37 |
+
# Verify image exists
|
| 38 |
+
if not img_path.exists():
|
| 39 |
+
raise ValueError("Image generation failed")
|
| 40 |
+
|
| 41 |
+
return img_path
|
| 42 |
+
|
| 43 |
+
except Exception as e:
|
| 44 |
+
raise gr.Error(f"Conversion failed: {str(e)}")
|
| 45 |
+
|
| 46 |
+
with gr.Blocks() as app:
|
| 47 |
+
gr.Markdown("## π DOCX to Image Converter")
|
| 48 |
+
with gr.Row():
|
| 49 |
+
file_input = gr.File(label="Upload DOCX", file_types=[".docx"])
|
| 50 |
+
format_radio = gr.Radio(["jpg", "png"], label="Output Format", value="jpg")
|
| 51 |
+
output_image = gr.Image(label="Result", type="filepath") # This ensures image output only
|
| 52 |
+
|
| 53 |
+
gr.Button("Convert").click(
|
| 54 |
+
fn=convert_to_image,
|
| 55 |
+
inputs=[file_input, format_radio],
|
| 56 |
+
outputs=output_image
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
app.launch()
|