Ocillus commited on
Commit
1bafbd4
·
verified ·
1 Parent(s): 9f188b5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ import os
4
+ import numpy as np
5
+ import cv2
6
+ import time
7
+ # Directory to store the PDF files
8
+ output_directory = "base"
9
+ os.makedirs(output_directory, exist_ok=True)
10
+
11
+ # Initialize an empty list to store the uploaded images as NumPy arrays
12
+ images_list = []
13
+
14
+ # Function to add an uploaded image (NumPy array) to the list
15
+ def add_image(image):
16
+ print(image) # Display the image array
17
+ global images_list
18
+ images_list.append(image)
19
+ return f"Image added! Current number of images: {len(images_list)}"
20
+
21
+ # Function to convert NumPy array to PIL Image
22
+ def numpy_to_pil(np_img):
23
+ if np_img.ndim == 2: # Grayscale
24
+ return Image.fromarray(np_img)
25
+ elif np_img.shape[2] == 3: # RGB
26
+ return Image.fromarray(cv2.cvtColor(np_img, cv2.COLOR_BGR2RGB))
27
+ elif np_img.shape[2] == 4: # RGBA
28
+ return Image.fromarray(cv2.cvtColor(np_img, cv2.COLOR_BGRA2RGBA))
29
+ else:
30
+ raise ValueError("Unsupported image format")
31
+
32
+ # Function to merge images into a PDF and save it
33
+ def merge_images_to_pdf():
34
+ if not images_list:
35
+ return "No images to merge!"
36
+
37
+ # Convert NumPy arrays to PIL Images
38
+ image_objs = [numpy_to_pil(img) for img in images_list]
39
+
40
+ # Save the images as a PDF
41
+ pdf_output_path = os.path.join(output_directory, str(time.ctime())+'.pdf')
42
+ image_objs[0].save(pdf_output_path, save_all=True, append_images=image_objs[1:])
43
+
44
+ # Clear the images list after saving the PDF
45
+ images_list.clear()
46
+
47
+ return f"PDF saved successfully at {pdf_output_path}!"
48
+
49
+ # Create the Gradio interface
50
+ with gr.Blocks() as demo:
51
+ gr.Markdown("### Image to PDF Converter")
52
+
53
+ # Image upload component (uses webcam or upload)
54
+ image_input = gr.Image(source="webcam", streaming=True, type="numpy")
55
+
56
+ # Button to add the image to the list
57
+ add_button = gr.Button("Add Image")
58
+
59
+ # Button to merge the images into a PDF
60
+ merge_button = gr.Button("Merge Images to PDF")
61
+
62
+ # Output text to display status
63
+ output_text = gr.Textbox(label="Status")
64
+
65
+ # Event handling
66
+ add_button.click(add_image, inputs=image_input, outputs=output_text)
67
+ merge_button.click(merge_images_to_pdf, outputs=output_text)
68
+
69
+ # Launch the Gradio app
70
+ demo.launch()