ssboost commited on
Commit
b86b06a
·
verified ·
1 Parent(s): 83d7da1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -18
app.py CHANGED
@@ -58,8 +58,8 @@ class GradioClientController:
58
  try:
59
  self.client = Client(self.api_endpoint)
60
  logger.info("API 클라이언트가 성공적으로 초기화되었습니다.")
61
- # 초기화 성공 시 배경 옵션 로드
62
- self._load_background_options()
63
  return
64
  except Exception as e:
65
  if attempt < max_retries - 1:
@@ -72,21 +72,60 @@ class GradioClientController:
72
  logger.error(f"클라이언트 초기화 실패: {str(e)}")
73
  self.client = None
74
 
75
- def _load_background_options(self):
76
- """배경 옵션을 미리 로드하여 캐시"""
77
  try:
78
  if self.client:
79
- # 배경 타입별로 옵션 로드
80
- background_types = ["심플 배경", "스튜디오 배경", "자연 환경", "실내 환경", "특수배경", "주얼리", "특수효과"]
81
- for bg_type in background_types:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  result = self.client.predict(bg_type, api_name="/update_dropdowns")
83
- if isinstance(result, (list, tuple)) and len(result) >= 7:
84
- self.background_options[bg_type] = result
85
- logger.info(f"배경 옵션 로드 완료: {bg_type}")
86
- time.sleep(0.1) # API 호출 간격
 
 
 
 
 
 
 
 
87
  except Exception as e:
88
- logger.warning(f"배경 옵션 미리 로드 실패: {str(e)}")
89
- # 실패해도 계속 진행
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  def _ensure_client(self) -> bool:
92
  """클라이언트 연결 상태 확인 및 재연결"""
@@ -306,9 +345,10 @@ def create_gradio_interface():
306
  value="심플 배경"
307
  )
308
 
309
- # 드롭다운 컴포넌트들 (API에서 동적으로 로드)
310
  simple_dropdown = gr.Dropdown(
311
- choices=[],
 
312
  label="심플 배경 선택",
313
  visible=True,
314
  interactive=True
@@ -451,10 +491,20 @@ def create_gradio_interface():
451
  ]
452
  )
453
 
454
- # 앱 로드 시 초기 드롭다운 설정
 
 
 
 
 
 
 
 
 
 
 
455
  app.load(
456
- fn=controller.update_dropdowns,
457
- inputs=[background_type],
458
  outputs=[simple_dropdown, studio_dropdown, nature_dropdown,
459
  indoor_dropdown, special_dropdown, jewelry_dropdown, special_effects_dropdown]
460
  )
 
58
  try:
59
  self.client = Client(self.api_endpoint)
60
  logger.info("API 클라이언트가 성공적으로 초기화되었습니다.")
61
+ # 초기화 성공 시 심플 배경 옵션 먼저 로드
62
+ self._load_simple_background()
63
  return
64
  except Exception as e:
65
  if attempt < max_retries - 1:
 
72
  logger.error(f"클라이언트 초기화 실패: {str(e)}")
73
  self.client = None
74
 
75
+ def _load_simple_background(self):
76
+ """심플 배경 옵션만 먼저 로드"""
77
  try:
78
  if self.client:
79
+ result = self.client.predict("심플 배경", api_name="/update_dropdowns")
80
+ if isinstance(result, (list, tuple)) and len(result) >= 7:
81
+ self.background_options["심플 배경"] = result
82
+ logger.info("심플 배경 옵션 로드 완료")
83
+ return result[0] # 심플 배경 선택지 반환
84
+ except Exception as e:
85
+ logger.warning(f"심플 배경 옵션 로드 실패: {str(e)}")
86
+ return []
87
+ def get_initial_dropdown_data(self, bg_type: str = "심플 배경") -> Tuple:
88
+ """초기 드롭다운 데이터 가져오기"""
89
+ try:
90
+ # 캐시된 데이터 먼저 확인
91
+ if bg_type in self.background_options:
92
+ result = self.background_options[bg_type]
93
+ logger.info(f"캐시에서 초기 드롭다운 데이터 로드: {bg_type}")
94
+ else:
95
+ # API 호출로 데이터 가져오기
96
+ if self.client:
97
  result = self.client.predict(bg_type, api_name="/update_dropdowns")
98
+ self.background_options[bg_type] = result # 캐시에 저장
99
+ logger.info(f"API에서 초기 드롭다운 데이터 로드: {bg_type}")
100
+ else:
101
+ logger.error("클라이언트가 초기화되지 않음")
102
+ return tuple([[] for _ in range(7)])
103
+
104
+ # 결과 반환 (실제 선택지만)
105
+ if isinstance(result, (list, tuple)) and len(result) >= 7:
106
+ return result[:7]
107
+ else:
108
+ return tuple([[] for _ in range(7)])
109
+
110
  except Exception as e:
111
+ logger.error(f"초기 드롭다운 데이터 로드 실패: {str(e)}")
112
+ return tuple([[] for _ in range(7)])
113
+
114
+ def get_initial_simple_choices(self) -> list:
115
+ """심플 배경 초기 선택지만 반환"""
116
+ try:
117
+ if "심플 배경" in self.background_options:
118
+ choices = self.background_options["심플 배경"][0]
119
+ return choices if choices else []
120
+ elif self.client:
121
+ result = self.client.predict("심플 배경", api_name="/update_dropdowns")
122
+ if isinstance(result, (list, tuple)) and len(result) >= 1:
123
+ choices = result[0]
124
+ self.background_options["심플 배경"] = result
125
+ return choices if choices else []
126
+ except Exception as e:
127
+ logger.error(f"심플 배경 선택지 로드 실패: {str(e)}")
128
+ return []
129
 
130
  def _ensure_client(self) -> bool:
131
  """클라이언트 연결 상태 확인 및 재연결"""
 
345
  value="심플 배경"
346
  )
347
 
348
+ # 드롭다운 컴포넌트들 - 심플 배경은 즉시 로드
349
  simple_dropdown = gr.Dropdown(
350
+ choices=controller.get_initial_simple_choices(),
351
+ value=None, # 첫 번째 값은 로드 후 설정
352
  label="심플 배경 선택",
353
  visible=True,
354
  interactive=True
 
491
  ]
492
  )
493
 
494
+ # 앱 로드 시 모든 드롭다운 초기 설정 (더 강력한 초기화)
495
+ def initialize_all_dropdowns():
496
+ """모든 드롭다운을 초기화하는 함수"""
497
+ try:
498
+ logger.info("드롭다운 초기화 시작")
499
+ updates = controller.update_dropdowns("심플 배경")
500
+ logger.info("드롭다운 초기화 완료")
501
+ return updates
502
+ except Exception as e:
503
+ logger.error(f"드롭다운 초기화 실패: {str(e)}")
504
+ return tuple([gr.update() for _ in range(7)])
505
+
506
  app.load(
507
+ fn=initialize_all_dropdowns,
 
508
  outputs=[simple_dropdown, studio_dropdown, nature_dropdown,
509
  indoor_dropdown, special_dropdown, jewelry_dropdown, special_effects_dropdown]
510
  )