ginipick commited on
Commit
70f271a
·
verified ·
1 Parent(s): 2f6382c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -24
app.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
  Gradio UI that calls the remote animation server.
3
- 환경변수 ANIM_API_URL 서버 주소를 설정하세요
4
  ANIM_API_URL=http://211.233.58.201:7788/
5
  """
6
 
@@ -11,39 +11,32 @@ import gradio as gr
11
  import httpx
12
  from gradio_client import Client, handle_file
13
 
14
- # ────────────────────────── 로깅 ──────────────────────────── #
15
  logging.basicConfig(
16
  level=logging.INFO,
17
  format="%(asctime)s [%(levelname)s] %(message)s"
18
  )
19
  log = logging.getLogger(__name__)
20
 
21
- # ───────────────────── 서버 URL 결정 로직 ───────────────────── #
22
- _DEFAULT_URL = "http://127.0.0.1:7788/"
23
- REMOTE_URL = "http://211.233.58.201:7788/"
24
- API_URL = os.getenv("ANIM_API_URL", REMOTE_URL)
25
 
26
- # Hugging Face Space 컨테이너 안에서 127.0.0.1 사용하면 외부 접속 불가
27
  if "127.0.0.1" in API_URL and os.getenv("HF_SPACE") == "true":
28
  raise RuntimeError(
29
- "HF Space 내부에서는 ANIM_API_URL 공인 IP나 도메인으로 설정해야 합니다."
30
  )
31
 
32
- # ──────────────────────── 헬퍼 함수 ───────────────────────── #
33
- def make_client() -> Client:
34
- """
35
- httpx.Timeout 은 0.27+ 에서 4개 또는 default 모두 지정해야 함
36
- connect 30s • read/write 120s • pool 30s
37
- """
38
- timeout = httpx.Timeout(connect=30.0, read=120.0, write=120.0, pool=30.0)
39
- return Client(API_URL, timeout=timeout, retries=3)
40
 
41
  def test_api_connection():
42
  now = datetime.now().strftime("%H:%M:%S")
43
  try:
44
- client = make_client()
45
- ready = client.get("/healthz")["ready"]
46
- msg = f"[{now}] 서버 연결 성공 ✅ (ready={ready})"
47
  log.info(msg)
48
  return True, msg
49
  except Exception as e:
@@ -51,17 +44,19 @@ def test_api_connection():
51
  log.error(msg)
52
  return False, msg
53
 
 
54
  def generate_animation(image, audio, guidance_scale, steps, progress=gr.Progress()):
55
  start = datetime.now().strftime("%H:%M:%S")
56
  logs = [f"[{start}] 요청 시작"]
 
57
  try:
58
  if image is None or audio is None:
59
  raise ValueError("이미지와 오디오를 모두 업로드하세요.")
60
 
61
  progress(0.05, desc="파일 준비")
62
- client = make_client()
63
 
64
- progress(0.15, desc="서버 호출 중… (최대 2~3분)")
65
  result = client.predict(
66
  image_path=handle_file(image),
67
  audio_path=handle_file(audio),
@@ -82,7 +77,7 @@ def generate_animation(image, audio, guidance_scale, steps, progress=gr.Progress
82
  logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] 오류: {e}")
83
  return None, None, "\n".join(logs)
84
 
85
- # ────────────────────────── UI 정의 ───────────────────────── #
86
  with gr.Blocks(title="Animation Generator Client") as demo:
87
  gr.Markdown("# 🎬 Animation Generator – Client UI")
88
 
@@ -107,14 +102,13 @@ with gr.Blocks(title="Animation Generator Client") as demo:
107
  with gr.Accordion("실행 로그", open=False):
108
  log_out = gr.Textbox(label="Logs", lines=12, max_lines=20, interactive=False)
109
 
110
- # 버튼 이벤트 연결
111
  gen_btn.click(
112
  generate_animation,
113
  inputs=[img_in, aud_in, scale, steps],
114
  outputs=[anim_out, comp_out, log_out]
115
  )
116
 
117
- # ────────────────────────── 실행 ─────────────────────────── #
118
  if __name__ == "__main__":
119
  demo.queue(max_size=4).launch(
120
  server_name="0.0.0.0",
 
1
  """
