aiqcamp commited on
Commit
afc3bcb
·
verified ·
1 Parent(s): bf4edff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -102
app.py CHANGED
@@ -3,74 +3,20 @@ import numpy as np
3
  import random
4
  import torch
5
  from diffusers import DiffusionPipeline
6
- import warnings
7
- import os
8
- from datetime import datetime
9
- import uuid
10
 
11
- # 경고 메시지 숨기기
12
- warnings.filterwarnings('ignore', category=UserWarning)
13
-
14
- # 저장 디렉토리 생성
15
- SAVE_DIR = "saved_images"
16
- if not os.path.exists(SAVE_DIR):
17
- os.makedirs(SAVE_DIR, exist_ok=True)
18
-
19
- # 장치 및 dtype 설정
20
- dtype = torch.float32 if torch.cuda.is_available() else torch.float32
21
  device = "cuda" if torch.cuda.is_available() else "cpu"
22
 
23
  # 모델 로드
24
  pipe = DiffusionPipeline.from_pretrained(
25
- "black-forest-labs/FLUX.1-schnell",
26
- torch_dtype=dtype,
27
- device_map="balanced" if torch.cuda.is_available() else None,
28
- use_safetensors=True
29
  ).to(device)
30
 
31
- # 메모리 최적화
32
- pipe.enable_attention_slicing()
33
- if device == "cpu":
34
- pipe.enable_sequential_cpu_offload()
35
-
36
  MAX_SEED = np.iinfo(np.int32).max
37
  MAX_IMAGE_SIZE = 2048
38
 
39
- def generate_diagram(prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4):
40
- """FLUX AI를 사용하여 다이어그램 생성"""
41
- try:
42
- if randomize_seed:
43
- seed = random.randint(0, MAX_SEED)
44
- generator = torch.Generator(device=device).manual_seed(seed)
45
-
46
- with torch.no_grad():
47
- image = pipe(
48
- prompt=prompt,
49
- width=width,
50
- height=height,
51
- num_inference_steps=num_inference_steps,
52
- generator=generator,
53
- guidance_scale=0.0
54
- ).images[0]
55
-
56
- # 이미지 저장
57
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
58
- unique_id = str(uuid.uuid4())[:8]
59
- filename = f"diagram_{timestamp}_{unique_id}.png"
60
- save_path = os.path.join(SAVE_DIR, filename)
61
- image.save(save_path)
62
-
63
- return image, seed
64
-
65
- except Exception as e:
66
- raise gr.Error(f"다이어그램 생성 중 오류 발생: {str(e)}")
67
- finally:
68
- if torch.cuda.is_available():
69
- torch.cuda.empty_cache()
70
-
71
-
72
-
73
-
74
  # Enhanced examples with more detailed prompts and specific styling
