Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -17,11 +17,11 @@ device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
| 17 |
print(f"Using device: {device}")
|
| 18 |
|
| 19 |
try:
|
| 20 |
-
# TTS модель казахск
|
| 21 |
tts_model = VitsModel.from_pretrained("facebook/mms-tts-kaz").to(device)
|
| 22 |
tts_tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-kaz")
|
| 23 |
|
| 24 |
-
#
|
| 25 |
translator = pipeline(
|
| 26 |
"translation",
|
| 27 |
model="facebook/nllb-200-distilled-600M",
|
|
@@ -31,11 +31,11 @@ try:
|
|
| 31 |
print("✅ Все модели успешно загружены!")
|
| 32 |
|
| 33 |
except Exception as e:
|
| 34 |
-
raise RuntimeError(f"Ошибка загрузки моделей: {str(e)}")
|
| 35 |
|
| 36 |
|
| 37 |
# =========================
|
| 38 |
-
# Talking Head
|
| 39 |
# =========================
|
| 40 |
|
| 41 |
TALKING_HEAD_SPACE = "Skywork/skyreels-a1-talking-head"
|
|
@@ -53,7 +53,9 @@ def inference(image: Image.Image, text: str):
|
|
| 53 |
img_path = None
|
| 54 |
|
| 55 |
try:
|
| 56 |
-
#
|
|
|
|
|
|
|
| 57 |
if image is None:
|
| 58 |
raise ValueError("Загрузите изображение лектора!")
|
| 59 |
|
|
@@ -63,7 +65,7 @@ def inference(image: Image.Image, text: str):
|
|
| 63 |
if len(text) > 500:
|
| 64 |
raise ValueError("Текст превышает 500 символов!")
|
| 65 |
|
| 66 |
-
print("Ввод (RU):", text)
|
| 67 |
|
| 68 |
# =========================
|
| 69 |
# Шаг 1 — Перевод
|
|
@@ -75,7 +77,10 @@ def inference(image: Image.Image, text: str):
|
|
| 75 |
)
|
| 76 |
|
| 77 |
translated_text = translation[0]["translation_text"]
|
| 78 |
-
print("Перевод (KK):", translated_text)
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
# =========================
|
| 81 |
# Шаг 2 — Озвучка
|
|
@@ -86,6 +91,10 @@ def inference(image: Image.Image, text: str):
|
|
| 86 |
output = tts_model(**inputs)
|
| 87 |
|
| 88 |
waveform = output.waveform.squeeze().cpu().numpy()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
audio = (waveform * 32767).astype("int16")
|
| 90 |
sampling_rate = tts_model.config.sampling_rate
|
| 91 |
|
|
@@ -93,8 +102,10 @@ def inference(image: Image.Image, text: str):
|
|
| 93 |
wavfile.write(f.name, sampling_rate, audio)
|
| 94 |
audio_path = f.name
|
| 95 |
|
|
|
|
|
|
|
| 96 |
# =========================
|
| 97 |
-
# Шаг 3 — Сохранение
|
| 98 |
# =========================
|
| 99 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
|
| 100 |
if image.mode != "RGB":
|
|
@@ -102,9 +113,12 @@ def inference(image: Image.Image, text: str):
|
|
| 102 |
image.save(f.name)
|
| 103 |
img_path = f.name
|
| 104 |
|
|
|
|
|
|
|
| 105 |
# =========================
|
| 106 |
# Шаг 4 — Генерация видео
|
| 107 |
# =========================
|
|
|
|
| 108 |
client = Client(TALKING_HEAD_SPACE)
|
| 109 |
|
| 110 |
result = client.predict(
|
|
@@ -115,22 +129,52 @@ def inference(image: Image.Image, text: str):
|
|
| 115 |
api_name="/process_image_audio"
|
| 116 |
)
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
else:
|
| 121 |
-
raise ValueError("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
error_msg = "✅ Видео успешно создано!"
|
| 124 |
|
| 125 |
except Exception as e:
|
| 126 |
error_msg = f"❌ Ошибка: {str(e)}"
|
|
|
|
| 127 |
traceback.print_exc()
|
| 128 |
|
| 129 |
finally:
|
|
|
|
|
|
|
|
|
|
| 130 |
for p in [audio_path, img_path]:
|
| 131 |
if p and os.path.exists(p):
|
| 132 |
try:
|
| 133 |
os.remove(p)
|
|
|
|
| 134 |
except:
|
| 135 |
pass
|
| 136 |
|
|
@@ -138,18 +182,18 @@ def inference(image: Image.Image, text: str):
|
|
| 138 |
|
| 139 |
|
| 140 |
# =========================
|
| 141 |
-
#
|
| 142 |
# =========================
|
| 143 |
|
| 144 |
-
title = "Бейне Оқытушы"
|
| 145 |
|
| 146 |
description = """
|
| 147 |
-
Суретіңізді жүктеп, дәріс мәтінін орыс тілінде енгізіңіз.
|
| 148 |
-
Жүйе автоматты түрде қазақ тіліне аударады және бейне
|
| 149 |
|
| 150 |
**Талаптар:**
|
| 151 |
- Фото: бет анық көрінетін
|
| 152 |
-
- Мәтін:
|
| 153 |
"""
|
| 154 |
|
| 155 |
iface = gr.Interface(
|
|
@@ -159,12 +203,12 @@ iface = gr.Interface(
|
|
| 159 |
gr.Textbox(
|
| 160 |
lines=5,
|
| 161 |
label="📝 Дәріс мәтіні (орыс тілінде)",
|
| 162 |
-
placeholder="
|
| 163 |
)
|
| 164 |
],
|
| 165 |
outputs=[
|
| 166 |
gr.Video(label="🎬 Дайын бейне"),
|
| 167 |
-
gr.Textbox(label="ℹ️ Мәртебе")
|
| 168 |
],
|
| 169 |
title=title,
|
| 170 |
description=description,
|
|
|
|
| 17 |
print(f"Using device: {device}")
|
| 18 |
|
| 19 |
try:
|
| 20 |
+
# TTS модель (казахский)
|
| 21 |
tts_model = VitsModel.from_pretrained("facebook/mms-tts-kaz").to(device)
|
| 22 |
tts_tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-kaz")
|
| 23 |
|
| 24 |
+
# Перевод ru -> kk
|
| 25 |
translator = pipeline(
|
| 26 |
"translation",
|
| 27 |
model="facebook/nllb-200-distilled-600M",
|
|
|
|
| 31 |
print("✅ Все модели успешно загружены!")
|
| 32 |
|
| 33 |
except Exception as e:
|
| 34 |
+
raise RuntimeError(f"❌ Ошибка загрузки моделей: {str(e)}")
|
| 35 |
|
| 36 |
|
| 37 |
# =========================
|
| 38 |
+
# Talking Head API
|
| 39 |
# =========================
|
| 40 |
|
| 41 |
TALKING_HEAD_SPACE = "Skywork/skyreels-a1-talking-head"
|
|
|
|
| 53 |
img_path = None
|
| 54 |
|
| 55 |
try:
|
| 56 |
+
# =========================
|
| 57 |
+
# Проверка входных данных
|
| 58 |
+
# =========================
|
| 59 |
if image is None:
|
| 60 |
raise ValueError("Загрузите изображение лектора!")
|
| 61 |
|
|
|
|
| 65 |
if len(text) > 500:
|
| 66 |
raise ValueError("Текст превышает 500 символов!")
|
| 67 |
|
| 68 |
+
print("📥 Ввод (RU):", text)
|
| 69 |
|
| 70 |
# =========================
|
| 71 |
# Шаг 1 — Перевод
|
|
|
|
| 77 |
)
|
| 78 |
|
| 79 |
translated_text = translation[0]["translation_text"]
|
| 80 |
+
print("🌍 Перевод (KK):", translated_text)
|
| 81 |
+
|
| 82 |
+
if not translated_text.strip():
|
| 83 |
+
raise ValueError("Перевод не удался!")
|
| 84 |
|
| 85 |
# =========================
|
| 86 |
# Шаг 2 — Озвучка
|
|
|
|
| 91 |
output = tts_model(**inputs)
|
| 92 |
|
| 93 |
waveform = output.waveform.squeeze().cpu().numpy()
|
| 94 |
+
|
| 95 |
+
if waveform.size == 0:
|
| 96 |
+
raise ValueError("TTS вернул пустое аудио!")
|
| 97 |
+
|
| 98 |
audio = (waveform * 32767).astype("int16")
|
| 99 |
sampling_rate = tts_model.config.sampling_rate
|
| 100 |
|
|
|
|
| 102 |
wavfile.write(f.name, sampling_rate, audio)
|
| 103 |
audio_path = f.name
|
| 104 |
|
| 105 |
+
print("🔊 Аудио создано:", audio_path)
|
| 106 |
+
|
| 107 |
# =========================
|
| 108 |
+
# Шаг 3 — Сохранение фото
|
| 109 |
# =========================
|
| 110 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
|
| 111 |
if image.mode != "RGB":
|
|
|
|
| 113 |
image.save(f.name)
|
| 114 |
img_path = f.name
|
| 115 |
|
| 116 |
+
print("🖼 Фото сохранено:", img_path)
|
| 117 |
+
|
| 118 |
# =========================
|
| 119 |
# Шаг 4 — Генерация видео
|
| 120 |
# =========================
|
| 121 |
+
print("🎥 Подключение к SkyReels...")
|
| 122 |
client = Client(TALKING_HEAD_SPACE)
|
| 123 |
|
| 124 |
result = client.predict(
|
|
|
|
| 129 |
api_name="/process_image_audio"
|
| 130 |
)
|
| 131 |
|
| 132 |
+
print("✅ RAW RESULT:", result)
|
| 133 |
+
|
| 134 |
+
# =========================
|
| 135 |
+
# Универсальный разбор результата
|
| 136 |
+
# =========================
|
| 137 |
+
|
| 138 |
+
if isinstance(result, tuple) and len(result) > 0:
|
| 139 |
+
video_data = result[0]
|
| 140 |
+
elif isinstance(result, dict):
|
| 141 |
+
video_data = result
|
| 142 |
else:
|
| 143 |
+
raise ValueError(f"Неизвестный формат ответа API: {type(result)}")
|
| 144 |
+
|
| 145 |
+
if isinstance(video_data, dict):
|
| 146 |
+
video_path = (
|
| 147 |
+
video_data.get("video")
|
| 148 |
+
or video_data.get("path")
|
| 149 |
+
or video_data.get("file")
|
| 150 |
+
)
|
| 151 |
|
| 152 |
+
elif isinstance(video_data, str):
|
| 153 |
+
video_path = video_data
|
| 154 |
+
|
| 155 |
+
else:
|
| 156 |
+
raise ValueError(f"Не удалось извлечь видео: {type(video_data)}")
|
| 157 |
+
|
| 158 |
+
if not video_path:
|
| 159 |
+
raise ValueError("API не вернул путь к видео!")
|
| 160 |
+
|
| 161 |
+
print("✅ Видео создано:", video_path)
|
| 162 |
error_msg = "✅ Видео успешно создано!"
|
| 163 |
|
| 164 |
except Exception as e:
|
| 165 |
error_msg = f"❌ Ошибка: {str(e)}"
|
| 166 |
+
print(error_msg)
|
| 167 |
traceback.print_exc()
|
| 168 |
|
| 169 |
finally:
|
| 170 |
+
# =========================
|
| 171 |
+
# Очистка временных файлов
|
| 172 |
+
# =========================
|
| 173 |
for p in [audio_path, img_path]:
|
| 174 |
if p and os.path.exists(p):
|
| 175 |
try:
|
| 176 |
os.remove(p)
|
| 177 |
+
print("🗑 Удалён файл:", p)
|
| 178 |
except:
|
| 179 |
pass
|
| 180 |
|
|
|
|
| 182 |
|
| 183 |
|
| 184 |
# =========================
|
| 185 |
+
# Интерфейс Gradio
|
| 186 |
# =========================
|
| 187 |
|
| 188 |
+
title = "🎓 Бейне Оқытушы"
|
| 189 |
|
| 190 |
description = """
|
| 191 |
+
Суретіңізді жүктеп, дәріс мәтінін **орыс тілінде** енгізіңіз.
|
| 192 |
+
Жүйе автоматты түрде қазақ тіліне аударады, озвучка жасайды және бейне шығарады!
|
| 193 |
|
| 194 |
**Талаптар:**
|
| 195 |
- Фото: бет анық көрінетін
|
| 196 |
+
- Мәтін: 500 таңбаға дейін
|
| 197 |
"""
|
| 198 |
|
| 199 |
iface = gr.Interface(
|
|
|
|
| 203 |
gr.Textbox(
|
| 204 |
lines=5,
|
| 205 |
label="📝 Дәріс мәтіні (орыс тілінде)",
|
| 206 |
+
placeholder="Мәтінді енгізіңіз..."
|
| 207 |
)
|
| 208 |
],
|
| 209 |
outputs=[
|
| 210 |
gr.Video(label="🎬 Дайын бейне"),
|
| 211 |
+
gr.Textbox(label="ℹ️ Мәртебе", interactive=False)
|
| 212 |
],
|
| 213 |
title=title,
|
| 214 |
description=description,
|