openfree commited on
Commit
eef0ab8
·
verified ·
1 Parent(s): e714f1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -28
app.py CHANGED
@@ -13,28 +13,21 @@ from transformers import pipeline as hf_pipeline
13
  ##############################################################################
14
  # 1) ZeroGPU 환경 처리 + device, dtype 설정
15
  ##############################################################################
16
- ##############################################################################
17
- # 1) ZeroGPU 환경 처리 + device, dtype 설정
18
- ##############################################################################
19
- # ZeroGPU 초기화 시도
20
  try:
21
  import zerogpu
22
  zerogpu.init()
23
  print("ZeroGPU initialized successfully")
24
  device = "cuda" if torch.cuda.is_available() else "cpu"
25
  except ImportError:
26
- # ZeroGPU가 설치되지 않은 경우
27
  print("ZeroGPU package not installed, continuing without it")
28
  if os.getenv("ZERO_GPU"):
29
  print("ZeroGPU environment variable is set but zerogpu package is not installed.")
30
  device = "cuda" if torch.cuda.is_available() else "cpu"
31
  except Exception as e:
32
- # ZeroGPU 초기화 중 다른 오류가 발생한 경우
33
  print(f"Error initializing ZeroGPU: {e}")
34
  print("Continuing without ZeroGPU")
35
  device = "cuda" if torch.cuda.is_available() else "cpu"
36
 
37
- # GPU일 때만 bfloat16, 그 외에는 float32
38
  dtype = torch.bfloat16 if device == "cuda" else torch.float32
39
 
40
  print(f"Using device: {device}, dtype: {dtype}")
@@ -57,7 +50,6 @@ try:
57
  print("Models loaded successfully")
58
  except Exception as e:
59
  print(f"Error loading models: {e}")
60
- # 모델 로드 에러 처리를 위한 더미 함수들
61
  def dummy_translator(text):
62
  return [{'translation_text': text}]
63
 
@@ -90,20 +82,14 @@ def contains_korean(text):
90
  # 이미지 생성 함수
91
  ##############################################################################
92
  def generate_design_image(prompt, seed=42, randomize_seed=True, width=1024, height=1024, num_inference_steps=4):
93
- """
94
- 생성된 확장 아이디어 텍스트(prompt)를 입력받아,
95
- 필요시 한국어를 영어로 번역한 후 DiffusionPipeline으로 이미지를 생성합니다.
96
- """
97
  original_prompt = prompt
98
  translated = False
99
 
100
- # 한국어가 포함되어 있으면 영어로 번역
101
  if contains_korean(prompt):
102
  translation = translator(prompt)
103
  prompt = translation[0]['translation_text']
104
  translated = True
105
 
106
- # 랜덤 시드 설정
107
  if randomize_seed:
108
  seed = random.randint(0, MAX_SEED)
109
 