75
  EXAMPLES = [
76
  {
@@ -272,33 +218,19 @@ GRADIO_EXAMPLES = [
272
  for example in EXAMPLES
273
  ]
274
 
275
- def generate_diagram(prompt, width=1024, height=1024):
276
- """FLUX AI를 사용하여 다이어그램 생성"""
277
- try:
278
- # 시드 설정
279
  seed = random.randint(0, MAX_SEED)
280
- generator = torch.Generator(device=device).manual_seed(seed)
281
-
282
- # 이미지 생성
283
- image = pipeline(
284
- prompt=prompt,
285
- width=width,
286
- height=height,
287
- num_inference_steps=4,
288
- generator=generator,
289
- ).images[0]
290
-
291
- # 이미지 저장
292
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
293
- unique_id = str(uuid.uuid4())[:8]
294
- filename = f"diagram_{timestamp}_{unique_id}.png"
295
- save_path = os.path.join(SAVE_DIR, filename)
296
- image.save(save_path)
297
-
298
- return image
299
-
300
- except Exception as e:
301
- raise gr.Error(f"다이어그램 생성 중 오류 발생: {str(e)}")
302
 
303
  # CSS 스타일
304
  css="""
@@ -311,36 +243,37 @@ css="""
311
  # Gradio 인터페이스 생성
312
  with gr.Blocks(css=css) as demo:
313
  with gr.Column(elem_id="col-container"):
314
- gr.Markdown("""# FLUX 다이어그램 생성기
315
- FLUX AI를 사용하여 아름다운 손그림 스타일의 다이어그램을 생성합니다
 
316
  """)
317
 
318
  with gr.Row():
319
  prompt = gr.Text(
320
- label="프롬프트",
321
  show_label=False,
322
  max_lines=1,
323
- placeholder="다이어그램 구조를 입력하세요...",
324
  container=False,
325
  )
326
- run_button = gr.Button("생성", scale=0)
327
 
328
- result = gr.Image(label="생성된 다이어그램", show_label=False)
329
 
330
- with gr.Accordion("고급 설정", open=False):
331
  seed = gr.Slider(
332
- label="시드",
333
  minimum=0,
334
  maximum=MAX_SEED,
335
  step=1,
336
  value=0,
337
  )
338
 
339
- randomize_seed = gr.Checkbox(label="랜덤 시드", value=True)
340
 
341
  with gr.Row():
342
  width = gr.Slider(
343
- label="너비",
344
  minimum=256,
345
  maximum=MAX_IMAGE_SIZE,
346
  step=32,
@@ -348,7 +281,7 @@ with gr.Blocks(css=css) as demo:
348
  )
349
 
350
  height = gr.Slider(
351
- label="높이",
352
  minimum=256,
353
  maximum=MAX_IMAGE_SIZE,
354
  step=32,
@@ -356,26 +289,24 @@ with gr.Blocks(css=css) as demo:
356
  )
357
 
358
  num_inference_steps = gr.Slider(
359
- label="추론 단계 ",
360
  minimum=1,
361
  maximum=50,
362
  step=1,
363
  value=4,
364
  )
365
 
366
- # 예제 추가
367
  gr.Examples(
368
- examples=EXAMPLES, # 이전에 정의된 예제들 사용
369
- fn=generate_diagram,
370
  inputs=[prompt],
371
  outputs=[result, seed],
372
- cache_examples=True
373
  )
374
 
375
- # 이벤트 핸들러
376
  gr.on(
377
  triggers=[run_button.click, prompt.submit],
378
- fn=generate_diagram,
379
  inputs=[prompt, seed, randomize_seed, width, height, num_inference_steps],
380
  outputs=[result, seed]
381
  )
 
3
  import random
4
  import torch
5
  from diffusers import DiffusionPipeline
 
 
 
 
6
 
7
+ # 기본 설정
8
+ dtype = torch.bfloat16
 
 
 
 
 
 
 
 
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
 
11
  # 모델 로드
12
  pipe = DiffusionPipeline.from_pretrained(
13
+ "black-forest-labs/FLUX.1-schnell",
14
+ torch_dtype=dtype
 
 
15
  ).to(device)
16
 
 
 
 
 
 
17
  MAX_SEED = np.iinfo(np.int32).max
18
  MAX_IMAGE_SIZE = 2048
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # Enhanced examples with more detailed prompts and specific styling
21
  EXAMPLES = [
22
  {
 
218
  for example in EXAMPLES
219
  ]
220
 
221
+ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
222
+ if randomize_seed:
 
 
223
  seed = random.randint(0, MAX_SEED)
224
+ generator = torch.Generator().manual_seed(seed)
225
+ image = pipe(
226
+ prompt=prompt,
227
+ width=width,
228
+ height=height,
229
+ num_inference_steps=num_inference_steps,
230
+ generator=generator,
231
+ guidance_scale=0.0
232
+ ).images[0]
233
+ return image, seed
 
 
 
 
 
 
 
 
 
 
 
 
234
 
235
  # CSS 스타일
236
  css="""
 
243
  # Gradio 인터페이스 생성
244
  with gr.Blocks(css=css) as demo:
245
  with gr.Column(elem_id="col-container"):
246
+ gr.Markdown("""# FLUX.1 [schnell]
247
+ 12B param rectified flow transformer distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/) for 4 step generation
248
+ [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-schnell)]
249
  """)
250
 
251
  with gr.Row():
252
  prompt = gr.Text(
253
+ label="Prompt",
254
  show_label=False,
255
  max_lines=1,
256
+ placeholder="Enter your prompt",
257
  container=False,
258
  )
259
+ run_button = gr.Button("Run", scale=0)
260
 
261
+ result = gr.Image(label="Result", show_label=False)
262
 
263
+ with gr.Accordion("Advanced Settings", open=False):
264
  seed = gr.Slider(
265
+ label="Seed",
266
  minimum=0,
267
  maximum=MAX_SEED,
268
  step=1,
269
  value=0,
270
  )
271
 
272
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
273
 
274
  with gr.Row():
275
  width = gr.Slider(
276
+ label="Width",
277
  minimum=256,
278
  maximum=MAX_IMAGE_SIZE,
279
  step=32,
 
281
  )
282
 
283
  height = gr.Slider(
284
+ label="Height",
285
  minimum=256,
286
  maximum=MAX_IMAGE_SIZE,
287
  step=32,
 
289
  )
290
 
291
  num_inference_steps = gr.Slider(
292
+ label="Number of inference steps",
293
  minimum=1,
294
  maximum=50,
295
  step=1,
296
  value=4,
297
  )
298
 
 
299
  gr.Examples(
300
+ examples=GRADIO_EXAMPLES,
301
+ fn=infer,
302
  inputs=[prompt],
303
  outputs=[result, seed],
304
+ cache_examples="lazy"
305
  )
306
 
 
307
  gr.on(
308
  triggers=[run_button.click, prompt.submit],
309
+ fn=infer,
310
  inputs=[prompt, seed, randomize_seed, width, height, num_inference_steps],
311
  outputs=[result, seed]
312
  )