openfree commited on
Commit
234479f
·
verified ·
1 Parent(s): 1c9e93d

Delete app-backup2.py

Browse files
Files changed (1) hide show
  1. app-backup2.py +0 -558
app-backup2.py DELETED
@@ -1,558 +0,0 @@
1
- import gradio as gr
2
- import spaces
3
- import torch
4
- from diffusers import AutoencoderKL, TCDScheduler
5
- from diffusers.models.model_loading_utils import load_state_dict
6
- from gradio_imageslider import ImageSlider
7
- from huggingface_hub import hf_hub_download
8
-
9
- from controlnet_union import ControlNetModel_Union
10
- from pipeline_fill_sd_xl import StableDiffusionXLFillPipeline
11
-
12
- from PIL import Image, ImageDraw
13
- import numpy as np
14
-
15
- import json
16
- import os
17
- import subprocess
18
- import requests
19
- from transformers import pipeline
20
-
21
-
22
- config_file = hf_hub_download(
23
- "xinsir/controlnet-union-sdxl-1.0",
24
- filename="config_promax.json",
25
- )
26
-
27
- config = ControlNetModel_Union.load_config(config_file)
28
- controlnet_model = ControlNetModel_Union.from_config(config)
29
- model_file = hf_hub_download(
30
- "xinsir/controlnet-union-sdxl-1.0",
31
- filename="diffusion_pytorch_model_promax.safetensors",
32
- )
33
- state_dict = load_state_dict(model_file)
34
- model, _, _, _, _ = ControlNetModel_Union._load_pretrained_model(
35
- controlnet_model, state_dict, model_file, "xinsir/controlnet-union-sdxl-1.0"
36
- )
37
- model.to(device="cuda", dtype=torch.float16)
38
-
39
- vae = AutoencoderKL.from_pretrained(
40
- "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16
41
- ).to("cuda")
42
-
43
- pipe = StableDiffusionXLFillPipeline.from_pretrained(
44
- "SG161222/RealVisXL_V5.0_Lightning",
45
- torch_dtype=torch.float16,
46
- vae=vae,
47
- controlnet=model,
48
- variant="fp16",
49
- ).to("cuda")
50
-
51
- pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
52
-
53
- # 새로운 코드 추가
54
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
55
- PIXABAY_API_KEY = "33492762-a28a596ec4f286f84cd328b17"
56
- PIXABAY_API_URL = "https://pixabay.com/api/"
57
- PIXABAY_VIDEO_API_URL = "https://pixabay.com/api/videos/"
58
-
59
- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
60
-
61
- def load_json_data(json_file='gallery_data.json'):
62
- json_path = os.path.join(BASE_DIR, json_file)
63
- with open(json_path, 'r', encoding='utf-8') as f:
64
- return json.load(f)
65
-
66
- def create_thumbnail(video_path, output_path):
67
- command = [
68
- 'ffmpeg', '-i', video_path,
69
- '-ss', '00:00:01.000',
70
- '-vframes', '1',
71
- output_path
72
- ]
73
- subprocess.run(command, check=True)
74
-
75
- def create_gallery_item(prompt, filename):
76
- video_path = os.path.join(BASE_DIR, filename)
77
- thumbnail_path = os.path.join(BASE_DIR, 'thumbnails', f"{os.path.splitext(filename)[0]}.jpg")
78
-
79
- thumbnails_dir = os.path.join(BASE_DIR, 'thumbnails')
80
- if not os.path.exists(thumbnails_dir):
81
- os.makedirs(thumbnails_dir)
82
-
83
- if not os.path.exists(thumbnail_path):
84
- create_thumbnail(video_path, thumbnail_path)
85
-
86
- return (thumbnail_path, prompt)
87
-
88
- def translate_to_english(text):
89
- translated = translator(text, max_length=40)
90
- return translated[0]['translation_text']
91
-
92
- def search_images(keyword):
93
- params = {
94
- "key": PIXABAY_API_KEY,
95
- "q": keyword,
96
- "per_page": 80
97
- }
98
- response = requests.get(PIXABAY_API_URL, params=params)
99
- if response.status_code == 200:
100
- return response.json()
101
- else:
102
- print(f"Pixabay API error: {response.status_code}, {response.text}")
103
- return None
104
-
105
- def display_images(keyword):
106
- if not keyword:
107
- return "키워드를 입력해주세요."
108
-
109
- if any('\u3131' <= char <= '\u3163' or '\uac00' <= char <= '\ud7a3' for char in keyword):
110
- keyword = translate_to_english(keyword)
111
-
112
- images = search_images(keyword)
113
-
114
- if not images or 'hits' not in images or not images['hits']:
115
- return "검색 결과가 없습니다."
116
-
117
- html = "<div style='display: flex; flex-wrap: wrap; gap: 10px;'>"
118
- for image in images['hits']:
119
- html += f"<img src='{image['webformatURL']}' style='width: 200px; height: 150px; object-fit: cover;'>"
120
- html += "</div>"
121
-
122
- return html
123
-
124
- def search_videos(keyword):
125
- params = {
126
- "key": PIXABAY_API_KEY,
127
- "q": keyword,
128
- "per_page": 80
129
- }
130
- response = requests.get(PIXABAY_VIDEO_API_URL, params=params)
131
- if response.status_code == 200:
132
- return response.json()
133
- else:
134
- print(f"Pixabay API error: {response.status_code}, {response.text}")
135
- return None
136
-
137
- def display_videos(keyword):
138
- if not keyword:
139
- return "키워드를 입력해주세요."
140
-
141
- if any('\u3131' <= char <= '\u3163' or '\uac00' <= char <= '\ud7a3' for char in keyword):
142
- keyword = translate_to_english(keyword)
143
-
144
- videos = search_videos(keyword)
145
-
146
- if not videos or 'hits' not in videos or not videos['hits']:
147
- return "검색 결과가 없습니다."
148
-
149
- html = "<div style='display: flex; flex-wrap: wrap; gap: 10px;'>"
150
- for video in videos['hits']:
151
- video_url = video['videos']['medium']['url']
152
- html += f"""
153
- <div style='width: 300px; margin-bottom: 20px;'>
154
- <video width='300' height='200' controls>
155
- <source src='{video_url}' type='video/mp4'>
156
- </video>
157
- </div>
158
- """
159
- html += "</div>"
160
-
161
- return html
162
-
163
- css = """
164
- footer {
165
- visibility: hidden;
166
- }
167
- .tab-nav button {
168
- color: #7FFFD4 !important;
169
- }
170
- .tab-nav button.selected {
171
- color: #FFFF00 !important;
172
- border-color: #FFFF00 !important;
173
- }
174
- """
175
-
176
-
177
- def can_expand(source_width, source_height, target_width, target_height, alignment):
178
- """Checks if the image can be expanded based on the alignment."""
179
- if alignment in ("Left", "Right") and source_width >= target_width:
180
- return False
181
- if alignment in ("Top", "Bottom") and source_height >= target_height:
182
- return False
183
- return True
184
-
185
- @spaces.GPU(duration=24)
186
- def infer(image, width, height, overlap_width, num_inference_steps, resize_option, custom_resize_size, prompt_input=None, alignment="Middle"):
187
- source = image
188
- target_size = (width, height)
189
- overlap = overlap_width
190
-
191
- # Upscale if source is smaller than target in both dimensions
192
- if source.width < target_size[0] and source.height < target_size[1]:
193
- scale_factor = min(target_size[0] / source.width, target_size[1] / source.height)
194
- new_width = int(source.width * scale_factor)
195
- new_height = int(source.height * scale_factor)
196
- source = source.resize((new_width, new_height), Image.LANCZOS)
197
-
198
- if source.width > target_size[0] or source.height > target_size[1]:
199
- scale_factor = min(target_size[0] / source.width, target_size[1] / source.height)
200
- new_width = int(source.width * scale_factor)
201
- new_height = int(source.height * scale_factor)
202
- source = source.resize((new_width, new_height), Image.LANCZOS)
203
-
204
- if resize_option == "Full":
205
- resize_size = max(source.width, source.height)
206
- elif resize_option == "1/2":
207
- resize_size = max(source.width, source.height) // 2
208
- elif resize_option == "1/3":
209
- resize_size = max(source.width, source.height) // 3
210
- elif resize_option == "1/4":
211
- resize_size = max(source.width, source.height) // 4
212
- else: # Custom
213
- resize_size = custom_resize_size
214
-
215
- aspect_ratio = source.height / source.width
216
- new_width = resize_size
217
- new_height = int(resize_size * aspect_ratio)
218
- source = source.resize((new_width, new_height), Image.LANCZOS)
219
-
220
- if not can_expand(source.width, source.height, target_size[0], target_size[1], alignment):
221
- alignment = "Middle"
222
-
223
- # Calculate margins based on alignment
224
- if alignment == "Middle":
225
- margin_x = (target_size[0] - source.width) // 2
226
- margin_y = (target_size[1] - source.height) // 2
227
- elif alignment == "Left":
228
- margin_x = 0
229
- margin_y = (target_size[1] - source.height) // 2
230
- elif alignment == "Right":
231
- margin_x = target_size[0] - source.width
232
- margin_y = (target_size[1] - source.height) // 2
233
- elif alignment == "Top":
234
- margin_x = (target_size[0] - source.width) // 2
235
- margin_y = 0
236
- elif alignment == "Bottom":
237
- margin_x = (target_size[0] - source.width) // 2
238
- margin_y = target_size[1] - source.height
239
-
240
- background = Image.new('RGB', target_size, (255, 255, 255))
241
- background.paste(source, (margin_x, margin_y))
242
-
243
- mask = Image.new('L', target_size, 255)
244
- mask_draw = ImageDraw.Draw(mask)
245
-
246
- # Adjust mask generation based on alignment
247
- if alignment == "Middle":
248
- mask_draw.rectangle([
249
- (margin_x + overlap, margin_y + overlap),
250
- (margin_x + source.width - overlap, margin_y + source.height - overlap)
251
- ], fill=0)
252
- elif alignment == "Left":
253
- mask_draw.rectangle([
254
- (margin_x, margin_y),
255
- (margin_x + source.width - overlap, margin_y + source.height)
256
- ], fill=0)
257
- elif alignment == "Right":
258
- mask_draw.rectangle([
259
- (margin_x + overlap, margin_y),
260
- (margin_x + source.width, margin_y + source.height)
261
- ], fill=0)
262
- elif alignment == "Top":
263
- mask_draw.rectangle([
264
- (margin_x, margin_y),
265
- (margin_x + source.width, margin_y + source.height - overlap)
266
- ], fill=0)
267
- elif alignment == "Bottom":
268
- mask_draw.rectangle([
269
- (margin_x, margin_y + overlap),
270
- (margin_x + source.width, margin_y + source.height)
271
- ], fill=0)
272
-
273
- cnet_image = background.copy()
274
- cnet_image.paste(0, (0, 0), mask)
275
-
276
- final_prompt = f"{prompt_input} , high quality, 4k"
277
-
278
- (
279
- prompt_embeds,
280
- negative_prompt_embeds,
281
- pooled_prompt_embeds,
282
- negative_pooled_prompt_embeds,
283
- ) = pipe.encode_prompt(final_prompt, "cuda", True)
284
-
285
- for image in pipe(
286
- prompt_embeds=prompt_embeds,
287
- negative_prompt_embeds=negative_prompt_embeds,
288
- pooled_prompt_embeds=pooled_prompt_embeds,
289
- negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
290
- image=cnet_image,
291
- num_inference_steps=num_inference_steps
292
- ):
293
- yield cnet_image, image
294
-
295
- image = image.convert("RGBA")
296
- cnet_image.paste(image, (0, 0), mask)
297
-
298
- yield background, cnet_image
299
-
300
- def clear_result():
301
- """Clears the result ImageSlider."""
302
- return gr.update(value=None)
303
-
304
-
305
-
306
- def preload_presets(target_ratio, ui_width, ui_height):
307
- """Updates the width and height sliders based on the selected aspect ratio."""
308
- if target_ratio == "9:16":
309
- changed_width = 720
310
- changed_height = 1280
311
- return changed_width, changed_height, "Middle", gr.update(open=False)
312
- elif target_ratio == "16:9":
313
- changed_width = 1280
314
- changed_height = 720
315
- return changed_width, changed_height, "Middle", gr.update(open=False)
316
- elif target_ratio == "1:1":
317
- changed_width = 1024
318
- changed_height = 1024
319
- return changed_width, changed_height, "Middle", gr.update(open=False)
320
- elif target_ratio == "SORA최적비율":
321
- changed_width = 720
322
- changed_height = 480
323
- return changed_width, changed_height, "Middle", gr.update(open=False)
324
- elif target_ratio == "Custom":
325
- return ui_width, ui_height, "Middle", gr.update(open=True)
326
-
327
- def select_the_right_preset(user_width, user_height):
328
- if user_width == 720 and user_height == 1280:
329
- return "9:16"
330
- elif user_width == 1280 and user_height == 720:
331
- return "16:9"
332
- elif user_width == 1024 and user_height == 1024:
333
- return "1:1"
334
- elif user_width == 720 and user_height == 480:
335
- return "SORA최적비율"
336
- else:
337
- return "Custom"
338
-
339
-
340
- def toggle_custom_resize_slider(resize_option):
341
- return gr.update(visible=(resize_option == "Custom"))
342
-
343
- with gr.Blocks(theme="Nymbo/Nymbo_Theme", css="""
344
- footer {
345
- visibility: hidden;
346
- }
347
- .tab-nav button {
348
- color: #7FFFD4 !important; /* 형광 민트 색상 */
349
- }
350
- .tab-nav button.selected {
351
- color: #FFFF00 !important; /* 밝은 형광 옐로우 */
352
- border-color: #FFFF00 !important;
353
- }
354
- """) as demo:
355
- with gr.Tab("BEST 갤러리"):
356
- gr.Markdown("'OpenFree SORA' 생성 BEST 갤러리")
357
-
358
- selected_video = gr.Video(label="선택된 비디오", width=800)
359
- selected_prompt = gr.Markdown(label="프롬프트")
360
-
361
- gallery_data = load_json_data()
362
- for i in range(0, len(gallery_data), 5):
363
- with gr.Row():
364
- for item in gallery_data[i:i+5]:
365
- with gr.Column(scale=1, min_width=200):
366
- video_path = os.path.join(BASE_DIR, item['filename'])
367
- gr.Video(video_path, autoplay=True, loop=True, width=200, height=200)
368
- gr.Button("선택", size="sm").click(
369
- lambda x=video_path, p=item['prompt']: (x, p),
370
- outputs=[selected_video, selected_prompt]
371
- )
372
-
373
-
374
- with gr.Tab("이미지 확장"):
375
- with gr.Row():
376
- with gr.Column():
377
- input_image = gr.Image(
378
- type="pil",
379
- label="Input Image"
380
- )
381
-
382
- with gr.Row():
383
- with gr.Column(scale=2):
384
- prompt_input = gr.Textbox(label="Prompt (Optional)")
385
- with gr.Column(scale=1):
386
- run_button = gr.Button("Generate")
387
-
388
-
389
- with gr.Row():
390
- target_ratio = gr.Radio(
391
- label="Expected Ratio",
392
- choices=["9:16", "16:9", "1:1", "SORA최적비율", "Custom"],
393
- value="9:16",
394
- scale=2
395
- )
396
-
397
- alignment_dropdown = gr.Dropdown(
398
- choices=["Middle", "Left", "Right", "Top", "Bottom"],
399
- value="Middle",
400
- label="고정 위치 선택"
401
- )
402
-
403
-
404
-
405
- with gr.Accordion(label="Advanced settings", open=False) as settings_panel:
406
- with gr.Column():
407
- with gr.Row():
408
- width_slider = gr.Slider(
409
- label="Width",
410
- minimum=256,
411
- maximum=1536,
412
- step=8,
413
- value=720, # Set a default value
414
- )
415
- height_slider = gr.Slider(
416
- label="Height",
417
- minimum=256,
418
- maximum=1536,
419
- step=8,
420
- value=480, # Set a default value
421
- )
422
- with gr.Row():
423
- num_inference_steps = gr.Slider(label="Steps", minimum=4, maximum=12, step=1, value=8)
424
- overlap_width = gr.Slider(
425
- label="Mask overlap width",
426
- minimum=1,
427
- maximum=50,
428
- value=42,
429
- step=1
430
- )
431
- with gr.Row():
432
- resize_option = gr.Radio(
433
- label="Resize input image",
434
- choices=["Full", "1/2", "1/3", "1/4", "Custom"],
435
- value="Full"
436
- )
437
-
438
- custom_resize_size = gr.Slider(
439
- label="Custom resize size",
440
- minimum=256, # 이전에는 720이었습니다.
441
- maximum=1024,
442
- step=8,
443
- value=512, # 초기 값이므로 이 값도 적절히 조정할 수 있습니다.
444
- visible=False # 기본적으로 이 슬라이더는 숨겨져 있으며, 'Custom'이 선택될 때만 보입니다.
445
- )
446
-
447
-
448
-
449
- gr.Examples(
450
- examples=[
451
- ["./examples/example_2.jpg", 1440, 810, "Middle"],
452
- ["./examples/example_3.jpg", 1024, 1024, "Bottom"],
453
- ["./examples/example_4.png", 1024, 1024, "Top"],
454
- ],
455
- inputs=[input_image, width_slider, height_slider, alignment_dropdown],
456
- )
457
-
458
- with gr.Column():
459
- result = ImageSlider(
460
- interactive=False,
461
- label="Generated Image",
462
- )
463
- use_as_input_button = gr.Button("Use as Input Image", visible=False)
464
-
465
- def use_output_as_input(output_image):
466
- """Sets the generated output as the new input image."""
467
- return gr.update(value=output_image[1])
468
-
469
- use_as_input_button.click(
470
- fn=use_output_as_input,
471
- inputs=[result],
472
- outputs=[input_image]
473
- )
474
- target_ratio.change(
475
- fn=preload_presets,
476
- inputs=[target_ratio, width_slider, height_slider],
477
- outputs=[width_slider, height_slider, alignment_dropdown, settings_panel],
478
- queue=False
479
- )
480
-
481
-
482
- width_slider.change(
483
- fn=select_the_right_preset,
484
- inputs=[width_slider, height_slider],
485
- outputs=[target_ratio],
486
- queue=False
487
- )
488
-
489
- height_slider.change(
490
- fn=select_the_right_preset,
491
- inputs=[width_slider, height_slider],
492
- outputs=[target_ratio],
493
- queue=False
494
- )
495
-
496
- resize_option.change(
497
- fn=toggle_custom_resize_slider,
498
- inputs=[resize_option],
499
- outputs=[custom_resize_size],
500
- queue=False
501
- )
502
-
503
- run_button.click(
504
- fn=clear_result,
505
- inputs=None,
506
- outputs=result,
507
- ).then(
508
- fn=infer,
509
- inputs=[input_image, width_slider, height_slider, overlap_width, num_inference_steps,
510
- resize_option, custom_resize_size, prompt_input, alignment_dropdown],
511
- outputs=result,
512
- ).then(
513
- fn=lambda: gr.update(visible=True),
514
- inputs=None,
515
- outputs=use_as_input_button,
516
- )
517
-
518
- prompt_input.submit(
519
- fn=clear_result,
520
- inputs=None,
521
- outputs=result,
522
- ).then(
523
- fn=infer,
524
- inputs=[input_image, width_slider, height_slider, overlap_width, num_inference_steps,
525
- resize_option, custom_resize_size, prompt_input, alignment_dropdown],
526
- outputs=result,
527
- ).then(
528
- fn=lambda: gr.update(visible=True),
529
- inputs=None,
530
- outputs=use_as_input_button,
531
- )
532
-
533
-
534
- with gr.Tab("Free 이미지 검색"):
535
- gr.Markdown("## 저작권 Free/ 상업적 사용 허용 이미지 검색")
536
- keyword_input = gr.Textbox(label="키워드 입력 (한글 또는 영어)")
537
- search_button = gr.Button("검색")
538
- image_output = gr.HTML(label="검색 결과")
539
-
540
- search_button.click(
541
- fn=display_images,
542
- inputs=[keyword_input],
543
- outputs=[image_output]
544
- )
545
-
546
- with gr.Tab("Free 비디오 검색"):
547
- gr.Markdown("## 저작권 Free/ 상업적 사용 허용 비디오 검색")
548
- keyword_input = gr.Textbox(label="키워드 입력 (한글 또는 영어)")
549
- search_button = gr.Button("검색")
550
- video_output = gr.HTML(label="검색 결과")
551
-
552
- search_button.click(
553
- fn=display_videos,
554
- inputs=[keyword_input],
555
- outputs=[video_output]
556
- )
557
-
558
- demo.queue(max_size=12).launch(share=False)