Files
LihonT/services/members/dub.py
cheb0chik 3540ac84ea LihonT 2.3.0 (Serena): profile music, AI video dubbing, PiP & bg play, fonts, cleaner
- Shared moderated MP3 profile music (with floating mini-player and MediaSession controls, zero bubble when absent)
- AI video dubbing into Russian with burned-in ASS subtitles inside AgentChat (`services/members/dub.py`)
- Picture-in-Picture 9:16 and background audio playback (`PlayControl` + `play_patch.py`)
- System/custom .ttf fonts & emoji packs (`FontsAndEmoji`), account cleaner (`AccountCleaner`)
- Feed blacklist, muted sound restoration, OLED burn-in shift, A/B flag editor, presets, long comments
- Updated site homepage (`src/web/index.html`) for LihonT 2.3.0 Serena
2026-11-26 15:40:32 +03:00

519 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""AI TikTok video dubbing into Russian for AgentChat.
Takes a TikTok video URL, downloads the watermark-free video (tikwm), extracts & transcribes speech
with timestamps via Groq Whisper (`whisper-large-v3-turbo`), translates segments into concise natural
Russian via the active LLM gate, synthesizes Russian speech, mixes a ducked original + non-overlapping
Russian TTS WAV track in Python, burns clean .ass subtitles, and renders MP4 via ffmpeg 4.3.
"""
from __future__ import annotations
import array
import json
import os
import re
import secrets
import shutil
import subprocess
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import wave
from pathlib import Path
import ai
TIKTOK_URL_RE = re.compile(
r"https://(?:vt\.|vm\.|www\.|m\.)?tiktok\.com/[^\s<>\"']{4,220}",
re.IGNORECASE,
)
JOB_ID_RE = re.compile(r"[0-9a-f]{24}\Z")
MAX_DURATION_SEC = 180
MAX_VIDEO_BYTES = 26_000_000
MAX_DUB_TTL_SEC = 2 * 3600
MAX_CONCURRENT_JOBS = 2
DAILY_LIMIT = 6
OWNER_DAILY_LIMIT = 100
SAMPLE_RATE = 24000
MAX_SEGMENTS = 32
GROQ_TRANSCRIBE_URL = "https://api.groq.com/openai/v1/audio/transcriptions"
TIKWM_API = "https://www.tikwm.com/api/"
GTTS_URL = "https://translate.google.com/translate_tts"
class DubError(ValueError):
pass
def extract_tiktok_url(text: str) -> str | None:
if not isinstance(text, str):
return None
m = TIKTOK_URL_RE.search(text.strip())
return m.group(0) if m else None
def resolve_tikwm(url: str, opener=urllib.request.urlopen) -> tuple[str, str]:
"""Resolves a TikTok URL via tikwm.com into (mp4_url, title)."""
body = urllib.parse.urlencode({"url": url, "hd": "1"}).encode("utf-8")
req = urllib.request.Request(
TIKWM_API,
data=body,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
},
)
with opener(req, timeout=20) as resp:
payload = json.loads(resp.read(1_000_000).decode("utf-8", "replace"))
if payload.get("code") != 0:
raise DubError("Не удалось получить видео по этой ссылке")
data = payload.get("data") or {}
dur = float(data.get("duration") or 0)
if dur > MAX_DURATION_SEC:
raise DubError("Видео длиннее 3 минут — выберите ролик покороче")
video_url = data.get("hdplay") or data.get("play") or data.get("wmplay") or ""
if not isinstance(video_url, str) or not video_url.startswith("https://"):
raise DubError("Не удалось найти видеопоток")
title = " ".join(str(data.get("title") or "").split())[:120]
return video_url, title
def download_file(url: str, dest: Path, max_bytes: int = MAX_VIDEO_BYTES, opener=urllib.request.urlopen) -> int:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
total = 0
with opener(req, timeout=45) as resp, dest.open("wb") as out:
while True:
chunk = resp.read(65536)
if not chunk:
break
total += len(chunk)
if total > max_bytes:
raise DubError("Видео слишком большое (макс. 25 МБ)")
out.write(chunk)
if total < 1024:
raise DubError("Скачался пустой видеофайл")
return total
def probe_video(video_path: Path) -> tuple[int, int, float, bool]:
"""Returns (width, height, duration_sec, has_audio)."""
out = subprocess.run(
["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(video_path)],
capture_output=True, timeout=15, check=False,
)
if out.returncode != 0:
raise DubError("Не удалось прочитать видео")
info = json.loads(out.stdout.decode("utf-8", "replace"))
streams = info.get("streams") or []
v = next((s for s in streams if s.get("codec_type") == "video"), None)
if v is None:
raise DubError("В файле нет видеодорожки")
w = int(v.get("width") or 720)
h = int(v.get("height") or 1280)
dur = float((info.get("format") or {}).get("duration") or v.get("duration") or 0)
if dur > MAX_DURATION_SEC:
raise DubError("Видео длиннее 3 минут — выберите ролик покороче")
has_audio = any(s.get("codec_type") == "audio" for s in streams)
return w, h, max(1.0, dur), has_audio
def extract_audio_mp3(video_path: Path, mp3_path: Path) -> None:
res = subprocess.run(
["ffmpeg", "-y", "-v", "error", "-i", str(video_path), "-vn",
"-ac", "1", "-ar", "16000", "-b:a", "48k", str(mp3_path)],
capture_output=True, timeout=45, check=False,
)
if res.returncode != 0 or not mp3_path.is_file() or mp3_path.stat().st_size < 128:
raise DubError("В видео нет звуковой дорожки")
def transcribe_groq(mp3_bytes: bytes, opener=urllib.request.urlopen) -> list[dict]:
key = os.environ.get("GROQ_KEY") or os.environ.get("GROQ_API_KEY") or ""
if not key:
raise DubError("На сервере не настроен ключ распознавания речи")
boundary = uuid.uuid4().hex
parts = [
f"--{boundary}\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nwhisper-large-v3-turbo\r\n".encode(),
f"--{boundary}\r\nContent-Disposition: form-data; name=\"response_format\"\r\n\r\nverbose_json\r\n".encode(),
f"--{boundary}\r\nContent-Disposition: form-data; name=\"timestamp_granularities[]\"\r\n\r\nsegment\r\n".encode(),
(
f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"audio.mp3\"\r\n"
"Content-Type: audio/mpeg\r\n\r\n"
).encode(),
mp3_bytes,
f"\r\n--{boundary}--\r\n".encode(),
]
req = urllib.request.Request(
GROQ_TRANSCRIBE_URL,
data=b"".join(parts),
headers={
"Authorization": "Bearer " + key,
"Content-Type": "multipart/form-data; boundary=" + boundary,
"User-Agent": "lihont-dub/1",
},
)
with opener(req, timeout=45) as resp:
data = json.loads(resp.read(2_000_000).decode("utf-8", "replace"))
raw_segments = data.get("segments") or []
segments = []
for seg in raw_segments:
text = " ".join(str(seg.get("text") or "").split()).strip()
if not text:
continue
start = max(0.0, float(seg.get("start") or 0.0))
end = max(start + 0.3, float(seg.get("end") or start + 1.0))
segments.append({"start": start, "end": end, "text": text})
if not segments and data.get("text"):
full = " ".join(str(data["text"]).split()).strip()
if full:
segments.append({"start": 0.0, "end": float(data.get("duration") or 5.0), "text": full})
if not segments:
raise DubError("В видео не удалось распознать речь")
return segments[:MAX_SEGMENTS]
def parse_translation_json(reply_text: str, count: int) -> list[str]:
cleaned = reply_text.strip()
fence = re.search(r"```(?:json)?\s*([\s\S]*?)```", cleaned)
if fence:
cleaned = fence.group(1).strip()
m = re.search(r"\[[\s\S]*\]", cleaned)
if not m:
raise DubError("Модель вернула неверный формат перевода")
arr = json.loads(m.group(0))
out = [""] * count
if isinstance(arr, list):
for idx, item in enumerate(arr):
if isinstance(item, dict):
pos = int(item.get("i", idx))
if 0 <= pos < count:
out[pos] = " ".join(str(item.get("ru") or item.get("text") or "").split()).strip()
elif isinstance(item, str) and idx < count:
out[idx] = " ".join(item.split()).strip()
if not any(out):
raise DubError("Не удалось перевести реплики")
return out
def translate_segments(ai_gate, segments: list[dict]) -> list[dict]:
items = [
{"i": i, "sec": round(max(0.5, s["end"] - s["start"]), 1), "text": s["text"]}
for i, s in enumerate(segments)
]
prompt = (
"Ты переводчик озвучки (дубляжа) коротких видео TikTok на живой естественный русский язык. "
"Переведи каждую реплику из JSON ниже. Делай фразы короткими и ёмкими, чтобы диктор успел прочитать за указанное время `sec`. "
"Верни ТОЛЬКО JSON-массив объектов вида [{\"i\":0,\"ru\":\"...\"}] без пояснений.\n\n"
+ json.dumps(items, ensure_ascii=False)
)
reply = ai_gate._ask([{"role": "user", "content": prompt}])
lines = parse_translation_json(reply, len(segments))
result = []
for seg, ru in zip(segments, lines):
result.append({
"start": seg["start"],
"end": seg["end"],
"src": seg["text"],
"ru": ru or seg["text"],
})
return result
def split_tts_chunks(text: str, limit: int = 180) -> list[str]:
text = " ".join(text.split()).strip()
if len(text) <= limit:
return [text] if text else []
chunks = []
while len(text) > limit:
cut = max(text.rfind(". ", 0, limit), text.rfind(", ", 0, limit), text.rfind(" ", 0, limit))
if cut < limit // 3:
cut = limit
chunks.append(text[:cut].strip())
text = text[cut:].strip(" ,")
if text:
chunks.append(text)
return chunks
def fetch_tts_mp3(text: str, opener=urllib.request.urlopen) -> bytes:
chunks = split_tts_chunks(text)
out = []
for chunk in chunks:
qs = urllib.parse.urlencode({"ie": "UTF-8", "client": "tw-ob", "tl": "ru", "q": chunk})
req = urllib.request.Request(GTTS_URL + "?" + qs, headers={"User-Agent": "Mozilla/5.0"})
with opener(req, timeout=15) as resp:
out.append(resp.read(500_000))
return b"".join(out)
def decode_tts_pcm(mp3_bytes: bytes, tmpdir: Path, idx: int, target_max_sec: float) -> array.array:
mp3_path = tmpdir / f"seg_{idx}.mp3"
pcm_path = tmpdir / f"seg_{idx}.pcm"
mp3_path.write_bytes(mp3_bytes)
probe = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", str(mp3_path)],
capture_output=True, timeout=10, check=False,
)
dur = 0.0
if probe.returncode == 0:
try:
dur = float((json.loads(probe.stdout.decode("utf-8", "replace")).get("format") or {}).get("duration") or 0)
except (ValueError, TypeError):
dur = 0.0
filters = []
if dur > 0.4 and target_max_sec >= 0.7 and dur > target_max_sec:
speed = min(1.38, max(1.0, dur / target_max_sec))
if speed > 1.04:
filters.append(f"atempo={speed:.3f}")
cmd = ["ffmpeg", "-y", "-v", "error", "-i", str(mp3_path)]
if filters:
cmd.extend(["-af", ",".join(filters)])
cmd.extend(["-f", "s16le", "-ac", "1", "-ar", str(SAMPLE_RATE), str(pcm_path)])
res = subprocess.run(cmd, capture_output=True, timeout=20, check=False)
if res.returncode != 0 or not pcm_path.is_file():
return array.array("h")
arr = array.array("h")
arr.frombytes(pcm_path.read_bytes())
return arr
def build_tts_track(segments: list[dict], total_duration: float, tmpdir: Path, tts_fn=fetch_tts_mp3) -> Path:
"""Synthesizes each translated segment and places samples sequentially onto a 24kHz mono WAV track."""
total_samples = max(SAMPLE_RATE, int((total_duration + 0.5) * SAMPLE_RATE))
buf = array.array("h", [0]) * total_samples
cursor = 0
for idx, seg in enumerate(segments):
ru = seg.get("ru") or ""
if not ru:
continue
mp3 = tts_fn(ru)
if not mp3:
continue
next_start = segments[idx + 1]["start"] if idx + 1 < len(segments) else total_duration
slot = max(0.8, next_start - seg["start"] - 0.05)
pcm = decode_tts_pcm(mp3, tmpdir, idx, slot)
if not pcm:
continue
start_sample = max(cursor, int(seg["start"] * SAMPLE_RATE))
if start_sample >= total_samples:
break
usable = min(len(pcm), total_samples - start_sample)
for j in range(usable):
buf[start_sample + j] = pcm[j]
cursor = start_sample + usable + int(0.05 * SAMPLE_RATE)
wav_path = tmpdir / "dub_ru.wav"
with wave.open(str(wav_path), "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SAMPLE_RATE)
wf.writeframes(buf.tobytes())
return wav_path
def _ass_time(sec: float) -> str:
sec = max(0.0, sec)
h = int(sec // 3600)
m = int((sec % 3600) // 60)
s = int(sec % 60)
cs = int(round((sec - int(sec)) * 100)) % 100
return f"{h}:{m:02d}:{s:02d}.{cs:02d}"
def build_ass(segments: list[dict], width: int, height: int) -> str:
font_size = max(24, round(min(width, height) * 0.052))
margin_v = max(48, round(height * 0.14))
margin_lr = max(24, round(width * 0.06))
lines = [
"[Script Info]",
"ScriptType: v4.00+",
f"PlayResX: {width}",
f"PlayResY: {height}",
"WrapStyle: 1",
"",
"[V4+ Styles]",
"Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, "
"Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, "
"Alignment, MarginL, MarginR, MarginV, Encoding",
f"Style: Default,DejaVu Sans,{font_size},&H00FFFFFF,&H00FFFFFF,&H00121218,&HA0121218,"
f"1,0,0,0,100,100,0,0,3,6,0,2,{margin_lr},{margin_lr},{margin_v},204",
"",
"[Events]",
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
]
for seg in segments:
ru = (seg.get("ru") or "").replace("\\", " ").replace("{", "(").replace("}", ")")
if not ru:
continue
lines.append(f"Dialogue: 0,{_ass_time(seg['start'])},{_ass_time(seg['end'])},Default,,0,0,0,,{ru}")
return "\n".join(lines) + "\n"
def render_dubbed_video(video_path: Path, tts_wav: Path, ass_path: Path, out_path: Path, has_audio: bool) -> None:
escaped_ass = str(ass_path).replace("\\", "/").replace(":", "\\:")
if has_audio:
audio_graph = (
"[0:a]volume=0.22[orig];[1:a]volume=1.35[ru];"
"[orig][ru]amix=inputs=2:duration=first:dropout_transition=0,volume=2.0,alimiter=limit=0.95[aout]"
)
else:
audio_graph = "[1:a]volume=1.2,alimiter=limit=0.95[aout]"
filter_complex = f"[0:v]ass='{escaped_ass}'[vout];{audio_graph}"
cmd = [
"ffmpeg", "-y", "-v", "error",
"-i", str(video_path),
"-i", str(tts_wav),
"-filter_complex", filter_complex,
"-map", "[vout]",
"-map", "[aout]",
"-c:v", "libx264", "-preset", "veryfast", "-crf", "24", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "128k",
"-shortest",
"-movflags", "+faststart",
str(out_path),
]
res = subprocess.run(cmd, capture_output=True, timeout=180, check=False)
if res.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 2048:
err = res.stderr.decode("utf-8", "replace")[:200]
raise DubError("Не получилось собрать видео: " + (err or "ошибка ffmpeg"))
class DubManager:
def __init__(self, registry, run_async=True):
self.r = registry
self.dir = Path(registry.art_dir).parent / "dubs"
self.run_async = run_async
self._lock = threading.Lock()
self._sem = threading.Semaphore(MAX_CONCURRENT_JOBS)
self._jobs: dict[str, dict] = {}
self.operations = {"dub_start": self.start, "dub_status": self.status}
def call(self, operation: str, payload: dict) -> dict:
return self.operations[operation](payload)
def _cleanup_old(self):
now = time.time()
try:
if self.dir.is_dir():
for f in self.dir.glob("*.mp4"):
if now - f.stat().st_mtime > MAX_DUB_TTL_SEC:
f.unlink(missing_ok=True)
except OSError:
pass
with self._lock:
stale = [k for k, v in self._jobs.items() if now - v["created_at"] > MAX_DUB_TTL_SEC]
for k in stale:
del self._jobs[k]
def file_path(self, job_id: str) -> Path | None:
if not isinstance(job_id, str) or not JOB_ID_RE.fullmatch(job_id):
return None
p = self.dir / f"{job_id}.mp4"
return p if p.is_file() else None
def start(self, p: dict) -> dict:
tg_id, _ = self.r.accounts._member(p)
url = extract_tiktok_url(str(p.get("url") or ""))
if not url:
raise ValueError("Нужна ссылка на видео TikTok")
day = self.r.ai._day()
cap = OWNER_DAILY_LIMIT if self.r.ai._owner(tg_id) else DAILY_LIMIT
usage_key = day + "#dub"
if not self.r.ai._take(tg_id, usage_key, cap):
raise ValueError("Daily limit reached (%d). Try again tomorrow" % cap)
self._cleanup_old()
job_id = secrets.token_hex(12)
with self._lock:
self._jobs[job_id] = {
"id": job_id,
"tg_id": tg_id,
"url": url,
"status": "queued",
"stage": "В очереди на озвучку…",
"summary": "",
"error": "",
"path": "",
"created_at": time.time(),
"usage_key": usage_key,
}
if self.run_async:
threading.Thread(target=self._run_job, args=(job_id,), name="lihont-dub-" + job_id[:6], daemon=True).start()
return {"job_id": job_id, "status": "queued", "stage": "В очереди на озвучку…"}
def status(self, p: dict) -> dict:
tg_id, _ = self.r.accounts._member(p)
job_id = str(p.get("job_id") or "")
if not JOB_ID_RE.fullmatch(job_id):
raise ValueError("Bad job id")
with self._lock:
job = self._jobs.get(job_id)
if job is None or job["tg_id"] != tg_id:
raise ValueError("Задача не найдена")
return {
"job_id": job_id,
"status": job["status"],
"stage": job["stage"],
"summary": job["summary"],
"error": job["error"],
"path": job["path"],
}
def _set(self, job_id: str, **updates):
with self._lock:
if job_id in self._jobs:
self._jobs[job_id].update(updates)
def _run_job(self, job_id: str):
job = self._jobs.get(job_id)
if job is None:
return
with self._sem:
try:
self._execute(job_id, job["url"])
except DubError as exc:
self.r.ai._give_back(job["tg_id"], job["usage_key"])
self._set(job_id, status="error", stage="Ошибка", error=str(exc))
except Exception as exc:
self.r.ai._give_back(job["tg_id"], job["usage_key"])
self._set(job_id, status="error", stage="Ошибка", error="Не удалось озвучить видео: " + str(exc)[:100])
def _execute(self, job_id: str, url: str):
self.dir.mkdir(parents=True, exist_ok=True)
out_path = self.dir / f"{job_id}.mp4"
with tempfile.TemporaryDirectory(prefix="lihont-dub-") as td:
tmp = Path(td)
self._set(job_id, status="downloading", stage="Скачиваю видео…")
video_url, _title = resolve_tikwm(url)
in_mp4 = tmp / "in.mp4"
download_file(video_url, in_mp4)
w, h, dur, has_audio = probe_video(in_mp4)
self._set(job_id, status="transcribing", stage="Распознаю речь и тайминги…")
src_mp3 = tmp / "src.mp3"
extract_audio_mp3(in_mp4, src_mp3)
segments = transcribe_groq(src_mp3.read_bytes())
self._set(job_id, status="translating", stage="Перевожу на русский…")
translated = translate_segments(self.r.ai, segments)
self._set(job_id, status="synthesizing", stage="Озвучиваю переведённые фразы…")
tts_wav = build_tts_track(translated, dur, tmp)
ass_path = tmp / "subs.ass"
ass_path.write_text(build_ass(translated, w, h), encoding="utf-8")
self._set(job_id, status="rendering", stage="Склеиваю видео с озвучкой и субтитрами…")
part = self.dir / f"{job_id}.part.mp4"
render_dubbed_video(in_mp4, tts_wav, ass_path, part, has_audio)
os.replace(part, out_path)
preview_lines = [seg["ru"] for seg in translated if seg.get("ru")]
summary = " · ".join(preview_lines[:3])
if len(summary) > 180:
summary = summary[:177] + "…"
self._set(job_id, status="done", stage="Готово", summary=summary, path="dub/" + job_id + ".mp4")