@@ -420,7 +406,6 @@ def process_inputs(text1, text2, text3, selected_category, progress=gr.Progress(
420
  time.sleep(0.3)
421
  progress(0.1, desc="창의적인 아이디어 생성 시작...")
422
 
423
- # 카테고리에 해당하는 아이디어 생성
424
  results = generate_transformations(text1, text2, text3, selected_category)
425
 
426
  progress(0.8, desc="결과 포맷팅 중...")
@@ -507,7 +492,8 @@ with gr.Blocks(
507
  text_input1 = gr.Textbox(label="키워드 1 (필수)", placeholder="예: 스마트폰")
508
  text_input2 = gr.Textbox(label="키워드 2 (선택)", placeholder="예: 인공지능")
509
  text_input3 = gr.Textbox(label="키워드 3 (선택)", placeholder="예: 헬스케어")
510
- category_dropdown = gr.Dropdown(
 
511
  label="카테고리 선택",
512
  choices=list(physical_transformation_categories.keys()),
513
  value=list(physical_transformation_categories.keys())[0],
@@ -534,34 +520,31 @@ with gr.Blocks(
534
  idea_output = gr.Markdown(label="아이디어 결과")
535
  generated_image = gr.Image(label="생성된 디자인 이미지", type="pil")
536
 
537
- # 예제
538
  gr.Examples(
539
  examples=[
540
- ["스마트폰", "", "", list(physical_transformation_categories.keys())[0]],
541
- ["자동차", "", "", list(physical_transformation_categories.keys())[0]],
542
- ["자동차", "인공지능", "", list(physical_transformation_categories.keys())[0]],
543
- ["드론", "인공지능", "", list(physical_transformation_categories.keys())[0]],
544
- ["운동화", "웨어러블", "건강", list(physical_transformation_categories.keys())[0]],
545
  ],
546
- inputs=[text_input1, text_input2, text_input3, category_dropdown],
547
  )
548
 
549
- # 처리중 아이콘 보이기
550
  def show_processing_indicator():
551
  return gr.update(visible=True)
552
 
553
- # 처리중 아이콘 숨기기
554
  def hide_processing_indicator():
555
  return gr.update(visible=False)
556
 
557
- # 버튼 클릭 시 처리 로직
558
  submit_button.click(
559
  fn=show_processing_indicator,
560
  inputs=None,
561
  outputs=processing_indicator
562
  ).then(
563
  fn=process_all,
564
- inputs=[text_input1, text_input2, text_input3, category_dropdown],
565
  outputs=[idea_output, generated_image]
566
  ).then(
567
  fn=hide_processing_indicator,
@@ -569,6 +552,5 @@ with gr.Blocks(
569
  outputs=processing_indicator
570
  )
571
 
572
- # 메인 실행
573
  if __name__ == "__main__":
574
  demo.launch(debug=True)
 
13
  ##############################################################################
14
  # 1) ZeroGPU 환경 처리 + device, dtype 설정
15
  ##############################################################################
 
 
 
 
16
  try:
17
  import zerogpu
18
  zerogpu.init()
19
  print("ZeroGPU initialized successfully")
20
  device = "cuda" if torch.cuda.is_available() else "cpu"
21
  except ImportError:
 
22
  print("ZeroGPU package not installed, continuing without it")
23
  if os.getenv("ZERO_GPU"):
24
  print("ZeroGPU environment variable is set but zerogpu package is not installed.")
25
  device = "cuda" if torch.cuda.is_available() else "cpu"
26
  except Exception as e:
 
27
  print(f"Error initializing ZeroGPU: {e}")
28
  print("Continuing without ZeroGPU")
29
  device = "cuda" if torch.cuda.is_available() else "cpu"
30
 
 
31
  dtype = torch.bfloat16 if device == "cuda" else torch.float32
32
 
33
  print(f"Using device: {device}, dtype: {dtype}")
 
50
  print("Models loaded successfully")
51
  except Exception as e:
52
  print(f"Error loading models: {e}")
 
53
  def dummy_translator(text):
54
  return [{'translation_text': text}]
55
 
 
82
  # 이미지 생성 함수
83
  ##############################################################################
84
  def generate_design_image(prompt, seed=42, randomize_seed=True, width=1024, height=1024, num_inference_steps=4):
 
 
 
 
85
  original_prompt = prompt
86
  translated = False
87
 
 
88
  if contains_korean(prompt):
89
  translation = translator(prompt)
90
  prompt = translation[0]['translation_text']
91
  translated = True
92
 
 
93
  if randomize_seed:
94
  seed = random.randint(0, MAX_SEED)
95
 
 
406
  time.sleep(0.3)
407
  progress(0.1, desc="창의적인 아이디어 생성 시작...")
408
 
 
409
  results = generate_transformations(text1, text2, text3, selected_category)
410
 
411
  progress(0.8, desc="결과 포맷팅 중...")
 
492
  text_input1 = gr.Textbox(label="키워드 1 (필수)", placeholder="예: 스마트폰")
493
  text_input2 = gr.Textbox(label="키워드 2 (선택)", placeholder="예: 인공지능")
494
  text_input3 = gr.Textbox(label="키워드 3 (선택)", placeholder="예: 헬스케어")
495
+ # 드롭다운 대신 라디오 버튼으로 카테고리 선택 (모든 옵션이 펼쳐짐)
496
+ category_radio = gr.Radio(
497
  label="카테고리 선택",
498
  choices=list(physical_transformation_categories.keys()),
499
  value=list(physical_transformation_categories.keys())[0],
 
520
  idea_output = gr.Markdown(label="아이디어 결과")
521
  generated_image = gr.Image(label="생성된 디자인 이미지", type="pil")
522
 
523
+ # 다양한 카테고리가 포함된 예제 (라디오 버튼 입력)
524
  gr.Examples(
525
  examples=[
526
+ ["스마트폰", "", "", "공간 이동"],
527
+ ["자동차", "", "", "크기와 형태 변화"],
528
+ ["자동차", "인공지능", "", "표면 및 외관 변화"],
529
+ ["드론", "인공지능", "", "물질의 상태 변화"],
530
+ ["운동화", "웨어러블", "건강", "전기 및 자기 변화"],
531
  ],
532
+ inputs=[text_input1, text_input2, text_input3, category_radio],
533
  )
534
 
 
535
  def show_processing_indicator():
536
  return gr.update(visible=True)
537
 
 
538
  def hide_processing_indicator():
539
  return gr.update(visible=False)
540
 
 
541
  submit_button.click(
542
  fn=show_processing_indicator,
543
  inputs=None,
544
  outputs=processing_indicator
545
  ).then(
546
  fn=process_all,
547
+ inputs=[text_input1, text_input2, text_input3, category_radio],
548
  outputs=[idea_output, generated_image]
549
  ).then(
550
  fn=hide_processing_indicator,
 
552
  outputs=processing_indicator
553
  )
554
 
 
555
  if __name__ == "__main__":
556
  demo.launch(debug=True)