Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import tempfile
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
def images_to_pdf(image_files):
|
| 7 |
+
"""
|
| 8 |
+
Takes a list of image file paths, converts them to RGB,
|
| 9 |
+
and saves them as a single PDF in a temporary location.
|
| 10 |
+
"""
|
| 11 |
+
if not image_files:
|
| 12 |
+
return None
|
| 13 |
+
|
| 14 |
+
pil_images = []
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
# Loop through file paths received from Gradio
|
| 18 |
+
for file_path in image_files:
|
| 19 |
+
try:
|
| 20 |
+
img = Image.open(file_path)
|
| 21 |
+
# Convert RGBA (transparent) to RGB to ensure PDF compatibility
|
| 22 |
+
if img.mode == 'RGBA':
|
| 23 |
+
img = img.convert('RGB')
|
| 24 |
+
pil_images.append(img)
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"Error processing file {file_path}: {e}")
|
| 27 |
+
continue
|
| 28 |
+
|
| 29 |
+
if not pil_images:
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
# Create a temporary file for the PDF output
|
| 33 |
+
# suffix='.pdf' is crucial so Gradio knows how to serve it back
|
| 34 |
+
temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
|
| 35 |
+
output_path = temp_pdf.name
|
| 36 |
+
|
| 37 |
+
# Save the first image and append the rest
|
| 38 |
+
pil_images[0].save(
|
| 39 |
+
output_path,
|
| 40 |
+
save_all=True,
|
| 41 |
+
append_images=pil_images[1:]
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
return output_path
|
| 45 |
+
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Error creating PDF: {e}")
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
# Define the Gradio Interface
|
| 51 |
+
with gr.Blocks(title="Image to PDF Converter") as app:
|
| 52 |
+
gr.Markdown("# 📄 Images to PDF API")
|
| 53 |
+
gr.Markdown("Upload multiple images to convert them into a single PDF file. Use via interface or API.")
|
| 54 |
+
|
| 55 |
+
with gr.Row():
|
| 56 |
+
with gr.Column():
|
| 57 |
+
img_input = gr.File(
|
| 58 |
+
file_count="multiple",
|
| 59 |
+
file_types=["image"],
|
| 60 |
+
label="Upload Images"
|
| 61 |
+
)
|
| 62 |
+
convert_btn = gr.Button("Convert to PDF", variant="primary")
|
| 63 |
+
|
| 64 |
+
with gr.Column():
|
| 65 |
+
pdf_output = gr.File(label="Download PDF")
|
| 66 |
+
|
| 67 |
+
convert_btn.click(fn=images_to_pdf, inputs=img_input, outputs=pdf_output)
|
| 68 |
+
|
| 69 |
+
# Launch with 0.0.0.0 to ensure it runs on Spaces
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
app.launch(server_name="0.0.0.0")
|