longshiine commited on
Commit
80bf838
·
1 Parent(s): aa20204

feat: single mode

Browse files

Signed-off-by: longshiine <[email protected]>

Files changed (3) hide show
  1. app.py +237 -3
  2. links.txt +10 -0
  3. requirements.txt +82 -0
app.py CHANGED
@@ -1,7 +1,241 @@
 
1
  import gradio as gr
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
  demo.launch()
 
1
+ import requests
2
  import gradio as gr
3
+ import zipfile
4
+ from PIL import Image
5
+ from io import BytesIO
6
+ from rembg import remove
7
 
8
+ def download_image(image_url: str) -> Image.Image:
9
+ # 이미지 다운로드
10
+ response = requests.get(image_url)
11
+
12
+ if response.status_code == 200:
13
+ original_image = Image.open(BytesIO(response.content))
14
+ return original_image
15
+ else:
16
+ raise Exception(f"Failed to download image. Status code: {response.status_code}")
17
+
18
+ def remove_background(image: Image.Image) -> Image.Image:
19
+ # 이미지 누끼따기
20
+ try:
21
+ removebg_image = remove(
22
+ image,
23
+ post_process_mask=True,
24
+ alpha_matting=True,
25
+ alpha_matting_foreground_threshold=270,
26
+ alpha_matting_background_threshold=30,
27
+ alpha_matting_erode_size=15)
28
+ return removebg_image
29
+
30
+ except Exception as e:
31
+ print(f"Failed to remove background: {e}")
32
+ return None
33
+
34
+ def crop_image(image: Image.Image) -> Image.Image:
35
+ # 이미지 크롭
36
+ try:
37
+ # 알파 채널을 사용하여 이미지의 경계 영역 찾기
38
+ bbox = image.getbbox()
39
+ if bbox:
40
+ # 경계 상자로 이미지 크롭
41
+ cropped_image = image.crop(bbox)
42
+ return cropped_image
43
+ else:
44
+ print("No bounding box found.")
45
+ return image
46
+
47
+ except Exception as e:
48
+ print(f"Failed to crop image: {e}")
49
+ return None
50
+
51
+ def resize_image(image: Image.Image, max_size: int) -> Image.Image:
52
+ # 이미지 크기 조정
53
+ try:
54
+ # 이미지의 현재 너비와 높이 가져오기
55
+ width, height = image.size
56
+
57
+ # 너비와 높이 중 더 큰 쪽의 비율에 맞춰 크기를 조정
58
+ if width > height:
59
+ new_width = max_size
60
+ new_height = int((max_size / width) * height)
61
+ else:
62
+ new_height = max_size
63
+ new_width = int((max_size / height) * width)
64
+
65
+ resized_image = image.resize((new_width, new_height))
66
+ return resized_image
67
+
68
+ except Exception as e:
69
+ print(f"Failed to resize image: {e}")
70
+ return None
71
+
72
+ def paste_to_background_type_a(background: Image.Image, product: Image.Image) -> Image.Image:
73
+ # 배경에 제품 이미지 합성
74
+ try:
75
+ # 배경 이미지 크기 가져오기
76
+ bg_width, bg_height = background.size
77
+
78
+ # 제품 이미지 크기 가져오기
79
+ product_width, product_height = product.size
80
+
81
+ # 제품 이미지를 배경 이미지 중앙에 위치시키기
82
+ offset = ((bg_width - product_width) // 2, (bg_height - product_height) // 2)
83
+
84
+ # 알파 채널을 고려하여 합성
85
+ background.paste(product, offset, mask=product)
86
+ return background
87
+
88
+ except Exception as e:
89
+ print(f"Failed to paste product image to background: {e}")
90
+ return None
91
+
92
+ def paste_to_background_type_b(background: Image.Image, product: Image.Image, margin: int = 10) -> Image.Image:
93
+ try:
94
+ # 배경 이미지 크기 가져오기
95
+ bg_width, bg_height = background.size
96
+
97
+ # 제품 이미지 크기 가져오기
98
+ product_width, product_height = product.size
99
+
100
+ # 두 제품 이미지를 위한 전체 너비 계산 (제품 이미지 두 개 + 마진)
101
+ total_width = (product_width * 2) + margin
102
+
103
+ if total_width > bg_width:
104
+ raise ValueError("Background is too narrow to fit two product images with the specified margin.")
105
+
106
+ # 첫 번째 제품 이미지의 왼쪽 상단 좌표 계산
107
+ left_offset = (bg_width - total_width) // 2
108
+ top_offset = (bg_height - product_height) // 2
109
+
110
+ # 두 번째 제품 이미지의 왼쪽 상단 좌표 계산
111
+ right_offset = left_offset + product_width + margin
112
+
113
+ # 첫 번째 제품 이미지 배경에 합성
114
+ background.paste(product, (left_offset, top_offset), mask=product)
115
+
116
+ # 두 번째 제품 이미지 배경에 합성
117
+ background.paste(product, (right_offset, top_offset), mask=product)
118
+ return background
119
+
120
+ except Exception as e:
121
+ print(f"Failed to paste product images to background: {e}")
122
+ return None
123
+
124
+ def paste_to_background_type_c(background: Image.Image, product: Image.Image, margin: int = 10, top_margin: int = 15) -> Image.Image:
125
+ try:
126
+ # 배경 이미지 크기 가져오기
127
+ bg_width, bg_height = background.size
128
+
129
+ # 제품 이미지 크기 가져오기
130
+ product_width, product_height = product.size
131
+
132
+ # 먼저 type_b 형태로 아래 두 제품 이미지를 배치
133
+ background_with_two_products = paste_to_background_type_b(background, product, margin)
134
+
135
+ # 중앙 상단에 위치할 제품 이미지의 오프셋 계산
136
+ center_offset_x = (bg_width - product_width) // 2
137
+ center_offset_y = ((bg_height - product_height) // 2) + top_margin
138
+
139
+ if center_offset_y < 0:
140
+ raise ValueError("Background is too small to fit three product images with the specified top margin.")
141
+
142
+ # 세 번째 제품 이미지 배경에 합성 (중앙 상단)
143
+ background_with_two_products.paste(product, (center_offset_x, center_offset_y), mask=product)
144
+
145
+ # 결과 이미지 저장 및 반환
146
+ return background_with_two_products
147
+
148
+ except Exception as e:
149
+ print(f"Failed to paste product images to background: {e}")
150
+ return None
151
+
152
+ def create_zip_file(images: list, zip_filename: str = "images.zip") -> bytes:
153
+ # 메모리 내에서 ZIP 파일 생성
154
+ zip_buffer = BytesIO()
155
+
156
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
157
+ for i, image in enumerate(images):
158
+ # 이미지를 메모리 버퍼에 저장
159
+ image_buffer = BytesIO()
160
+ image.save(image_buffer, format="PNG")
161
+ image_buffer.seek(0)
162
+
163
+ # 버퍼 내용을 ZIP 파일에 추가
164
+ zipf.writestr(f"image_{i + 1}.png", image_buffer.getvalue())
165
+
166
+ # ZIP 파일 데이터를 반환
167
+ zip_buffer.seek(0)
168
+ return zip_buffer.getvalue()
169
+
170
+ def image_processing_single(background_image: Image.Image, product_image_url: str):
171
+ # 각종 설정 값
172
+ product_image_size = 650 # 배경이 제거된 제품 이미지의 크기
173
+ type_b_margin = 15
174
+ type_c_margin_1, type_c_margin_2 = 15, 45 # (1=가운데 두개의 마진, 2= 중앙 한개의 top 마진)
175
+
176
+ # 이미지 다운로드
177
+ original_image = download_image(product_image_url)
178
+
179
+ # 이미지 누끼따기
180
+ removebg_image = remove_background(original_image)
181
+
182
+ # 이미지 크롭
183
+ cropped_image = crop_image(removebg_image)
184
+
185
+ # 크롭된 이미지 원하는 사이즈로 resize
186
+ resized_image = resize_image(cropped_image, product_image_size)
187
+
188
+ # type_a 합성
189
+ type_a_image = paste_to_background_type_a(background_image.copy(), resized_image)
190
+ type_b_image = paste_to_background_type_b(background_image.copy(), resized_image, type_b_margin)
191
+ type_c_image = paste_to_background_type_c(background_image.copy(), resized_image, type_c_margin_1, type_c_margin_2)
192
+
193
+ # 결과 이미지 반환
194
+ image_list = [type_a_image, type_b_image, type_c_image]
195
+ image_zip_file = create_zip_file(image_list)
196
+
197
+ return image_list #, image_zip_file
198
+
199
+ def image_processing_multi(background_image: Image.Image, product_image_url_list: list):
200
+ # 각종 설정 값
201
+ product_image_size = 650 # 배경이 제거된 제품 이미지의 크기
202
+ type_b_margin = 15
203
+ type_c_margin_1, type_c_margin_2 = 15, 45 # (1=가운데 두개의 마진, 2= 중앙 한개의 top 마진)
204
+
205
+ for idx, product_image_url in enumerate(product_image_url_list):
206
+ # 이미지 다운로드
207
+ original_image = download_image(product_image_url)
208
+
209
+ # 이미지 누끼따기
210
+ removebg_image = remove_background(original_image)
211
+
212
+ # 이미지 크롭
213
+ cropped_image = crop_image(removebg_image)
214
+
215
+ # 크롭된 이미지 원하는 사이즈로 resize
216
+ resized_image = resize_image(cropped_image, product_image_size)
217
+
218
+ # type_a 합성
219
+ type_a_image = paste_to_background_type_a(background_image.copy(), resized_image)
220
+ type_b_image = paste_to_background_type_b(background_image.copy(), resized_image, type_b_margin)
221
+ type_c_image = paste_to_background_type_c(background_image.copy(), resized_image, type_c_margin_1, type_c_margin_2)
222
+
223
+
224
+ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
225
+ with gr.Row():
226
+ background_image = gr.Image(label="Background Image", type="pil")
227
+ with gr.Tab("Single"):
228
+ link = gr.Textbox(label="Image URL")
229
+ btn_single = gr.Button("Generate Images")
230
+ with gr.Tab("Multi"):
231
+ links = gr.File(label="Image URLs (.txt file)")
232
+ btn_multi = gr.Button("Generate Images")
233
+
234
+ with gr.Row():
235
+ preview = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery", columns=[3], rows=[1], object_fit="contain", height="auto")
236
+ output_zip = gr.File(label="Download Result Zip File")
237
+
238
+ # evnets
239
+ btn_single.click(fn=image_processing_single, inputs=[background_image, link], outputs=[preview], api_name="image_processing")
240
 
 
241
  demo.launch()
links.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/drb/drb00370/v/67.jpg,
2
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/cgn/cgn01206/l/73.jpg,
3
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/sre/sre01256/l/96.jpg,
4
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/lex/lex19936/v/115.jpg,
5
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/cey/cey66577/v/6.jpg,
6
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/nor/nor01844/v/39.jpg,
7
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/swv/swv06072/v/8.jpg,
8
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/age/age00855/v/40.jpg,
9
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/nhi/nhi03515/v/41.jpg,
10
+ https://cloudinary.images-iherb.com/image/upload/f_auto,q_auto:eco/images/nhi/nhi03512/v/49.jpg,
requirements.txt ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ annotated-types==0.7.0
3
+ anyio==4.6.0
4
+ attrs==24.2.0
5
+ certifi==2024.8.30
6
+ charset-normalizer==3.3.2
7
+ click==8.1.7
8
+ coloredlogs==15.0.1
9
+ contourpy==1.3.0
10
+ cycler==0.12.1
11
+ fastapi==0.115.0
12
+ ffmpy==0.4.0
13
+ filelock==3.16.1
14
+ flatbuffers==24.3.25
15
+ fonttools==4.53.1
16
+ fsspec==2024.9.0
17
+ gradio==4.44.0
18
+ gradio_client==1.3.0
19
+ h11==0.14.0
20
+ httpcore==1.0.5
21
+ httpx==0.27.2
22
+ huggingface-hub==0.25.0
23
+ humanfriendly==10.0
24
+ idna==3.10
25
+ imageio==2.35.1
26
+ importlib_resources==6.4.5
27
+ Jinja2==3.1.4
28
+ jsonschema==4.23.0
29
+ jsonschema-specifications==2023.12.1
30
+ kiwisolver==1.4.7
31
+ lazy_loader==0.4
32
+ llvmlite==0.43.0
33
+ markdown-it-py==3.0.0
34
+ MarkupSafe==2.1.5
35
+ matplotlib==3.9.2
36
+ mdurl==0.1.2
37
+ mpmath==1.3.0
38
+ networkx==3.3
39
+ numba==0.60.0
40
+ numpy==2.0.2
41
+ onnxruntime==1.19.2
42
+ opencv-python-headless==4.10.0.84
43
+ orjson==3.10.7
44
+ packaging==24.1
45
+ pandas==2.2.3
46
+ pillow==10.4.0
47
+ platformdirs==4.3.6
48
+ pooch==1.8.2
49
+ protobuf==5.28.2
50
+ pydantic==2.9.2
51
+ pydantic_core==2.23.4
52
+ pydub==0.25.1
53
+ Pygments==2.18.0
54
+ PyMatting==1.1.12
55
+ pyparsing==3.1.4
56
+ python-dateutil==2.9.0.post0
57
+ python-multipart==0.0.9
58
+ pytz==2024.2
59
+ PyYAML==6.0.2
60
+ referencing==0.35.1
61
+ rembg==2.0.59
62
+ requests==2.32.3
63
+ rich==13.8.1
64
+ rpds-py==0.20.0
65
+ ruff==0.6.6
66
+ scikit-image==0.24.0
67
+ scipy==1.14.1
68
+ semantic-version==2.10.0
69
+ shellingham==1.5.4
70
+ six==1.16.0
71
+ sniffio==1.3.1
72
+ starlette==0.38.5
73
+ sympy==1.13.3
74
+ tifffile==2024.9.20
75
+ tomlkit==0.12.0
76
+ tqdm==4.66.5
77
+ typer==0.12.5
78
+ typing_extensions==4.12.2
79
+ tzdata==2024.1
80
+ urllib3==2.2.3
81
+ uvicorn==0.30.6
82
+ websockets==12.0