Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,9 +6,11 @@ from pydub import AudioSegment
|
|
| 6 |
import hashlib
|
| 7 |
from sonic import Sonic
|
| 8 |
from PIL import Image
|
| 9 |
-
import torch
|
| 10 |
|
|
|
|
| 11 |
# 모델 초기화
|
|
|
|
| 12 |
cmd = (
|
| 13 |
'python3 -m pip install "huggingface_hub[cli]"; '
|
| 14 |
'huggingface-cli download LeonJoe13/Sonic --local-dir checkpoints; '
|
|
@@ -19,175 +21,160 @@ os.system(cmd)
|
|
| 19 |
|
| 20 |
pipe = Sonic()
|
| 21 |
|
|
|
|
|
|
|
|
|
|
| 22 |
def get_md5(content):
|
|
|
|
| 23 |
md5hash = hashlib.md5(content)
|
| 24 |
return md5hash.hexdigest()
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
def get_video_res(img_path, audio_path, res_video_path, dynamic_scale=1.0):
|
| 28 |
-
expand_ratio = 0.
|
| 29 |
min_resolution = 512
|
| 30 |
-
inference_steps = 25 # 2초 분량의 비디오(25 프레임)로 고정
|
| 31 |
|
| 32 |
-
# 오디오 길이(
|
| 33 |
audio = AudioSegment.from_file(audio_path)
|
| 34 |
-
duration = len(audio) / 1000.0 # 초
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
| 36 |
|
|
|
|
| 37 |
face_info = pipe.preprocess(img_path, expand_ratio=expand_ratio)
|
| 38 |
print(f"Face detection info: {face_info}")
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
dynamic_scale=dynamic_scale
|
| 54 |
-
)
|
| 55 |
-
return res_video_path
|
| 56 |
-
else:
|
| 57 |
-
return -1
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
| 61 |
os.makedirs(tmp_path, exist_ok=True)
|
| 62 |
os.makedirs(res_path, exist_ok=True)
|
| 63 |
|
|
|
|
|
|
|
|
|
|
| 64 |
def process_sonic(image, audio, dynamic_scale):
|
| 65 |
# 입력 검증
|
| 66 |
if image is None:
|
| 67 |
raise gr.Error("Please upload an image")
|
| 68 |
if audio is None:
|
| 69 |
raise gr.Error("Please upload an audio file")
|
| 70 |
-
|
| 71 |
img_md5 = get_md5(np.array(image))
|
| 72 |
audio_md5 = get_md5(audio[1])
|
| 73 |
-
print(f"Processing
|
| 74 |
-
|
|
|
|
| 75 |
sampling_rate, arr = audio[:2]
|
| 76 |
-
if
|
| 77 |
arr = arr[:, None]
|
| 78 |
-
|
| 79 |
-
# numpy array로부터 AudioSegment 생성
|
| 80 |
audio_segment = AudioSegment(
|
| 81 |
arr.tobytes(),
|
| 82 |
frame_rate=sampling_rate,
|
| 83 |
sample_width=arr.dtype.itemsize,
|
| 84 |
-
channels=arr.shape[1]
|
| 85 |
)
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
| 94 |
if not os.path.exists(image_path):
|
| 95 |
image.save(image_path)
|
| 96 |
if not os.path.exists(audio_path):
|
| 97 |
audio_segment.export(audio_path, format="wav")
|
| 98 |
-
|
| 99 |
-
# 캐시된 결과가 있으면 반환, 없으면 새로 생성
|
| 100 |
if os.path.exists(res_video_path):
|
| 101 |
print(f"Using cached result: {res_video_path}")
|
| 102 |
return res_video_path
|
| 103 |
-
else:
|
| 104 |
-
print(f"Generating new video with dynamic scale: {dynamic_scale}")
|
| 105 |
-
return get_video_res(image_path, audio_path, res_video_path, dynamic_scale)
|
| 106 |
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
def get_example():
|
|
|
|
| 109 |
return []
|
| 110 |
|
| 111 |
css = """
|
| 112 |
-
.gradio-container {
|
| 113 |
-
|
| 114 |
-
}
|
| 115 |
-
.
|
| 116 |
-
text-align: center;
|
| 117 |
-
color: #2a2a2a;
|
| 118 |
-
margin-bottom: 2em;
|
| 119 |
-
}
|
| 120 |
-
.parameter-section {
|
| 121 |
-
background-color: #f5f5f5;
|
| 122 |
-
padding: 1em;
|
| 123 |
-
border-radius: 8px;
|
| 124 |
-
margin: 1em 0;
|
| 125 |
-
}
|
| 126 |
-
.example-section {
|
| 127 |
-
margin-top: 2em;
|
| 128 |
-
}
|
| 129 |
"""
|
| 130 |
|
| 131 |
-
with gr.Blocks(css=css,theme="apriel") as demo:
|
| 132 |
-
gr.HTML(
|
|
|
|
| 133 |
<div class="main-header">
|
| 134 |
-
<h1>🎭 Sonic: Advanced Portrait Animation</h1>
|
| 135 |
-
<p>Transform still images into dynamic videos synchronized with audio</p>
|
| 136 |
</div>
|
| 137 |
-
|
| 138 |
-
|
|
|
|
| 139 |
with gr.Row():
|
| 140 |
with gr.Column():
|
| 141 |
-
image_input = gr.Image(
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
label="
|
| 149 |
-
|
| 150 |
-
type="numpy"
|
| 151 |
)
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
dynamic_scale = gr.Slider(
|
| 155 |
-
minimum=0.5,
|
| 156 |
-
maximum=2.0,
|
| 157 |
-
value=1.0,
|
| 158 |
-
step=0.1,
|
| 159 |
-
label="Animation Intensity",
|
| 160 |
-
info="Adjust to control movement intensity (0.5: subtle, 2.0: dramatic)"
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
process_btn = gr.Button(
|
| 164 |
-
"Generate Animation",
|
| 165 |
-
variant="primary",
|
| 166 |
-
elem_id="process_btn"
|
| 167 |
-
)
|
| 168 |
-
|
| 169 |
with gr.Column():
|
| 170 |
-
video_output = gr.Video(
|
| 171 |
-
|
| 172 |
-
elem_id="video_output"
|
| 173 |
-
)
|
| 174 |
-
|
| 175 |
process_btn.click(
|
| 176 |
fn=process_sonic,
|
| 177 |
inputs=[image_input, audio_input, dynamic_scale],
|
| 178 |
outputs=video_output,
|
| 179 |
-
api_name="animate"
|
| 180 |
)
|
| 181 |
-
|
| 182 |
gr.Examples(
|
| 183 |
examples=get_example(),
|
| 184 |
fn=process_sonic,
|
| 185 |
inputs=[image_input, audio_input, dynamic_scale],
|
| 186 |
outputs=video_output,
|
| 187 |
-
cache_examples=False
|
| 188 |
)
|
| 189 |
-
|
| 190 |
-
|
| 191 |
|
| 192 |
-
#
|
| 193 |
-
|
|
|
|
|
|
|
|
|
| 6 |
import hashlib
|
| 7 |
from sonic import Sonic
|
| 8 |
from PIL import Image
|
| 9 |
+
import torch # 필요 시 사용
|
| 10 |
|
| 11 |
+
# ------------------------------------------------------------------
|
| 12 |
# 모델 초기화
|
| 13 |
+
# ------------------------------------------------------------------
|
| 14 |
cmd = (
|
| 15 |
'python3 -m pip install "huggingface_hub[cli]"; '
|
| 16 |
'huggingface-cli download LeonJoe13/Sonic --local-dir checkpoints; '
|
|
|
|
| 21 |
|
| 22 |
pipe = Sonic()
|
| 23 |
|
| 24 |
+
# ------------------------------------------------------------------
|
| 25 |
+
# 유틸
|
| 26 |
+
# ------------------------------------------------------------------
|
| 27 |
def get_md5(content):
|
| 28 |
+
"""바이트/배열에서 md5 해시 문자열 반환"""
|
| 29 |
md5hash = hashlib.md5(content)
|
| 30 |
return md5hash.hexdigest()
|
| 31 |
|
| 32 |
+
# ------------------------------------------------------------------
|
| 33 |
+
# 비디오 생성
|
| 34 |
+
# ------------------------------------------------------------------
|
| 35 |
+
@spaces.GPU(duration=300) # 최대 5분까지 GPU 세션 유지
|
| 36 |
def get_video_res(img_path, audio_path, res_video_path, dynamic_scale=1.0):
|
| 37 |
+
expand_ratio = 0.0 # ★ 얼굴 크롭 방지
|
| 38 |
min_resolution = 512
|
|
|
|
| 39 |
|
| 40 |
+
# 오디오 길이 → 프레임 수 결정 (fps=25, 최대 60초=1500프레임)
|
| 41 |
audio = AudioSegment.from_file(audio_path)
|
| 42 |
+
duration = len(audio) / 1000.0 # 초
|
| 43 |
+
fps = 25
|
| 44 |
+
max_steps = fps * 60 # 1500
|
| 45 |
+
inference_steps = max(1, min(int(duration * fps), max_steps))
|
| 46 |
+
print(f"Audio duration: {duration:.2f}s → inference_steps: {inference_steps}")
|
| 47 |
|
| 48 |
+
# 얼굴 정보는 참고용으로만 출력
|
| 49 |
face_info = pipe.preprocess(img_path, expand_ratio=expand_ratio)
|
| 50 |
print(f"Face detection info: {face_info}")
|
| 51 |
+
if face_info["face_num"] == 0:
|
| 52 |
+
print("Warning: face not detected – proceeding with full image.")
|
| 53 |
|
| 54 |
+
# 출력 폴더 보장
|
| 55 |
+
os.makedirs(os.path.dirname(res_video_path), exist_ok=True)
|
| 56 |
+
|
| 57 |
+
# 비디오 생성
|
| 58 |
+
pipe.process(
|
| 59 |
+
img_path,
|
| 60 |
+
audio_path,
|
| 61 |
+
res_video_path,
|
| 62 |
+
min_resolution=min_resolution,
|
| 63 |
+
inference_steps=inference_steps,
|
| 64 |
+
dynamic_scale=dynamic_scale,
|
| 65 |
+
)
|
| 66 |
+
return res_video_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
# ------------------------------------------------------------------
|
| 69 |
+
# 캐시·경로 설정
|
| 70 |
+
# ------------------------------------------------------------------
|
| 71 |
+
tmp_path = "./tmp_path/"
|
| 72 |
+
res_path = "./res_path/"
|
| 73 |
os.makedirs(tmp_path, exist_ok=True)
|
| 74 |
os.makedirs(res_path, exist_ok=True)
|
| 75 |
|
| 76 |
+
# ------------------------------------------------------------------
|
| 77 |
+
# Gradio 콜백
|
| 78 |
+
# ------------------------------------------------------------------
|
| 79 |
def process_sonic(image, audio, dynamic_scale):
|
| 80 |
# 입력 검증
|
| 81 |
if image is None:
|
| 82 |
raise gr.Error("Please upload an image")
|
| 83 |
if audio is None:
|
| 84 |
raise gr.Error("Please upload an audio file")
|
| 85 |
+
|
| 86 |
img_md5 = get_md5(np.array(image))
|
| 87 |
audio_md5 = get_md5(audio[1])
|
| 88 |
+
print(f"Processing (img={img_md5}, audio={audio_md5})")
|
| 89 |
+
|
| 90 |
+
# numpy 오디오 → AudioSegment
|
| 91 |
sampling_rate, arr = audio[:2]
|
| 92 |
+
if arr.ndim == 1:
|
| 93 |
arr = arr[:, None]
|
|
|
|
|
|
|
| 94 |
audio_segment = AudioSegment(
|
| 95 |
arr.tobytes(),
|
| 96 |
frame_rate=sampling_rate,
|
| 97 |
sample_width=arr.dtype.itemsize,
|
| 98 |
+
channels=arr.shape[1],
|
| 99 |
)
|
| 100 |
+
|
| 101 |
+
# 경로
|
| 102 |
+
image_path = os.path.abspath(os.path.join(tmp_path, f"{img_md5}.png"))
|
| 103 |
+
audio_path = os.path.abspath(os.path.join(tmp_path, f"{audio_md5}.wav"))
|
| 104 |
+
res_video_path = os.path.abspath(
|
| 105 |
+
os.path.join(res_path, f"{img_md5}_{audio_md5}_{dynamic_scale}.mp4")
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# 저장 / 캐시
|
| 109 |
if not os.path.exists(image_path):
|
| 110 |
image.save(image_path)
|
| 111 |
if not os.path.exists(audio_path):
|
| 112 |
audio_segment.export(audio_path, format="wav")
|
| 113 |
+
|
|
|
|
| 114 |
if os.path.exists(res_video_path):
|
| 115 |
print(f"Using cached result: {res_video_path}")
|
| 116 |
return res_video_path
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
print(f"Generating new video (dynamic_scale={dynamic_scale})")
|
| 119 |
+
return get_video_res(image_path, audio_path, res_video_path, dynamic_scale)
|
| 120 |
+
|
| 121 |
+
# ------------------------------------------------------------------
|
| 122 |
+
# Gradio UI
|
| 123 |
+
# ------------------------------------------------------------------
|
| 124 |
def get_example():
|
| 125 |
+
"""예시 데이터 (필요 시 추가)"""
|
| 126 |
return []
|
| 127 |
|
| 128 |
css = """
|
| 129 |
+
.gradio-container { font-family: 'Arial', sans-serif; }
|
| 130 |
+
.main-header { text-align: center; color: #2a2a2a; margin-bottom: 2em; }
|
| 131 |
+
.parameter-section { background-color: #f5f5f5; padding: 1em; border-radius: 8px; margin: 1em 0; }
|
| 132 |
+
.example-section { margin-top: 2em; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
"""
|
| 134 |
|
| 135 |
+
with gr.Blocks(css=css, theme="apriel") as demo:
|
| 136 |
+
gr.HTML(
|
| 137 |
+
"""
|
| 138 |
<div class="main-header">
|
| 139 |
+
<h1>🎭 Longer Sonic: Advanced Portrait Animation</h1>
|
| 140 |
+
<p>Transform still images into dynamic videos synchronized with audio(Demo max 60sec)</p>
|
| 141 |
</div>
|
| 142 |
+
"""
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
with gr.Row():
|
| 146 |
with gr.Column():
|
| 147 |
+
image_input = gr.Image(type="pil", label="Portrait Image", elem_id="image_input")
|
| 148 |
+
audio_input = gr.Audio(label="Voice/Audio Input", elem_id="audio_input", type="numpy")
|
| 149 |
+
dynamic_scale = gr.Slider(
|
| 150 |
+
minimum=0.5,
|
| 151 |
+
maximum=2.0,
|
| 152 |
+
value=1.0,
|
| 153 |
+
step=0.1,
|
| 154 |
+
label="Animation Intensity",
|
| 155 |
+
info="Adjust to control movement intensity (0.5: subtle, 2.0: dramatic)",
|
|
|
|
| 156 |
)
|
| 157 |
+
process_btn = gr.Button("Generate Animation", variant="primary", elem_id="process_btn")
|
| 158 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
with gr.Column():
|
| 160 |
+
video_output = gr.Video(label="Generated Animation", elem_id="video_output")
|
| 161 |
+
|
|
|
|
|
|
|
|
|
|
| 162 |
process_btn.click(
|
| 163 |
fn=process_sonic,
|
| 164 |
inputs=[image_input, audio_input, dynamic_scale],
|
| 165 |
outputs=video_output,
|
| 166 |
+
api_name="animate",
|
| 167 |
)
|
| 168 |
+
|
| 169 |
gr.Examples(
|
| 170 |
examples=get_example(),
|
| 171 |
fn=process_sonic,
|
| 172 |
inputs=[image_input, audio_input, dynamic_scale],
|
| 173 |
outputs=video_output,
|
| 174 |
+
cache_examples=False,
|
| 175 |
)
|
|
|
|
|
|
|
| 176 |
|
| 177 |
+
# ------------------------------------------------------------------
|
| 178 |
+
# Launch
|
| 179 |
+
# ------------------------------------------------------------------
|
| 180 |
+
demo.launch(share=True)
|