douyinWEB/scripts/_deploy_shorts_room_offsets.py
2026-09-13 22:10:49 -05:00

133 lines
5.0 KiB
Python

# -*- coding: utf-8 -*-
"""Deploy Shorts multi-channel room offsets + heal empty clips; turn off global room dedupe."""
from __future__ import annotations
import json
import sys
import time
import http.cookiejar
import urllib.request
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB")
FILES = [
("backend/app/db.py", "/tmp/_dy_db.py"),
("backend/app/shorts_pipeline.py", "/tmp/_dy_sp.py"),
("backend/app/clip_cascade.py", "/tmp/_dy_cc.py"),
("backend/app/clip_retention.py", "/tmp/_dy_cr.py"),
]
REMOTE = r'''#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
pairs=[
('/tmp/_dy_db.py','/opt/douyinWEB/backend/app/db.py'),
('/tmp/_dy_sp.py','/opt/douyinWEB/backend/app/shorts_pipeline.py'),
('/tmp/_dy_cc.py','/opt/douyinWEB/backend/app/clip_cascade.py'),
('/tmp/_dy_cr.py','/opt/douyinWEB/backend/app/clip_retention.py'),
]
for s,d in pairs:
p=Path(s); dst=Path(d)
dst.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n'))
print('ok', dst)
PY
# Heal empty-clip scheduled jobs + force new dedupe setting
python3 <<'PY'
import sqlite3, datetime, time
BJ=datetime.timezone(datetime.timedelta(hours=8))
day=datetime.datetime.now(BJ).strftime('%Y-%m-%d')
now=time.time()
conn=sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db')
# migrate column
cols={r[1] for r in conn.execute('PRAGMA table_info(shorts_jobs)')}
if 'clip_offset_sec' not in cols:
conn.execute('ALTER TABLE shorts_jobs ADD COLUMN clip_offset_sec REAL NOT NULL DEFAULT 0')
print('added clip_offset_sec')
# settings
for k,v in [('shorts_dedupe_room_day','false'),('shorts_channel_min_gap_sec','600'),('shorts_upload_min_gap_sec','600'),('shorts_max_concurrent','3')]:
row=conn.execute('SELECT value FROM kv_settings WHERE key=?',(k,)).fetchone()
if row:
conn.execute('UPDATE kv_settings SET value=? WHERE key=?',(v,k))
else:
conn.execute('INSERT INTO kv_settings(key,value) VALUES(?,?)',(k,v))
print('kv',k,v)
# heal
cur=conn.execute("""
UPDATE shorts_jobs SET status='pending', clip_path='', clip_seconds=0, upload_at=0,
error='成片路径为空,已重新排队录制', finished_at=0, updated_at=?
WHERE push_date=? AND status IN ('scheduled','recorded','uploading')
AND IFNULL(youtube_video_id,'')='' AND IFNULL(clip_path,'')=''
""",(now,day))
print('healed_empty', cur.rowcount, 'day', day)
rows=conn.execute('SELECT status,COUNT(*) FROM shorts_jobs WHERE push_date=? GROUP BY status',(day,)).fetchall()
print('jobs', dict(rows))
conn.commit(); conn.close()
PY
systemctl restart douyinweb-api.service
sleep 6
systemctl is-active douyinweb-api.service
curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo
grep -n 'clip_offset_sec\|dedupe_room_global\|next_shorts_room_clip_offset' /opt/douyinWEB/backend/app/db.py /opt/douyinWEB/backend/app/shorts_pipeline.py | head -20
'''
def deploy(label, host, port, user, pw, sudo=False):
print(f"\n===== {label} =====")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for local, remote in FILES:
data = (ROOT / local).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
with sftp.file(remote, "wb") as f:
f.write(data)
with sftp.file("/tmp/_dy_room_off.sh", "w") as f:
f.write(REMOTE.replace("\r\n", "\n"))
sftp.close()
cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_room_off.sh" if sudo else "bash /tmp/_dy_room_off.sh"
_, o, e = c.exec_command(cmd, timeout=180)
print((o.read() + e.read()).decode("utf-8", "replace"))
c.close()
deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False)
deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True)
time.sleep(3)
base = "https://dylive.nomadro.com"
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
req = urllib.request.Request(
base + "/api/auth/login",
data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(),
method="POST",
headers={"Content-Type": "application/json"},
)
op.open(req, timeout=30)
# force settings via API too
req2 = urllib.request.Request(
base + "/api/settings",
data=json.dumps({"shorts_dedupe_room_day": False, "shorts_channel_min_gap_sec": 600, "shorts_max_concurrent": 3}).encode(),
method="PATCH",
headers={"Content-Type": "application/json"},
)
with op.open(req2, timeout=40) as r:
print("settings patched", bool(r.read()))
req3 = urllib.request.Request(base + "/api/shorts/fill-quota", data=b"{}", method="POST", headers={"Content-Type": "application/json"})
with op.open(req3, timeout=90) as r:
st = json.loads(r.read().decode())
print(
"fill just=", st.get("just_quota_filled"),
"active_rec=", st.get("active_records"),
"active_up=", st.get("active_uploads"),
"gap=", st.get("quota_gap"),
"pending-ish board unmet=", (st.get("board") or {}).get("min_unmet"),
)
print("done")