openfree commited on
Commit
2279f85
·
verified ·
1 Parent(s): 5d6304b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -216
app.py CHANGED
@@ -1,228 +1,127 @@
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)
 
1
+ # ---------------------------------------------------------
2
+ # app.py (2025-05 rev, aligned with latest sonic.py)
3
+ # ---------------------------------------------------------
4
+ import os, io, hashlib, numpy as np, gradio as gr, spaces
5
  from pydub import AudioSegment
 
 
 
6
  from PIL import Image
7
+ from sonic import Sonic
 
 
 
 
 
 
 
 
 
8
 
9
+ # ------------------------------------------------------------------
10
+ # 1) 모델 & 체크포인트 다운로드 (최초 1회)
11
+ # ------------------------------------------------------------------
12
+ os.system(
13
+ 'python3 -m pip install "huggingface_hub[cli]" accelerate -q; '
14
+ 'huggingface-cli download LeonJoe13/Sonic '
15
+ ' --local-dir checkpoints -q; '
16
+ 'huggingface-cli download stabilityai/stable-video-diffusion-img2vid-xt '
17
+ ' --local-dir checkpoints/stable-video-diffusion-img2vid-xt -q; '
18
+ 'huggingface-cli download openai/whisper-tiny '
19
+ ' --local-dir checkpoints/whisper-tiny -q'
20
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ pipe = Sonic() # GPU 초기화
23
+
24
+ # ------------------------------------------------------------------
25
+ def md5(b: bytes) -> str: # 빠른 32-byte 해시
26
+ return hashlib.md5(b).hexdigest()
27
+
28
+ TMP_DIR, RES_DIR = "./tmp_path", "./res_path"
29
+ os.makedirs(TMP_DIR, exist_ok=True)
30
+ os.makedirs(RES_DIR, exist_ok=True)
31
+
32
+ # ------------------------------------------------------------------
33
+ @spaces.GPU(duration=600) # 최대 10분까지 GPU 사용
34
+ def get_video_res(img_p: str, wav_p: str, out_p: str, scale: float):
35
+ """실제 Sonic 파이프라인 호출(얼굴 체크·프레임·interpolate 포함)"""
36
+ audio = AudioSegment.from_file(wav_p)
37
+ dur = len(audio) / 1000.0
38
+ steps = max(25, min(int(dur * 12.5), 750)) # 12.5fps 기준
39
+
40
+ print(f"[INFO] Audio duration {dur:.2f}s ➜ steps {steps}")
41
+
42
+ face = pipe.preprocess(img_p)
43
+ print("[INFO] Face detection:", face)
44
+ if face["face_num"] == 0:
45
+ return -1 # 얼굴 없음
46
+
47
+ pipe.process(img_p, wav_p, out_p,
48
+ min_resolution=512,
49
+ inference_steps=steps,
50
+ dynamic_scale=scale)
51
+ return out_p
52
+
53
+ # ------------------------------------------------------------------
54
+ def run_sonic(image, audio, scale):
55
+ """Gradio 버튼 연결 함수 (캐싱·전처리)"""
56
+ if image is None: raise gr.Error("Please upload an image.")
57
+ if audio is None: raise gr.Error("Please upload an audio file.")
58
+
59
+ # ---- 이미지 저장 & 해시 -------------------------------------------------
60
+ buf_img = io.BytesIO(); image.save(buf_img, "PNG")
61
+ img_key = md5(buf_img.getvalue())
62
+ img_path = os.path.join(TMP_DIR, f"{img_key}.png")
63
+ if not os.path.exists(img_path):
64
+ with open(img_path, "wb") as f: f.write(buf_img.getvalue())
65
+
66
+ # ---- 오디오 → mono/16kHz WAV (≤60 s) -----------------------------------
67
+ sr, arr = audio[:2]
68
+ arr = arr if arr.ndim == 2 else arr[:, None]
69
+ seg = AudioSegment(arr.tobytes(), frame_rate=sr,
70
+ sample_width=arr.dtype.itemsize,
71
+ channels=arr.shape[1]
72
+ ).set_channels(1).set_frame_rate(16_000)[:60_000]
73
+ buf_wav = io.BytesIO(); seg.export(buf_wav, format="wav")
74
+ wav_key = md5(buf_wav.getvalue())
75
+ wav_path = os.path.join(TMP_DIR, f"{wav_key}.wav")
76
+ if not os.path.exists(wav_path):
77
+ with open(wav_path, "wb") as f: f.write(buf_wav.getvalue())
78
+
79
+ # ---- 결과 파일 경로 -----------------------------------------------------
80
+ out_path = os.path.join(RES_DIR, f"{img_key}_{wav_key}_{scale}.mp4")
81
+
82
+ # ---- 캐시 확인 ---------------------------------------------------------
83
+ if os.path.exists(out_path):
84
+ print("[INFO] Cached video used.")
85
+ return out_path
86
+
87
+ print(f"[INFO] Generating video (scale={scale}) …")
88
+ res = get_video_res(img_path, wav_path, out_path, scale)
89
+ if res == -1:
90
+ raise gr.Error("No face detected in the image.")
91
+ return res
92
+
93
+ # ------------------------------------------------------------------
94
+ # Gradio UI
95
+ # ------------------------------------------------------------------
96
  css = """
97
+ .gradio-container {font-family: Arial, sans-serif;}
98
+ .main-header {text-align:center;color:#2a2a2a;margin-bottom:2em;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  """
100
 
101
  with gr.Blocks(css=css) as demo:
102
+ gr.HTML(
103
+ "<div class='main-header'>"
104
+ "<h1>🎭 Sonic: Portrait-to-Video Animator</h1>"
105
+ "<p>Create talking-head videos (≤60 s audio)</p>"
106
+ "</div>"
107
+ )
108
+
109
  with gr.Row():
110
  with gr.Column():
111
+ img_in = gr.Image(type="pil", label="Portrait Image")
112
+ aud_in = gr.Audio(type="numpy", label="Voice/Audio (≤60 s)")
113
+ scale = gr.Slider(0.5, 2.0, 1.0, 0.1,
114
+ label="Animation Intensity")
115
+ btn = gr.Button("Generate", variant="primary")
116
+ vid_out = gr.Video(label="Generated Animation")
117
+
118
+ btn.click(run_sonic, inputs=[img_in, aud_in, scale], outputs=vid_out)
119
+
120
+ gr.HTML(
121
+ "<div style='text-align:center;margin-top:1.5em'>"
122
+ "<a href='https://github.com/jixiaozhong/Sonic' target='_blank'>GitHub</a> | "
123
+ "<a href='https://arxiv.org/pdf/2411.16331' target='_blank'>Paper</a>"
124
+ "</div>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  )
126
+
127
+ demo.launch(share=True)