2
  Gradio UI that calls the remote animation server.
3
+ ANIM_API_URL 환경변수를 설정해 서버 주소를 주입하세요.
4
  ANIM_API_URL=http://211.233.58.201:7788/
5
  """
6
 
 
11
  import httpx
12
  from gradio_client import Client, handle_file
13
 
14
+ # ──────────────────────── 로깅 ────────────────────────── #
15
  logging.basicConfig(
16
  level=logging.INFO,
17
  format="%(asctime)s [%(levelname)s] %(message)s"
18
  )
19
  log = logging.getLogger(__name__)
20
 
21
+ # ──────────────── 서버 URL 결정 ─────────────────────── #
22
+ DEFAULT_URL = "http://127.0.0.1:7788/"
23
+ REMOTE_URL = "http://211.233.58.201:7788/"
24
+ API_URL = os.getenv("ANIM_API_URL", REMOTE_URL)
25
 
 
26
  if "127.0.0.1" in API_URL and os.getenv("HF_SPACE") == "true":
27
  raise RuntimeError(
28
+ "HF Space 컨테이너 안에서는 공인 IP나 도메인을 ANIM_API_URL 로 지정해야 합니다."
29
  )
30
 
31
+ # ──────────────── 헬스체크 함수 ─────────────────────── #
32
+ TIMEOUT = httpx.Timeout(connect=30.0, read=120.0, write=120.0, pool=30.0)
 
 
 
 
 
 
33
 
34
  def test_api_connection():
35
  now = datetime.now().strftime("%H:%M:%S")
36
  try:
37
+ resp = httpx.get(f"{API_URL.rstrip('/')}/healthz", timeout=TIMEOUT)
38
+ ready = resp.json().get("ready", False)
39
+ msg = f"[{now}] 서버 연결 성공 ✅ (ready={ready})"
40
  log.info(msg)
41
  return True, msg
42
  except Exception as e:
 
44
  log.error(msg)
45
  return False, msg
46
 
47
+ # ──────────────── 애니메이션 생성 ───────────────────── #
48
  def generate_animation(image, audio, guidance_scale, steps, progress=gr.Progress()):
49
  start = datetime.now().strftime("%H:%M:%S")
50
  logs = [f"[{start}] 요청 시작"]
51
+
52
  try:
53
  if image is None or audio is None:
54
  raise ValueError("이미지와 오디오를 모두 업로드하세요.")
55
 
56
  progress(0.05, desc="파일 준비")
57
+ client = Client(API_URL) # ← timeout 인자 삭제
58
 
59
+ progress(0.15, desc="서버 호출 중… ( 소요 가능)")
60
  result = client.predict(
61
  image_path=handle_file(image),
62
  audio_path=handle_file(audio),
 
77
  logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] 오류: {e}")
78
  return None, None, "\n".join(logs)
79
 
80
+ # ─────────────────────── UI 정의 ────────────────────── #
81
  with gr.Blocks(title="Animation Generator Client") as demo:
82
  gr.Markdown("# 🎬 Animation Generator – Client UI")
83
 
 
102
  with gr.Accordion("실행 로그", open=False):
103
  log_out = gr.Textbox(label="Logs", lines=12, max_lines=20, interactive=False)
104
 
 
105
  gen_btn.click(
106
  generate_animation,
107
  inputs=[img_in, aud_in, scale, steps],
108
  outputs=[anim_out, comp_out, log_out]
109
  )
110
 
111
+ # ─────────────────────── 실행 ───────────────────────── #
112
  if __name__ == "__main__":
113
  demo.queue(max_size=4).launch(
114
  server_name="0.0.0.0",