Spaces:
Runtime error
Runtime error
import gradio as gr | |
from PIL import Image | |
import os | |
import numpy as np | |
import cv2 | |
import time | |
# Directory to store the PDF files | |
output_directory = "base" | |
os.makedirs(output_directory, exist_ok=True) | |
# Initialize an empty list to store the uploaded images as NumPy arrays | |
images_list = [] | |
# Function to add an uploaded image (NumPy array) to the list | |
def add_image(image): | |
print(image) # Display the image array | |
global images_list | |
images_list.append(image) | |
return f"Image added! Current number of images: {len(images_list)}" | |
# Function to convert NumPy array to PIL Image | |
def numpy_to_pil(np_img): | |
if np_img.ndim == 2: # Grayscale | |
return Image.fromarray(np_img) | |
elif np_img.shape[2] == 3: # RGB | |
return Image.fromarray(cv2.cvtColor(np_img, cv2.COLOR_BGR2RGB)) | |
elif np_img.shape[2] == 4: # RGBA | |
return Image.fromarray(cv2.cvtColor(np_img, cv2.COLOR_BGRA2RGBA)) | |
else: | |
raise ValueError("Unsupported image format") | |
# Function to merge images into a PDF and save it | |
def merge_images_to_pdf(): | |
if not images_list: | |
return "No images to merge!" | |
# Convert NumPy arrays to PIL Images | |
image_objs = [numpy_to_pil(img) for img in images_list] | |
# Save the images as a PDF | |
pdf_output_path = os.path.join(output_directory, str(time.ctime())+'.pdf') | |
image_objs[0].save(pdf_output_path, save_all=True, append_images=image_objs[1:]) | |
# Clear the images list after saving the PDF | |
images_list.clear() | |
return f"PDF saved successfully at {pdf_output_path}!" | |
# Create the Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("### Image to PDF Converter") | |
# Image upload component (uses webcam or upload) | |
image_input = gr.Image(source="webcam", streaming=True, type="numpy") | |
# Button to add the image to the list | |
add_button = gr.Button("Add Image") | |
# Button to merge the images into a PDF | |
merge_button = gr.Button("Merge Images to PDF") | |
# Output text to display status | |
output_text = gr.Textbox(label="Status") | |
# Event handling | |
add_button.click(add_image, inputs=image_input, outputs=output_text) | |
merge_button.click(merge_images_to_pdf, outputs=output_text) | |
# Launch the Gradio app | |
demo.launch() | |