douyinWEB/scripts/_fix_audio_128k.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

126 lines
4.3 KiB
Python

# -*- coding: utf-8 -*-
"""Deploy AAC 128k + map fix, force-restart EvanVlogs push."""
from __future__ import annotations
import sys
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
CMD = r"""
set -e
while IFS= read -r line; do
[ -n "$line" ] || continue
export "$line"
done < <(systemctl show douyinweb-api -p Environment --value | tr ' ' '\n')
systemctl restart douyinweb-api
sleep 8
systemctl is-active douyinweb-api
cd /opt/douyinWEB/backend
.venv/bin/python <<'PY'
import json, time, subprocess, urllib.request, urllib.error
from app import db, yt_assign_db, youtube_relay_db, youtube_neko
from app.youtube_relay_pipeline import _group_in_active_slot
from app.youtube_relay_presets import resolve_relay_encoding
from app.session_auth import (
create_session_token, get_admin_credentials, SESSION_COOKIE,
ensure_default_admin_credentials, hash_password,
)
from app.config import settings
db.init_db()
ensure_default_admin_credentials()
db.update_settings_map({
'admin_username': str(settings.admin_username or 'hackrobot'),
'admin_password_hash': hash_password(str(settings.admin_password or '')),
'youtube_relay_enabled': True,
'youtube_relay_time_slot_mode': True,
})
enc = resolve_relay_encoding(db.get_settings_map())
print('audio_kbps', enc.get('audio_bitrate_kbps'), 'preset', enc.get('preset_id'))
user,_=get_admin_credentials(); token=create_session_token(user)
port=8014
def call(method, path, body=None, timeout=300):
data=None if body is None else json.dumps(body).encode()
req=urllib.request.Request(
f'http://127.0.0.1:{port}{path}', data=data, method=method,
headers={'Cookie': f'{SESSION_COOKIE}={token}', 'Content-Type':'application/json'},
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode())
call('POST','/api/youtube/relay/start')
winner=None
for g in yt_assign_db.list_groups(include_urls=False, include_secret=False):
if g.get('has_stream_key') and g.get('enabled') and _group_in_active_slot(str(g.get('id')), keyed_only=True):
winner=g; break
print('winner', (winner or {}).get('name'))
if not winner:
raise SystemExit('no winner')
gid=str(winner['id'])
# force restart: stop then start so new ffmpeg picks 128k + map
try:
print('stop', call('POST', f'/api/youtube/relay/groups/{gid}/stop'))
except Exception as e:
print('stop_err', e)
time.sleep(2)
# kill any leftover youtube ffmpeg
for line in subprocess.getoutput('ps -eo pid,cmd').splitlines():
if 'ffmpeg' in line and 'rtmps.youtube' in line:
pid=int(line.strip().split(None,1)[0])
subprocess.call(['kill', str(pid)])
print('killed', pid)
time.sleep(2)
keep=int(winner.get('neko_instance_id') or 0)
if keep:
print('neko', youtube_neko.ensure_instance_running(keep))
r=call('POST', f'/api/youtube/relay/groups/{gid}/start')
print('start', {k:r.get(k) for k in ('ok','ffmpeg_pid','error','waiting','reused')})
time.sleep(15)
st=youtube_relay_db.get_relay_state(gid) or {}
print('status', st.get('status'), 'pid', st.get('ffmpeg_pid'))
pid=int(st.get('ffmpeg_pid') or 0)
if pid:
cmd=open(f'/proc/{pid}/cmdline','rb').read().decode('utf-8','replace').replace('\0',' ')
for token in ('-b:a','-map','-profile:a','aac_low','128k','96k'):
print('HAS', token, token in cmd)
# show snippet around audio args
i=cmd.find('-pix_fmt')
print('CMD_AUDIO', cmd[i:i+220] if i>=0 else 'n/a')
PY
"""
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in (
"backend/app/youtube_relay.py",
"backend/app/youtube_relay_presets.py",
):
sftp.put(str(ROOT / rel), f"/opt/douyinWEB/{rel}")
print("uploaded", rel)
sftp.close()
_, o, e = c.exec_command(CMD, timeout=420)
print(o.read().decode("utf-8", "replace"))
err = e.read().decode("utf-8", "replace")
if err.strip():
print("STDERR", err[-2000:])
code = o.channel.recv_exit_status()
print("exit", code)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())