Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,126 +1,138 @@
|
|
1 |
-
|
|
|
2 |
from pydub import AudioSegment
|
3 |
-
from PIL
|
4 |
-
|
5 |
-
|
6 |
-
# --------------------------------------------------------------
|
7 |
-
# 1) 필요 체크포인트(두 개)만 받는다
|
8 |
-
# --------------------------------------------------------------
|
9 |
-
DL_CMDS = [
|
10 |
-
# Sonic(가중치, unet 등)
|
11 |
-
"huggingface-cli download LeonJoe13/Sonic --local-dir checkpoints/LeonJoe13-Sonic --local-dir-use-symlinks False -q",
|
12 |
-
# stable-video-diffusion-img2vid-xt (VAE/UNet/CLIP)
|
13 |
-
"huggingface-cli download stabilityai/stable-video-diffusion-img2vid-xt "
|
14 |
-
"--local-dir checkpoints/stable-video-diffusion-img2vid-xt --local-dir-use-symlinks False -q",
|
15 |
-
# whisper-tiny
|
16 |
-
"huggingface-cli download openai/whisper-tiny --local-dir checkpoints/whisper-tiny --local-dir-use-symlinks False -q",
|
17 |
-
]
|
18 |
-
for cmd in DL_CMDS:
|
19 |
-
os.system(cmd)
|
20 |
-
|
21 |
-
pipe = Sonic() # 위에서 모델 경로를 자동으로 찾음
|
22 |
|
23 |
# ------------------------------------------------------------------
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
return hashlib.md5(b).hexdigest()
|
26 |
|
27 |
-
TMP_DIR
|
28 |
-
|
29 |
-
os.makedirs(
|
|
|
30 |
|
31 |
# ------------------------------------------------------------------
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
# ------------------------------------------------------------------
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
62 |
if not os.path.exists(img_path):
|
63 |
-
with open(img_path, "wb") as f: f.write(
|
64 |
-
|
65 |
-
#
|
66 |
-
|
67 |
-
|
68 |
-
seg = AudioSegment(arr.tobytes(), frame_rate=
|
69 |
-
sample_width=arr.dtype.itemsize,
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
if os.path.exists(out_path):
|
83 |
-
print("[INFO]
|
84 |
return out_path
|
85 |
|
86 |
-
print(f"[INFO] Generating video (
|
87 |
-
|
88 |
-
if res == -1:
|
89 |
-
raise gr.Error("No face detected in the image.")
|
90 |
-
return res
|
91 |
|
92 |
# ------------------------------------------------------------------
|
93 |
-
#
|
94 |
# ------------------------------------------------------------------
|
95 |
-
|
96 |
-
.gradio-container
|
97 |
-
.main-header
|
98 |
"""
|
99 |
|
100 |
-
with gr.Blocks(css=
|
101 |
-
gr.HTML(
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
)
|
107 |
|
108 |
with gr.Row():
|
109 |
with gr.Column():
|
110 |
-
img_in
|
111 |
-
aud_in
|
112 |
-
scale
|
113 |
-
|
114 |
-
btn
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
gr.HTML(
|
120 |
-
"<div style='text-align:center;margin-top:1.5em'>"
|
121 |
-
"<a href='https://github.com/jixiaozhong/Sonic' target='_blank'>GitHub</a> | "
|
122 |
-
"<a href='https://arxiv.org/pdf/2411.16331' target='_blank'>Paper</a>"
|
123 |
-
"</div>"
|
124 |
-
)
|
125 |
|
126 |
demo.launch(share=True)
|
|
|
1 |
+
# app.py
|
2 |
+
import os, io, hashlib, spaces, gradio as gr
|
3 |
from pydub import AudioSegment
|
4 |
+
from PIL import Image
|
5 |
+
import numpy as np
|
6 |
+
from sonic import Sonic # <-- 수정된 sonic.py 사용
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# ------------------------------------------------------------------
|
9 |
+
# 1. 필요한 모델·라이브러리 설치 & 체크포인트 다운로드
|
10 |
+
# ------------------------------------------------------------------
|
11 |
+
SETUP_CMD = (
|
12 |
+
# 필수 라이브러리
|
13 |
+
'python -m pip install --quiet "huggingface_hub[cli]" accelerate pydub Pillow '
|
14 |
+
# Sonic 체크포인트 → checkpoints/Sonic/*
|
15 |
+
'&& huggingface-cli download LeonJoe13/Sonic '
|
16 |
+
'--local-dir checkpoints/Sonic --local-dir-use-symlinks False '
|
17 |
+
# Whisper-tiny (음성 인코더)
|
18 |
+
'&& huggingface-cli download openai/whisper-tiny '
|
19 |
+
'--local-dir checkpoints/whisper-tiny --local-dir-use-symlinks False '
|
20 |
+
)
|
21 |
+
os.system(SETUP_CMD)
|
22 |
+
|
23 |
+
# ------------------------------------------------------------------
|
24 |
+
# 2. 파이프라인 초기화 (GPU 한 번만)
|
25 |
+
# ------------------------------------------------------------------
|
26 |
+
pipe = Sonic() # 오류가 사라진 상태로 초기화
|
27 |
+
|
28 |
+
# ------------------------------------------------------------------
|
29 |
+
# 3. 유틸리티
|
30 |
+
# ------------------------------------------------------------------
|
31 |
+
def _md5(b: bytes) -> str:
|
32 |
return hashlib.md5(b).hexdigest()
|
33 |
|
34 |
+
TMP_DIR = "tmp_path"
|
35 |
+
RES_DIR = "res_path"
|
36 |
+
os.makedirs(TMP_DIR, exist_ok=True)
|
37 |
+
os.makedirs(RES_DIR, exist_ok=True)
|
38 |
|
39 |
# ------------------------------------------------------------------
|
40 |
+
# 4. 실제 비디오 생성 (GPU 태스크)
|
41 |
+
# ------------------------------------------------------------------
|
42 |
+
@spaces.GPU(duration=600) # 최대 10분
|
43 |
+
def _render_video(img_path: str,
|
44 |
+
audio_path: str,
|
45 |
+
out_path: str,
|
46 |
+
dynamic_scale: float = 1.0) -> str | int:
|
47 |
+
|
48 |
+
min_resolution = 512
|
49 |
+
audio = AudioSegment.from_file(audio_path)
|
50 |
+
duration_sec = len(audio) / 1000.0
|
51 |
+
steps = int(np.clip(duration_sec * 12.5, 25, 750))
|
52 |
+
|
53 |
+
print(f"[INFO] Audio duration={duration_sec:.2f}s → inference_steps={steps}")
|
54 |
+
|
55 |
+
face_info = pipe.preprocess(img_path)
|
56 |
+
print(f"[INFO] Face detection info: {face_info}")
|
57 |
+
|
58 |
+
if face_info["face_num"] == 0:
|
59 |
+
return -1 # 얼굴 미검출
|
60 |
+
|
61 |
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
62 |
+
pipe.process(
|
63 |
+
img_path, audio_path, out_path,
|
64 |
+
min_resolution=min_resolution,
|
65 |
+
inference_steps=steps,
|
66 |
+
dynamic_scale=dynamic_scale,
|
67 |
+
)
|
68 |
+
return out_path
|
69 |
|
70 |
# ------------------------------------------------------------------
|
71 |
+
# 5. Gradio 래퍼
|
72 |
+
# ------------------------------------------------------------------
|
73 |
+
def run_sonic(image, audio, dynamic_scale):
|
74 |
+
|
75 |
+
if image is None:
|
76 |
+
raise gr.Error("Please upload an image.")
|
77 |
+
if audio is None:
|
78 |
+
raise gr.Error("Please upload an audio file.")
|
79 |
+
|
80 |
+
# ── 이미지 캐시 ───────────────────────────────────────────────
|
81 |
+
buf_i = io.BytesIO(); image.save(buf_i, format="PNG")
|
82 |
+
img_hash = _md5(buf_i.getvalue())
|
83 |
+
img_path = os.path.join(TMP_DIR, f"{img_hash}.png")
|
84 |
if not os.path.exists(img_path):
|
85 |
+
with open(img_path, "wb") as f: f.write(buf_i.getvalue())
|
86 |
+
|
87 |
+
# ── 오디오 캐시 (mono/16 kHz, ≤60 s) ─────────────────────────
|
88 |
+
rate, arr = audio[:2]
|
89 |
+
if arr.ndim == 1: arr = arr[:, None]
|
90 |
+
seg = AudioSegment(arr.tobytes(), frame_rate=rate,
|
91 |
+
sample_width=arr.dtype.itemsize, channels=arr.shape[1])
|
92 |
+
seg = seg.set_channels(1).set_frame_rate(16000)[:60_000]
|
93 |
+
buf_a = io.BytesIO(); seg.export(buf_a, format="wav")
|
94 |
+
aud_hash = _md5(buf_a.getvalue())
|
95 |
+
aud_path = os.path.join(TMP_DIR, f"{aud_hash}.wav")
|
96 |
+
if not os.path.exists(aud_path):
|
97 |
+
with open(aud_path, "wb") as f: f.write(buf_a.getvalue())
|
98 |
+
|
99 |
+
# ── 결과 경로 ────────────────────────────────────────────────
|
100 |
+
out_path = os.path.join(
|
101 |
+
RES_DIR, f"{img_hash}_{aud_hash}_{dynamic_scale:.1f}.mp4"
|
102 |
+
)
|
103 |
+
|
104 |
if os.path.exists(out_path):
|
105 |
+
print(f"[INFO] Cache hit → {out_path}")
|
106 |
return out_path
|
107 |
|
108 |
+
print(f"[INFO] Generating video (dynamic_scale={dynamic_scale}) …")
|
109 |
+
return _render_video(img_path, aud_path, out_path, dynamic_scale)
|
|
|
|
|
|
|
110 |
|
111 |
# ------------------------------------------------------------------
|
112 |
+
# 6. Gradio UI
|
113 |
# ------------------------------------------------------------------
|
114 |
+
CSS = """
|
115 |
+
.gradio-container{font-family:Arial, sans-serif}
|
116 |
+
.main-header{text-align:center;color:#2a2a2a;margin-bottom:2em}
|
117 |
"""
|
118 |
|
119 |
+
with gr.Blocks(css=CSS) as demo:
|
120 |
+
gr.HTML("""
|
121 |
+
<div class="main-header">
|
122 |
+
<h1>🎭 Sonic - Portrait Animation</h1>
|
123 |
+
<p>Turn a single photo into a talking-head video (≤1 min audio)</p>
|
124 |
+
</div>""")
|
|
|
125 |
|
126 |
with gr.Row():
|
127 |
with gr.Column():
|
128 |
+
img_in = gr.Image(type="pil", label="Portrait Image")
|
129 |
+
aud_in = gr.Audio(label="Voice / Audio (≤60 s)", type="numpy")
|
130 |
+
scale = gr.Slider(0.5, 2.0, 1.0, step=0.1,
|
131 |
+
label="Animation Intensity")
|
132 |
+
btn = gr.Button("Generate Animation", variant="primary")
|
133 |
+
with gr.Column():
|
134 |
+
vid_out = gr.Video(label="Result")
|
135 |
+
|
136 |
+
btn.click(run_sonic, [img_in, aud_in, scale], vid_out)
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
|
138 |
demo.launch(share=True)
|