DexterSptizu
commited on
Commit
•
bfa3efc
1
Parent(s):
58e18ca
Update app.py
Browse files
app.py
CHANGED
@@ -6,19 +6,49 @@ import io
|
|
6 |
import os
|
7 |
from datetime import datetime
|
8 |
|
9 |
-
def
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
if not os.path.exists("temp"):
|
12 |
os.makedirs("temp")
|
13 |
-
temp_path = f"temp/{uploaded_file.name}"
|
14 |
|
15 |
-
#
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
return temp_path
|
19 |
|
20 |
def save_image_from_url(image_url, index):
|
21 |
-
|
22 |
response = requests.get(image_url)
|
23 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
24 |
output_path = f"generated_variations/{timestamp}_variation_{index}.png"
|
@@ -44,7 +74,8 @@ def main():
|
|
44 |
# Main content
|
45 |
st.write("Upload an image to generate variations using DALL-E 2")
|
46 |
|
47 |
-
# Image upload
|
|
|
48 |
uploaded_file = st.file_uploader("Choose an image file", type=["png", "jpg", "jpeg"])
|
49 |
|
50 |
# Control options
|
@@ -56,51 +87,62 @@ def main():
|
|
56 |
selected_size = st.selectbox("Image size", size_options)
|
57 |
|
58 |
if uploaded_file is not None:
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
n=num_variations,
|
79 |
-
size=selected_size
|
80 |
-
)
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
mime="image/png"
|
97 |
-
)
|
98 |
-
|
99 |
-
# Cleanup temporary file
|
100 |
-
os.remove(temp_path)
|
101 |
-
|
102 |
-
except Exception as e:
|
103 |
-
st.error(f"An error occurred: {str(e)}")
|
104 |
|
105 |
if __name__ == "__main__":
|
106 |
main()
|
|
|
6 |
import os
|
7 |
from datetime import datetime
|
8 |
|
9 |
+
def preprocess_image(uploaded_file):
|
10 |
+
"""
|
11 |
+
Preprocess the image to meet OpenAI's requirements:
|
12 |
+
- Convert to PNG
|
13 |
+
- Ensure file size is less than 4MB
|
14 |
+
- Resize if necessary while maintaining aspect ratio
|
15 |
+
"""
|
16 |
+
# Create temp directory if it doesn't exist
|
17 |
if not os.path.exists("temp"):
|
18 |
os.makedirs("temp")
|
|
|
19 |
|
20 |
+
# Open and convert image to PNG
|
21 |
+
image = Image.open(uploaded_file)
|
22 |
+
|
23 |
+
# Convert to RGB if image is in RGBA mode
|
24 |
+
if image.mode == 'RGBA':
|
25 |
+
image = image.convert('RGB')
|
26 |
+
|
27 |
+
# Calculate new dimensions while maintaining aspect ratio
|
28 |
+
max_size = 1024
|
29 |
+
ratio = min(max_size/image.width, max_size/image.height)
|
30 |
+
new_size = (int(image.width*ratio), int(image.height*ratio))
|
31 |
+
|
32 |
+
# Resize image if it's too large
|
33 |
+
if image.width > max_size or image.height > max_size:
|
34 |
+
image = image.resize(new_size, Image.Resampling.LANCZOS)
|
35 |
+
|
36 |
+
# Save processed image
|
37 |
+
temp_path = f"temp/processed_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
|
38 |
+
image.save(temp_path, "PNG", optimize=True)
|
39 |
+
|
40 |
+
# Check file size and compress if needed
|
41 |
+
while os.path.getsize(temp_path) > 4*1024*1024: # 4MB in bytes
|
42 |
+
image = image.resize(
|
43 |
+
(int(image.width*0.9), int(image.height*0.9)),
|
44 |
+
Image.Resampling.LANCZOS
|
45 |
+
)
|
46 |
+
image.save(temp_path, "PNG", optimize=True)
|
47 |
+
|
48 |
return temp_path
|
49 |
|
50 |
def save_image_from_url(image_url, index):
|
51 |
+
"""Save image from URL to local file"""
|
52 |
response = requests.get(image_url)
|
53 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
54 |
output_path = f"generated_variations/{timestamp}_variation_{index}.png"
|
|
|
74 |
# Main content
|
75 |
st.write("Upload an image to generate variations using DALL-E 2")
|
76 |
|
77 |
+
# Image upload with clear file type instructions
|
78 |
+
st.info("Please upload a PNG, JPG, or JPEG image. The image will be automatically processed to meet OpenAI's requirements (PNG format, < 4MB).")
|
79 |
uploaded_file = st.file_uploader("Choose an image file", type=["png", "jpg", "jpeg"])
|
80 |
|
81 |
# Control options
|
|
|
87 |
selected_size = st.selectbox("Image size", size_options)
|
88 |
|
89 |
if uploaded_file is not None:
|
90 |
+
try:
|
91 |
+
# Display uploaded image
|
92 |
+
st.subheader("Uploaded Image")
|
93 |
+
image = Image.open(uploaded_file)
|
94 |
+
st.image(image, caption="Uploaded Image", use_container_width=True)
|
95 |
+
|
96 |
+
# Generate variations button
|
97 |
+
if st.button("Generate Variations"):
|
98 |
+
try:
|
99 |
+
# Preprocess and save image
|
100 |
+
with st.spinner("Processing image..."):
|
101 |
+
temp_path = preprocess_image(uploaded_file)
|
102 |
+
|
103 |
+
# Show processed image details
|
104 |
+
file_size_mb = os.path.getsize(temp_path) / (1024 * 1024)
|
105 |
+
st.success(f"Image processed successfully! File size: {file_size_mb:.2f}MB")
|
106 |
+
|
107 |
+
# Initialize OpenAI client
|
108 |
+
client = OpenAI(api_key=api_key)
|
|
|
|
|
|
|
109 |
|
110 |
+
with st.spinner("Generating variations..."):
|
111 |
+
# Generate variations
|
112 |
+
response = client.images.create_variation(
|
113 |
+
model="dall-e-2",
|
114 |
+
image=open(temp_path, "rb"),
|
115 |
+
n=num_variations,
|
116 |
+
size=selected_size
|
117 |
+
)
|
118 |
+
|
119 |
+
# Display generated variations
|
120 |
+
st.subheader("Generated Variations")
|
121 |
+
cols = st.columns(num_variations)
|
122 |
+
|
123 |
+
for idx, image_data in enumerate(response.data):
|
124 |
+
# Save and display each variation
|
125 |
+
saved_path = save_image_from_url(image_data.url, idx)
|
126 |
+
with cols[idx]:
|
127 |
+
st.image(saved_path, caption=f"Variation {idx+1}", use_container_width=True)
|
128 |
+
with open(saved_path, "rb") as file:
|
129 |
+
st.download_button(
|
130 |
+
label=f"Download Variation {idx+1}",
|
131 |
+
data=file,
|
132 |
+
file_name=f"variation_{idx+1}.png",
|
133 |
+
mime="image/png"
|
134 |
+
)
|
135 |
|
136 |
+
# Cleanup temporary file
|
137 |
+
os.remove(temp_path)
|
138 |
+
|
139 |
+
except Exception as e:
|
140 |
+
st.error(f"An error occurred: {str(e)}")
|
141 |
+
if "invalid_request_error" in str(e):
|
142 |
+
st.info("Please ensure your image meets OpenAI's requirements: PNG format, less than 4MB, and appropriate content.")
|
143 |
+
|
144 |
+
except Exception as e:
|
145 |
+
st.error(f"Error loading image: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
if __name__ == "__main__":
|
148 |
main()
|