admin08077 commited on
Commit
7e603e5
·
verified ·
1 Parent(s): cd6d071

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +558 -0
app.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance, ImageOps, ImageChops, ImageColor
3
+ import numpy as np
4
+ import io
5
+ import os
6
+ import json
7
+ from rembg import remove
8
+ import requests
9
+ from pathlib import Path
10
+ import zipfile
11
+
12
+ # ------------------------------
13
+ # Utility Functions
14
+ # ------------------------------
15
+
16
+ def download_file(url, dest_path):
17
+ """
18
+ Downloads a file from a URL to the specified destination path.
19
+ """
20
+ try:
21
+ response = requests.get(url, stream=True)
22
+ response.raise_for_status()
23
+ with open(dest_path, 'wb') as f:
24
+ for chunk in response.iter_content(chunk_size=8192):
25
+ f.write(chunk)
26
+ st.info(f"Downloaded: {dest_path.name}")
27
+ except Exception as e:
28
+ st.error(f"Failed to download {url}: {e}")
29
+
30
+ def setup_fonts():
31
+ """
32
+ Ensures that all required fonts are downloaded and available locally.
33
+ Uses open-source fonts from Google Fonts.
34
+ """
35
+ fonts_dir = Path("fonts")
36
+ fonts_dir.mkdir(exist_ok=True)
37
+
38
+ # Define open-source fonts to download
39
+ font_info = {
40
+ "Roboto": {
41
+ "name": "Roboto-Regular.ttf",
42
+ "url": "https://github.com/google/fonts/raw/main/apache/roboto/Roboto-Regular.ttf"
43
+ },
44
+ "OpenSans": {
45
+ "name": "OpenSans-Regular.ttf",
46
+ "url": "https://github.com/google/fonts/raw/main/apache/opensans/OpenSans-Regular.ttf"
47
+ },
48
+ "Lato": {
49
+ "name": "Lato-Regular.ttf",
50
+ "url": "https://github.com/google/fonts/raw/main/ofl/lato/Lato-Regular.ttf"
51
+ },
52
+ "Montserrat": {
53
+ "name": "Montserrat-Regular.ttf",
54
+ "url": "https://github.com/google/fonts/raw/main/ofl/montserrat/Montserrat-Regular.ttf"
55
+ },
56
+ "SourceSansPro": {
57
+ "name": "SourceSansPro-Regular.ttf",
58
+ "url": "https://github.com/google/fonts/raw/main/ofl/sourcesanspro/SourceSansPro-Regular.ttf"
59
+ }
60
+ }
61
+
62
+ # Download fonts if not already present
63
+ for font_key, font_details in font_info.items():
64
+ font_path = fonts_dir / font_details["name"]
65
+ if not font_path.exists():
66
+ st.info(f"Downloading {font_key} font...")
67
+ download_file(font_details["url"], font_path)
68
+ else:
69
+ st.success(f"Font {font_key} already exists.")
70
+
71
+ # Return a mapping of font names to paths
72
+ font_paths = {font_key: str(fonts_dir / details["name"]) for font_key, details in font_info.items()}
73
+ return font_paths
74
+
75
+ def setup_stickers():
76
+ """
77
+ Ensures that all required stickers are downloaded and available locally.
78
+ Downloads a set of free stickers from a reliable source.
79
+ """
80
+ stickers_dir = Path("stickers")
81
+ stickers_dir.mkdir(exist_ok=True)
82
+
83
+ # Define stickers to download
84
+ sticker_info = {
85
+ "Star": {
86
+ "name": "Star.png",
87
+ "url": "https://github.com/huggingface/datasets/raw/main/datasets/emoji/images/Star.png"
88
+ },
89
+ "Heart": {
90
+ "name": "Heart.png",
91
+ "url": "https://github.com/huggingface/datasets/raw/main/datasets/emoji/images/Heart.png"
92
+ },
93
+ "Smile": {
94
+ "name": "Smile.png",
95
+ "url": "https://github.com/huggingface/datasets/raw/main/datasets/emoji/images/Smile.png"
96
+ }
97
+ }
98
+
99
+ # Download stickers if not already present
100
+ for sticker_key, sticker_details in sticker_info.items():
101
+ sticker_path = stickers_dir / sticker_details["name"]
102
+ if not sticker_path.exists():
103
+ st.info(f"Downloading {sticker_key} sticker...")
104
+ download_file(sticker_details["url"], sticker_path)
105
+ else:
106
+ st.success(f"Sticker {sticker_key} already exists.")
107
+
108
+ # ------------------------------
109
+ # Initialize Application
110
+ # ------------------------------
111
+
112
+ # Set Streamlit page configuration
113
+ st.set_page_config(page_title="🎨 Pro Image Editor", layout="wide")
114
+
115
+ # Display a loading spinner while setting up fonts and stickers
116
+ with st.spinner('Setting up fonts and stickers...'):
117
+ font_paths = setup_fonts()
118
+ setup_stickers()
119
+
120
+ # Initialize session state for layers and history
121
+ if 'layers' not in st.session_state:
122
+ st.session_state['layers'] = []
123
+ if 'history' not in st.session_state:
124
+ st.session_state['history'] = []
125
+ if 'redo_stack' not in st.session_state:
126
+ st.session_state['redo_stack'] = []
127
+
128
+ # ------------------------------
129
+ # Layer Management Functions
130
+ # ------------------------------
131
+
132
+ def add_layer(layer):
133
+ st.session_state['layers'].append(layer)
134
+ st.session_state['history'].append(('add', layer))
135
+ st.session_state['redo_stack'] = []
136
+
137
+ def remove_layer(index):
138
+ layer = st.session_state['layers'].pop(index)
139
+ st.session_state['history'].append(('remove', layer, index))
140
+ st.session_state['redo_stack'] = []
141
+
142
+ def reorder_layers(from_idx, to_idx):
143
+ layer = st.session_state['layers'].pop(from_idx)
144
+ st.session_state['layers'].insert(to_idx, layer)
145
+ st.session_state['history'].append(('reorder', from_idx, to_idx))
146
+ st.session_state['redo_stack'] = []
147
+
148
+ def toggle_visibility(index):
149
+ st.session_state['layers'][index]['visible'] = not st.session_state['layers'][index].get('visible', True)
150
+ st.session_state['history'].append(('toggle', index))
151
+ st.session_state['redo_stack'] = []
152
+
153
+ def undo():
154
+ if not st.session_state['history']:
155
+ st.warning("No actions to undo.")
156
+ return
157
+ action = st.session_state['history'].pop()
158
+ st.session_state['redo_stack'].append(action)
159
+ action_type = action[0]
160
+ if action_type == 'add':
161
+ st.session_state['layers'].pop()
162
+ elif action_type == 'remove':
163
+ _, layer, index = action
164
+ st.session_state['layers'].insert(index, layer)
165
+ elif action_type == 'reorder':
166
+ _, from_idx, to_idx = action
167
+ layer = st.session_state['layers'].pop(to_idx)
168
+ st.session_state['layers'].insert(from_idx, layer)
169
+ elif action_type == 'toggle':
170
+ _, index = action
171
+ st.session_state['layers'][index]['visible'] = not st.session_state['layers'][index].get('visible', True)
172
+
173
+ def redo():
174
+ if not st.session_state['redo_stack']:
175
+ st.warning("No actions to redo.")
176
+ return
177
+ action = st.session_state['redo_stack'].pop()
178
+ st.session_state['history'].append(action)
179
+ action_type = action[0]
180
+ if action_type == 'add':
181
+ _, layer = action
182
+ st.session_state['layers'].append(layer)
183
+ elif action_type == 'remove':
184
+ _, _, index = action
185
+ st.session_state['layers'].pop(index)
186
+ elif action_type == 'reorder':
187
+ _, from_idx, to_idx = action
188
+ layer = st.session_state['layers'].pop(from_idx)
189
+ st.session_state['layers'].insert(to_idx, layer)
190
+ elif action_type == 'toggle':
191
+ _, index = action
192
+ st.session_state['layers'][index]['visible'] = not st.session_state['layers'][index].get('visible', True)
193
+
194
+ # ------------------------------
195
+ # Image Processing Functions
196
+ # ------------------------------
197
+
198
+ def apply_filters(image, filters):
199
+ if filters.get('grayscale'):
200
+ image = ImageOps.grayscale(image).convert("RGBA")
201
+ if filters.get('sepia'):
202
+ sepia_image = ImageOps.colorize(ImageOps.grayscale(image), '#704214', '#C0A080')
203
+ image = sepia_image.convert("RGBA")
204
+ if filters.get('blur'):
205
+ image = image.filter(ImageFilter.GaussianBlur(radius=filters.get('blur_radius', 2)))
206
+ if filters.get('brightness') != 1.0:
207
+ enhancer = ImageEnhance.Brightness(image)
208
+ image = enhancer.enhance(filters['brightness'])
209
+ if filters.get('contrast') != 1.0:
210
+ enhancer = ImageEnhance.Contrast(image)
211
+ image = enhancer.enhance(filters['contrast'])
212
+ return image
213
+
214
+ def auto_enhance(image):
215
+ enhancer = ImageEnhance.Color(image)
216
+ enhanced_image = enhancer.enhance(1.5) # Example enhancement factor
217
+ enhancer = ImageEnhance.Brightness(enhanced_image)
218
+ enhanced_image = enhancer.enhance(1.2)
219
+ enhancer = ImageEnhance.Contrast(enhanced_image)
220
+ enhanced_image = enhancer.enhance(1.3)
221
+ return enhanced_image
222
+
223
+ def remove_background(image):
224
+ img_bytes = io.BytesIO()
225
+ image.save(img_bytes, format='PNG')
226
+ img_bytes = img_bytes.getvalue()
227
+ output = remove(img_bytes)
228
+ new_image = Image.open(io.BytesIO(output)).convert("RGBA")
229
+ return new_image
230
+
231
+ def blend_images(base, overlay, mode):
232
+ if mode == "Multiply":
233
+ return ImageChops.multiply(base, overlay)
234
+ elif mode == "Screen":
235
+ return ImageChops.screen(base, overlay)
236
+ elif mode == "Overlay":
237
+ return ImageChops.overlay(base, overlay)
238
+ else:
239
+ return Image.alpha_composite(base, overlay)
240
+
241
+ # ------------------------------
242
+ # Sidebar Components
243
+ # ------------------------------
244
+
245
+ # 1. Upload Base Image
246
+ st.sidebar.header("1. Upload Base Image")
247
+ uploaded_file = st.sidebar.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
248
+
249
+ # 2. Add a Layer
250
+ st.sidebar.header("2. Add a Layer")
251
+ layer_type = st.sidebar.selectbox("Select Layer Type", ["Text", "Image", "Shape", "Sticker"])
252
+
253
+ if layer_type == "Text":
254
+ text_content = st.sidebar.text_input("Enter Text", "Your text here")
255
+ font_size = st.sidebar.slider("Font Size", 10, 200, 40)
256
+ font_color = st.sidebar.color_picker("Font Color", "#000000")
257
+ font_choice = st.sidebar.selectbox(
258
+ "Select Font",
259
+ list(font_paths.keys())
260
+ )
261
+ selected_font_path = font_paths.get(font_choice, list(font_paths.values())[0])
262
+ x_position = st.sidebar.slider("X Position", 0, 2000, 50)
263
+ y_position = st.sidebar.slider("Y Position", 0, 2000, 50)
264
+ opacity = st.sidebar.slider("Opacity", 0, 100, 100)
265
+ alignment = st.sidebar.selectbox("Text Alignment", ["left", "center", "right"])
266
+ blending_mode = st.sidebar.selectbox("Blending Mode", ["Normal", "Multiply", "Screen", "Overlay"])
267
+
268
+ if st.sidebar.button("Add Text Layer"):
269
+ layer = {
270
+ 'type': 'Text',
271
+ 'content': text_content,
272
+ 'x': x_position,
273
+ 'y': y_position,
274
+ 'font_size': font_size,
275
+ 'font_color': font_color,
276
+ 'font_path': selected_font_path,
277
+ 'opacity': opacity,
278
+ 'visible': True,
279
+ 'alignment': alignment,
280
+ 'blending_mode': blending_mode
281
+ }
282
+ add_layer(layer)
283
+ st.sidebar.success("Text layer added!")
284
+
285
+ elif layer_type == "Image":
286
+ overlay_file = st.sidebar.file_uploader("Upload an image for the layer", type=["jpg", "jpeg", "png"], key="overlay")
287
+ if overlay_file:
288
+ overlay_image = Image.open(overlay_file).convert("RGBA")
289
+ img_width, img_height = overlay_image.size
290
+ max_width = st.sidebar.slider("Width", 10, 2000, img_width)
291
+ max_height = st.sidebar.slider("Height", 10, 2000, img_height)
292
+ overlay_image = overlay_image.resize((max_width, max_height))
293
+ x_position = st.sidebar.slider("X Position", 0, 2000, 50)
294
+ y_position = st.sidebar.slider("Y Position", 0, 2000, 50)
295
+ opacity = st.sidebar.slider("Opacity", 0, 100, 100)
296
+ rotation = st.sidebar.slider("Rotation (degrees)", 0, 360, 0)
297
+ blending_mode = st.sidebar.selectbox("Blending Mode", ["Normal", "Multiply", "Screen", "Overlay"])
298
+
299
+ if st.sidebar.button("Add Image Layer"):
300
+ overlay_image = overlay_image.rotate(rotation, expand=True)
301
+ layer = {
302
+ 'type': 'Image',
303
+ 'content': overlay_image,
304
+ 'x': x_position,
305
+ 'y': y_position,
306
+ 'opacity': opacity,
307
+ 'visible': True,
308
+ 'blending_mode': blending_mode
309
+ }
310
+ add_layer(layer)
311
+ st.sidebar.success("Image layer added!")
312
+
313
+ elif layer_type == "Shape":
314
+ shape_type = st.sidebar.selectbox("Shape Type", ["Rectangle", "Circle", "Line"])
315
+ shape_color = st.sidebar.color_picker("Shape Color", "#FF0000")
316
+ x1 = st.sidebar.slider("Start X", 0, 2000, 100)
317
+ y1 = st.sidebar.slider("Start Y", 0, 2000, 100)
318
+ x2 = st.sidebar.slider("End X", 0, 2000, 300)
319
+ y2 = st.sidebar.slider("End Y", 0, 2000, 300)
320
+ thickness = st.sidebar.slider("Thickness", 1, 50, 5)
321
+ opacity = st.sidebar.slider("Opacity", 0, 100, 100)
322
+ blending_mode = st.sidebar.selectbox("Blending Mode", ["Normal", "Multiply", "Screen", "Overlay"])
323
+
324
+ if st.sidebar.button("Add Shape Layer"):
325
+ layer = {
326
+ 'type': 'Shape',
327
+ 'shape': shape_type,
328
+ 'color': shape_color,
329
+ 'coordinates': (x1, y1, x2, y2),
330
+ 'thickness': thickness,
331
+ 'opacity': opacity,
332
+ 'visible': True,
333
+ 'blending_mode': blending_mode
334
+ }
335
+ add_layer(layer)
336
+ st.sidebar.success("Shape layer added!")
337
+
338
+ elif layer_type == "Sticker":
339
+ sticker_options = ["Star", "Heart", "Smile"]
340
+ sticker = st.sidebar.selectbox("Select Sticker", sticker_options)
341
+ sticker_path = Path(f"stickers/{sticker}.png")
342
+ if sticker_path.exists():
343
+ sticker_image = Image.open(sticker_path).convert("RGBA")
344
+ img_width, img_height = sticker_image.size
345
+ max_width = st.sidebar.slider("Width", 10, 500, img_width)
346
+ max_height = st.sidebar.slider("Height", 10, 500, img_height)
347
+ sticker_image = sticker_image.resize((max_width, max_height))
348
+ x_position = st.sidebar.slider("X Position", 0, 2000, 50)
349
+ y_position = st.sidebar.slider("Y Position", 0, 2000, 50)
350
+ opacity = st.sidebar.slider("Opacity", 0, 100, 100)
351
+ rotation = st.sidebar.slider("Rotation (degrees)", 0, 360, 0)
352
+ blending_mode = st.sidebar.selectbox("Blending Mode", ["Normal", "Multiply", "Screen", "Overlay"])
353
+
354
+ if st.sidebar.button("Add Sticker Layer"):
355
+ sticker_image = sticker_image.rotate(rotation, expand=True)
356
+ layer = {
357
+ 'type': 'Sticker',
358
+ 'content': sticker_image,
359
+ 'x': x_position,
360
+ 'y': y_position,
361
+ 'opacity': opacity,
362
+ 'visible': True,
363
+ 'blending_mode': blending_mode
364
+ }
365
+ add_layer(layer)
366
+ st.sidebar.success("Sticker layer added!")
367
+ else:
368
+ st.sidebar.error("Sticker image not found.")
369
+
370
+ # 3. Manage Layers
371
+ st.sidebar.header("3. Manage Layers")
372
+ if st.session_state['layers']:
373
+ st.sidebar.subheader("Layers")
374
+ for idx, layer in enumerate(reversed(st.session_state['layers'])):
375
+ layer_num = len(st.session_state['layers']) - idx
376
+ with st.sidebar.expander(f"Layer {layer_num} ({layer['type']})"):
377
+ visibility = st.checkbox("Visible", value=layer.get('visible', True), key=f"visibility_{idx}")
378
+ if visibility != layer.get('visible', True):
379
+ toggle_visibility(len(st.session_state['layers']) - idx - 1)
380
+ if st.button("Remove", key=f"remove_{idx}"):
381
+ remove_layer(len(st.session_state['layers']) - idx - 1)
382
+ # Reordering
383
+ new_order = st.selectbox(
384
+ "Move to position",
385
+ options=list(range(1, len(st.session_state['layers'])+1)),
386
+ index=len(st.session_state['layers'])-idx-1,
387
+ key=f"move_{idx}"
388
+ )
389
+ if new_order != (len(st.session_state['layers']) - idx):
390
+ reorder_layers(len(st.session_state['layers']) - idx - 1, new_order - 1)
391
+
392
+ # 4. History (Undo/Redo)
393
+ st.sidebar.header("4. History")
394
+ col1, col2 = st.sidebar.columns(2)
395
+ with col1:
396
+ if st.sidebar.button("Undo"):
397
+ undo()
398
+ with col2:
399
+ if st.sidebar.button("Redo"):
400
+ redo()
401
+
402
+ # 5. Filters & Adjustments
403
+ st.sidebar.header("5. Filters & Adjustments")
404
+ apply_grayscale = st.sidebar.checkbox("Grayscale")
405
+ apply_sepia = st.sidebar.checkbox("Sepia")
406
+ apply_blur = st.sidebar.checkbox("Blur")
407
+ blur_radius = st.sidebar.slider("Blur Radius", 0.0, 10.0, 2.0)
408
+ brightness = st.sidebar.slider("Brightness", 0.5, 2.0, 1.0)
409
+ contrast = st.sidebar.slider("Contrast", 0.5, 2.0, 1.0)
410
+ apply_auto_enhance = st.sidebar.checkbox("Auto Enhance")
411
+ remove_bg = st.sidebar.checkbox("Remove Background")
412
+
413
+ filters = {
414
+ 'grayscale': apply_grayscale,
415
+ 'sepia': apply_sepia,
416
+ 'blur': apply_blur,
417
+ 'blur_radius': blur_radius,
418
+ 'brightness': brightness,
419
+ 'contrast': contrast
420
+ }
421
+
422
+ # 6. Advanced Tools
423
+ st.sidebar.header("6. Advanced Tools")
424
+ if st.sidebar.button("Remove Background"):
425
+ if uploaded_file:
426
+ try:
427
+ base_image = Image.open(uploaded_file).convert("RGBA")
428
+ canvas = remove_background(base_image)
429
+ st.session_state['layers'] = [] # Clear existing layers
430
+ st.success("Background removed successfully!")
431
+ except Exception as e:
432
+ st.error(f"Background removal failed: {e}")
433
+ else:
434
+ st.warning("Please upload an image first.")
435
+
436
+ # 7. Save/Load Project
437
+ st.sidebar.header("7. Save/Load Project")
438
+ project_name = st.sidebar.text_input("Project Name")
439
+ if st.sidebar.button("Save Project") and project_name:
440
+ projects_dir = Path("projects")
441
+ projects_dir.mkdir(exist_ok=True)
442
+ project_path = projects_dir / f"{project_name}.json"
443
+ try:
444
+ with open(project_path, "w") as f:
445
+ json.dump(st.session_state['layers'], f)
446
+ st.sidebar.success(f"Project '{project_name}' saved!")
447
+ except Exception as e:
448
+ st.sidebar.error(f"Failed to save project: {e}")
449
+
450
+ load_project = st.sidebar.file_uploader("Load Project", type=["json"], key="load_project")
451
+ if load_project:
452
+ try:
453
+ loaded_layers = json.load(load_project)
454
+ st.session_state['layers'] = loaded_layers
455
+ st.sidebar.success("Project loaded successfully!")
456
+ except Exception as e:
457
+ st.sidebar.error(f"Failed to load project: {e}")
458
+
459
+ # ------------------------------
460
+ # Main Area: Display and Edit Image
461
+ # ------------------------------
462
+
463
+ if uploaded_file:
464
+ base_image = Image.open(uploaded_file).convert("RGBA")
465
+ canvas = base_image.copy()
466
+
467
+ # Apply auto enhance if selected
468
+ if apply_auto_enhance:
469
+ canvas = auto_enhance(canvas)
470
+
471
+ # Initialize drawing context
472
+ draw = ImageDraw.Draw(canvas, 'RGBA')
473
+
474
+ for layer in st.session_state['layers']:
475
+ if not layer.get('visible', True):
476
+ continue
477
+ if layer['type'] == "Text":
478
+ try:
479
+ font = ImageFont.truetype(layer['font_path'], layer['font_size'])
480
+ except IOError:
481
+ font = ImageFont.load_default()
482
+ st.warning(f"Font not found: {layer['font_path']}. Using default font.")
483
+ text_color = layer['font_color']
484
+ text_opacity = int(255 * (layer.get('opacity', 100) / 100))
485
+ try:
486
+ text_color_rgba = ImageColor.getcolor(text_color, "RGBA")
487
+ except ValueError:
488
+ text_color_rgba = (0, 0, 0, text_opacity)
489
+ text_color_rgba = text_color_rgba[:3] + (text_opacity,)
490
+ text_layer = Image.new('RGBA', canvas.size, (255,255,255,0))
491
+ text_draw = ImageDraw.Draw(text_layer)
492
+ alignment = layer.get('alignment', 'left')
493
+ text_position = (layer['x'], layer['y'])
494
+ text_draw.text(text_position, layer['content'], fill=text_color_rgba, font=font, align=alignment)
495
+ if layer.get('blending_mode') and layer['blending_mode'] != "Normal":
496
+ canvas = blend_images(canvas, text_layer, layer['blending_mode'])
497
+ else:
498
+ canvas = Image.alpha_composite(canvas, text_layer)
499
+ elif layer['type'] in ["Image", "Sticker"]:
500
+ overlay = layer['content'].copy()
501
+ opacity = layer.get('opacity', 100)
502
+ if opacity < 100:
503
+ alpha = overlay.split()[3]
504
+ alpha = alpha.point(lambda p: p * opacity / 100)
505
+ overlay.putalpha(alpha)
506
+ if layer.get('blending_mode') and layer['blending_mode'] != "Normal":
507
+ canvas = blend_images(canvas, overlay, layer['blending_mode'])
508
+ else:
509
+ canvas.paste(overlay, (layer['x'], layer['y']), overlay)
510
+ elif layer['type'] == "Shape":
511
+ shape_layer = Image.new('RGBA', canvas.size, (255,255,255,0))
512
+ shape_draw = ImageDraw.Draw(shape_layer)
513
+ color = layer['color']
514
+ opacity = layer.get('opacity', 100)
515
+ try:
516
+ shape_color_rgba = ImageColor.getcolor(color, "RGBA")
517
+ except ValueError:
518
+ shape_color_rgba = (255, 0, 0, int(255 * (opacity / 100)))
519
+ shape_color_rgba = shape_color_rgba[:3] + (int(255 * (opacity / 100)),)
520
+ x1, y1, x2, y2 = layer['coordinates']
521
+ thickness = layer['thickness']
522
+ if layer['shape'] == "Rectangle":
523
+ shape_draw.rectangle([x1, y1, x2, y2], outline=shape_color_rgba, width=thickness)
524
+ elif layer['shape'] == "Circle":
525
+ shape_draw.ellipse([x1, y1, x2, y2], outline=shape_color_rgba, width=thickness)
526
+ elif layer['shape'] == "Line":
527
+ shape_draw.line([x1, y1, x2, y2], fill=shape_color_rgba, width=thickness)
528
+ if layer.get('blending_mode') and layer['blending_mode'] != "Normal":
529
+ canvas = blend_images(canvas, shape_layer, layer['blending_mode'])
530
+ else:
531
+ canvas = Image.alpha_composite(canvas, shape_layer)
532
+
533
+ # Apply filters
534
+ canvas = apply_filters(canvas, filters)
535
+
536
+ # Remove background if selected
537
+ if remove_bg:
538
+ try:
539
+ canvas = remove_background(canvas)
540
+ st.success("Background removed successfully!")
541
+ except Exception as e:
542
+ st.error(f"Background removal failed: {e}")
543
+
544
+ # Display the final image
545
+ st.image(canvas, caption="Edited Image", use_column_width=True)
546
+
547
+ # Download options
548
+ buffer = io.BytesIO()
549
+ canvas.save(buffer, format="PNG")
550
+ st.download_button(
551
+ label="📥 Download Edited Image",
552
+ data=buffer.getvalue(),
553
+ file_name="edited_image.png",
554
+ mime="image/png"
555
+ )
556
+
557
+ else:
558
+ st.warning("Please upload an image to start editing.")