-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
119 lines (103 loc) · 4.52 KB
/
Copy pathapp.py
File metadata and controls
119 lines (103 loc) · 4.52 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import gradio as gr
import subprocess
import tempfile
import os
import shutil
# Ensure the conversion script is executable
script_path = os.path.join(os.path.dirname(__file__), "convert_to_webp.sh")
if not os.access(script_path, os.X_OK):
try:
os.chmod(script_path, 0o755)
print(f"Made {script_path} executable.")
except Exception as e:
print(f"Warning: Could not make {script_path} executable: {e}")
# Optionally, raise an error or handle it differently if execution is critical
# raise RuntimeError(f"Script {script_path} must be executable.") from e
def convert_image(input_image):
"""
Converts the uploaded image to WebP using the shell script.
Args:
input_image: The uploaded image file object (from Gradio Image component).
Returns:
Tuple[str, str]: Path to the output WebP image and the script's output/errors.
"""
if input_image is None:
return None, "Please upload an image first."
# Use a temporary directory to handle input and output files
with tempfile.TemporaryDirectory() as temp_dir:
# Get the original filename and extension
original_filename = os.path.basename(input_image)
base_name, _ = os.path.splitext(original_filename)
# Define input and output paths within the temporary directory
input_path = os.path.join(temp_dir, original_filename)
output_webp_filename = f"{base_name}.webp"
output_path = os.path.join(temp_dir, output_webp_filename)
# Copy the uploaded file (using its path) to the temporary directory
shutil.copy(input_image, input_path)
print(f"Copied uploaded file to temporary path: {input_path}")
# Construct the command
command = [script_path, input_path, output_path]
print(f"Running command: {' '.join(command)}")
try:
# Run the conversion script
result = subprocess.run(
command,
capture_output=True,
text=True,
check=True, # Raise an exception for non-zero exit codes
encoding='utf-8' # Specify encoding
)
script_output = f"""Conversion Successful:
{result.stdout}"""
print(script_output)
# Gradio needs a persistent path to display the image,
# so we copy the result out of the temp dir
# Create a dedicated output directory if it doesn't exist
output_dir = "output_images"
os.makedirs(output_dir, exist_ok=True)
persistent_output_path = os.path.join(output_dir, output_webp_filename)
shutil.copy(output_path, persistent_output_path)
print(f"Copied result to persistent path: {persistent_output_path}")
return persistent_output_path, script_output
except subprocess.CalledProcessError as e:
error_message = f"""Conversion Failed:
Exit Code: {e.returncode}
Stderr:
{e.stderr}
Stdout:
{e.stdout}"""
print(error_message)
return None, error_message
except Exception as e:
error_message = f"An unexpected error occurred: {str(e)}"
print(error_message)
return None, error_message
# Define the Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Image to WebP Converter")
gr.Markdown("Upload an image (JPEG, PNG, etc.) to convert it to WebP format using optimized settings.")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="filepath", label="Upload Image")
convert_button = gr.Button("Convert to WebP", variant="primary")
with gr.Column():
image_output = gr.Image(type="filepath", label="WebP Output")
status_output = gr.Textbox(label="Conversion Log", lines=10, interactive=False)
convert_button.click(
fn=convert_image,
inputs=image_input,
outputs=[image_output, status_output],
api_name="convert_to_webp" # Optional: for API usage
)
gr.Examples(
examples=[os.path.join(os.path.dirname(__file__), "examples/sample.jpg")], # Add a path to an example image if you have one
inputs=image_input
)
if __name__ == "__main__":
# Clean up previous output images if the directory exists
output_dir = "output_images"
if os.path.exists(output_dir):
print(f"Cleaning up previous output directory: {output_dir}")
shutil.rmtree(output_dir)
os.makedirs(output_dir) # Recreate it empty
demo.launch() # Add share=True if you want a public link