Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,135 +1,228 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import os, io, hashlib
|
| 5 |
import numpy as np
|
| 6 |
from pydub import AudioSegment
|
|
|
|
|
|
|
|
|
|
| 7 |
from PIL import Image
|
| 8 |
-
import
|
| 9 |
-
import spaces
|
| 10 |
-
|
| 11 |
-
from sonic import Sonic # ← 현재 수정-완료된 sonic.py 를 사용
|
| 12 |
-
|
| 13 |
-
# ------------------------------------------------------------------
|
| 14 |
-
# 1. 필요 리소스(모델) 자동 다운로드 ── HF Spaces에서는 캐시 활용
|
| 15 |
-
# ------------------------------------------------------------------
|
| 16 |
-
os.system(
|
| 17 |
-
'python3 -m pip install "huggingface_hub[cli]" accelerate -q; '
|
| 18 |
-
'huggingface-cli download LeonJoe13/Sonic '
|
| 19 |
-
' --local-dir checkpoints -q; '
|
| 20 |
-
'huggingface-cli download stabilityai/stable-video-diffusion-img2vid-xt '
|
| 21 |
-
' --local-dir checkpoints/stable-video-diffusion-img2vid-xt -q; '
|
| 22 |
-
'huggingface-cli download openai/whisper-tiny '
|
| 23 |
-
' --local-dir checkpoints/whisper-tiny -q'
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
pipe = Sonic() # GPU 메모리를 즉시 점유
|
| 27 |
-
|
| 28 |
-
# ------------------------------------------------------------------
|
| 29 |
-
# 2. 유틸
|
| 30 |
-
# ------------------------------------------------------------------
|
| 31 |
-
def md5(b: bytes) -> str:
|
| 32 |
-
return hashlib.md5(b).hexdigest()
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
# ------------------------------------------------------------------
|
| 38 |
-
# 3. Sonic 실행 (GPU 태그 10 min)
|
| 39 |
-
# ------------------------------------------------------------------
|
| 40 |
-
@spaces.GPU(duration=600)
|
| 41 |
-
def get_video_res(img_path, wav_path, out_path, dyn_scale=1.0):
|
| 42 |
-
"""실제 Sonic 파이프라인 실행."""
|
| 43 |
-
audio = AudioSegment.from_file(wav_path)
|
| 44 |
-
dur_s = len(audio) / 1000.0 # 초
|
| 45 |
|
| 46 |
-
# 프레임 수 ≈ 초당 12.5 → inference_steps
|
| 47 |
-
inf_steps = max(25, min(int(dur_s * 12.5), 750))
|
| 48 |
-
print(f"[INFO] Audio duration: {dur_s:.2f}s → inference_steps={inf_steps}")
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
print(f"[INFO] Face detection info: {face_info}")
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
arr = arr[:, None]
|
| 82 |
-
|
| 83 |
-
arr.tobytes(),
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
.
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
"""
|
| 116 |
|
| 117 |
-
with gr.Blocks(css=
|
| 118 |
gr.HTML("""
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
""")
|
| 124 |
-
|
| 125 |
with gr.Row():
|
| 126 |
with gr.Column():
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
demo.launch(share=True)
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import os
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
from pydub import AudioSegment
|
| 6 |
+
import hashlib
|
| 7 |
+
import io
|
| 8 |
+
from sonic import Sonic
|
| 9 |
from PIL import Image
|
| 10 |
+
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# 초기 실행 시 필요한 모델들을 다운로드
|
| 13 |
+
cmd = (
|
| 14 |
+
'python3 -m pip install "huggingface_hub[cli]" accelerate; '
|
| 15 |
+
'huggingface-cli download LeonJoe13/Sonic --local-dir checkpoints; '
|
| 16 |
+
'huggingface-cli download stabilityai/stable-video-diffusion-img2vid-xt --local-dir checkpoints/stable-video-diffusion-img2vid-xt; '
|
| 17 |
+
'huggingface-cli download openai/whisper-tiny --local-dir checkpoints/whisper-tiny;'
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
)
|
| 22 |
+
os.system(cmd)
|
| 23 |
+
|
| 24 |
+
pipe = Sonic()
|
| 25 |
+
|
| 26 |
+
def get_md5(content_bytes: bytes):
|
| 27 |
+
"""MD5 해시를 계산하여 32자리 문자열을 반환"""
|
| 28 |
+
return hashlib.md5(content_bytes).hexdigest()
|
| 29 |
+
|
| 30 |
+
tmp_path = './tmp_path/'
|
| 31 |
+
res_path = './res_path/'
|
| 32 |
+
os.makedirs(tmp_path, exist_ok=True)
|
| 33 |
+
os.makedirs(res_path, exist_ok=True)
|
| 34 |
+
|
| 35 |
+
@spaces.GPU(duration=600) # 긴 비디오 처리를 위해 duration 600초로 설정 (10분)
|
| 36 |
+
def get_video_res(img_path, audio_path, res_video_path, dynamic_scale=1.0):
|
| 37 |
+
"""
|
| 38 |
+
Sonic pipeline으로부터 실제 비디오를 생성하는 함수.
|
| 39 |
+
최대 60초 길이의 오디오에 대해 inference_steps를 결정하여,
|
| 40 |
+
얼굴 탐지 후 영상 생성 작업을 수행함.
|
| 41 |
+
"""
|
| 42 |
+
expand_ratio = 0.0
|
| 43 |
+
min_resolution = 512
|
| 44 |
+
|
| 45 |
+
# 오디오 길이 계산
|
| 46 |
+
audio = AudioSegment.from_file(audio_path)
|
| 47 |
+
duration = len(audio) / 1000.0 # 초 단위
|
| 48 |
+
|
| 49 |
+
# 오디오 길이에 따라 inference_steps 결정 (최소 25프레임 ~ 최대 750프레임)
|
| 50 |
+
inference_steps = min(max(int(duration * 12.5), 25), 750)
|
| 51 |
+
print(f"[INFO] Audio duration: {duration:.2f} seconds, using inference_steps={inference_steps}")
|
| 52 |
+
|
| 53 |
+
# 얼굴 인식
|
| 54 |
+
face_info = pipe.preprocess(img_path, expand_ratio=expand_ratio)
|
| 55 |
print(f"[INFO] Face detection info: {face_info}")
|
| 56 |
|
| 57 |
+
# 얼굴이 하나라도 검출되면 -> pipeline 진행
|
| 58 |
+
if face_info['face_num'] > 0:
|
| 59 |
+
os.makedirs(os.path.dirname(res_video_path), exist_ok=True)
|
| 60 |
+
pipe.process(
|
| 61 |
+
img_path,
|
| 62 |
+
audio_path,
|
| 63 |
+
res_video_path,
|
| 64 |
+
min_resolution=min_resolution,
|
| 65 |
+
inference_steps=inference_steps,
|
| 66 |
+
dynamic_scale=dynamic_scale
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
)
|
| 70 |
+
return res_video_path
|
| 71 |
+
else:
|
| 72 |
+
# 얼굴이 전혀 없으면 -1 리턴
|
| 73 |
+
return -1
|
| 74 |
+
|
| 75 |
+
def process_sonic(image, audio, dynamic_scale):
|
| 76 |
+
"""
|
| 77 |
+
Gradio 인터페이스에서 호출되는 함수:
|
| 78 |
+
1. 이미지/오디오 검사
|
| 79 |
+
2. MD5 해시 -> 파일명
|
| 80 |
+
3. 캐시 검사 -> 없으면 영상 생성
|
| 81 |
+
"""
|
| 82 |
+
if image is None:
|
| 83 |
+
raise gr.Error("Please upload an image")
|
| 84 |
+
if audio is None:
|
| 85 |
+
raise gr.Error("Please upload an audio file")
|
| 86 |
+
|
| 87 |
+
# (1) 이미지 MD5
|
| 88 |
+
buf_img = io.BytesIO()
|
| 89 |
+
image.save(buf_img, format="PNG")
|
| 90 |
+
img_bytes = buf_img.getvalue()
|
| 91 |
+
img_md5 = get_md5(img_bytes)
|
| 92 |
+
|
| 93 |
+
# (2) 오디오 MD5
|
| 94 |
+
sampling_rate, arr = audio[:2]
|
| 95 |
+
if len(arr.shape) == 1:
|
| 96 |
arr = arr[:, None]
|
| 97 |
+
audio_segment = AudioSegment(
|
| 98 |
+
arr.tobytes(),
|
| 99 |
+
frame_rate=sampling_rate,
|
| 100 |
+
sample_width=arr.dtype.itemsize,
|
| 101 |
+
channels=arr.shape[1]
|
| 102 |
+
)
|
| 103 |
+
# Whisper 호환을 위해 mono/16kHz로 변환
|
| 104 |
+
audio_segment = audio_segment.set_channels(1).set_frame_rate(16000)
|
| 105 |
+
|
| 106 |
+
MAX_DURATION_MS = 60000
|
| 107 |
+
if len(audio_segment) > MAX_DURATION_MS:
|
| 108 |
+
audio_segment = audio_segment[:MAX_DURATION_MS]
|
| 109 |
+
|
| 110 |
+
buf_audio = io.BytesIO()
|
| 111 |
+
audio_segment.export(buf_audio, format="wav")
|
| 112 |
+
audio_bytes = buf_audio.getvalue()
|
| 113 |
+
audio_md5 = get_md5(audio_bytes)
|
| 114 |
+
|
| 115 |
+
# (3) 파일 경로
|
| 116 |
+
image_path = os.path.abspath(os.path.join(tmp_path, f'{img_md5}.png'))
|
| 117 |
+
audio_path = os.path.abspath(os.path.join(tmp_path, f'{audio_md5}.wav'))
|
| 118 |
+
res_video_path = os.path.abspath(os.path.join(res_path, f'{img_md5}_{audio_md5}_{dynamic_scale}.mp4'))
|
| 119 |
+
|
| 120 |
+
if not os.path.exists(image_path):
|
| 121 |
+
with open(image_path, "wb") as f:
|
| 122 |
+
f.write(img_bytes)
|
| 123 |
+
if not os.path.exists(audio_path):
|
| 124 |
+
with open(audio_path, "wb") as f:
|
| 125 |
+
f.write(audio_bytes)
|
| 126 |
+
|
| 127 |
+
# (4) 캐싱된 결과가 있으면 재사용
|
| 128 |
+
if os.path.exists(res_video_path):
|
| 129 |
+
print(f"[INFO] Using cached result: {res_video_path}")
|
| 130 |
+
return res_video_path
|
| 131 |
+
else:
|
| 132 |
+
print(f"[INFO] Generating new video with dynamic_scale={dynamic_scale}")
|
| 133 |
+
video_result = get_video_res(image_path, audio_path, res_video_path, dynamic_scale)
|
| 134 |
+
return video_result
|
| 135 |
+
|
| 136 |
+
def get_example():
|
| 137 |
+
return []
|
| 138 |
+
|
| 139 |
+
css = """
|
| 140 |
+
.gradio-container {
|
| 141 |
+
font-family: 'Arial', sans-serif;
|
| 142 |
+
}
|
| 143 |
+
.main-header {
|
| 144 |
+
text-align: center;
|
| 145 |
+
color: #2a2a2a;
|
| 146 |
+
margin-bottom: 2em;
|
| 147 |
+
}
|
| 148 |
+
.parameter-section {
|
| 149 |
+
background-color: #f5f5f5;
|
| 150 |
+
padding: 1em;
|
| 151 |
+
border-radius: 8px;
|
| 152 |
+
margin: 1em 0;
|
| 153 |
+
}
|
| 154 |
+
.example-section {
|
| 155 |
+
margin-top: 2em;
|
| 156 |
+
}
|
| 157 |
"""
|
| 158 |
|
| 159 |
+
with gr.Blocks(css=css) as demo:
|
| 160 |
gr.HTML("""
|
| 161 |
+
<div class="main-header">
|
| 162 |
+
<h1>🎭 Sonic: Advanced Portrait Animation</h1>
|
| 163 |
+
<p>Transform still images into dynamic videos synchronized with audio (up to 1 minute)</p>
|
| 164 |
+
</div>
|
| 165 |
""")
|
| 166 |
+
|
| 167 |
with gr.Row():
|
| 168 |
with gr.Column():
|
| 169 |
+
image_input = gr.Image(
|
| 170 |
+
type='pil',
|
| 171 |
+
label="Portrait Image",
|
| 172 |
+
elem_id="image_input"
|
| 173 |
+
)
|
| 174 |
+
audio_input = gr.Audio(
|
| 175 |
+
label="Voice/Audio Input (up to 1 minute)",
|
| 176 |
+
elem_id="audio_input",
|
| 177 |
+
type="numpy"
|
| 178 |
+
)
|
| 179 |
+
with gr.Column():
|
| 180 |
+
dynamic_scale = gr.Slider(
|
| 181 |
+
minimum=0.5,
|
| 182 |
+
maximum=2.0,
|
| 183 |
+
value=1.0,
|
| 184 |
+
step=0.1,
|
| 185 |
+
label="Animation Intensity",
|
| 186 |
+
info="Adjust to control movement intensity (0.5: subtle, 2.0: dramatic)"
|
| 187 |
+
)
|
| 188 |
+
process_btn = gr.Button(
|
| 189 |
+
"Generate Animation",
|
| 190 |
+
variant="primary",
|
| 191 |
+
elem_id="process_btn"
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
with gr.Column():
|
| 195 |
+
video_output = gr.Video(
|
| 196 |
+
label="Generated Animation",
|
| 197 |
+
elem_id="video_output"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
process_btn.click(
|
| 201 |
+
fn=process_sonic,
|
| 202 |
+
inputs=[image_input, audio_input, dynamic_scale],
|
| 203 |
+
outputs=video_output,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
gr.Examples(
|
| 207 |
+
examples=get_example(),
|
| 208 |
+
fn=process_sonic,
|
| 209 |
+
inputs=[image_input, audio_input, dynamic_scale],
|
| 210 |
+
outputs=video_output,
|
| 211 |
+
cache_examples=False
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
gr.HTML("""
|
| 215 |
+
<div style="text-align: center; margin-top: 2em;">
|
| 216 |
+
<div style="margin-bottom: 1em;">
|
| 217 |
+
<a href="https://github.com/jixiaozhong/Sonic" target="_blank" style="text-decoration: none;">
|
| 218 |
+
<img src="https://img.shields.io/badge/GitHub-Repo-blue?style=for-the-badge&logo=github" alt="GitHub Repo">
|
| 219 |
+
</a>
|
| 220 |
+
<a href="https://arxiv.org/pdf/2411.16331" target="_blank" style="text-decoration: none;">
|
| 221 |
+
<img src="https://img.shields.io/badge/Paper-arXiv-red?style=for-the-badge&logo=arxiv" alt="arXiv Paper">
|
| 222 |
+
</a>
|
| 223 |
+
</div>
|
| 224 |
+
<p>🔔 Note: For optimal results, use clear portrait images and high-quality audio (now supports up to 1 minute!)</p>
|
| 225 |
+
</div>
|
| 226 |
+
""")
|
| 227 |
|
| 228 |
+
demo.launch(share=True)
|