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

95 lines
4.2 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.

# -*- coding: utf-8 -*-
"""Hotfix source×channel analytics (API + FE) after relay room backfill."""
from __future__ import annotations
import sys
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/yt_studio_db.py",
"backend/app/main.py",
"frontend/src/app/youtube/analytics/[groupId]/page.tsx",
"frontend/src/app/youtube/analytics/page.tsx",
"frontend/src/components/YtAssignPanel.tsx",
]
REMOTE = r'''#!/bin/bash
set -euo pipefail
ROOT=/opt/douyinWEB
i=0
while [ -f "/tmp/_dy_src2_${i}.path" ]; do
rel=$(cat "/tmp/_dy_src2_${i}.path")
dst="$ROOT/$rel"
mkdir -p "$(dirname "$dst")"
python3 -c "from pathlib import Path; p=Path('/tmp/_dy_src2_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)"
i=$((i+1))
done
systemctl restart douyinweb-api.service
sleep 6
systemctl is-active douyinweb-api.service
cd "$ROOT/frontend"
npm run build >/tmp/dy_src2_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -60 /tmp/dy_src2_fe.log; exit 1; }
systemctl restart douyinweb-web.service
sleep 3
systemctl is-active douyinweb-web.service
/opt/douyinWEB/backend/.venv/bin/python - <<'PY'
import json, urllib.request, http.cookiejar
cj=http.cookiejar.CookieJar()
op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
op.open(urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST'), timeout=20)
gs=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/groups', timeout=30).read().decode())
groups=gs.get('groups') or []
print('groups', len(groups))
best=None
for g in groups[:8]:
gid=str(g.get('id'))
an=json.loads(op.open(f'http://127.0.0.1:8014/api/youtube/assign/groups/{gid}/analytics?days=30', timeout=120).read().decode())
ranks=[r for r in (an.get('source_rankings') or []) if r.get('measured')]
print('ch', g.get('name'), 'measured', len(ranks), 'slots', len(an.get('planning_slots') or []), 'sessions', (an.get('overview') or {}).get('session_count'))
if ranks and (best is None or ranks[0].get('score',0) > best[1]):
best=(g.get('name'), float(ranks[0].get('score') or 0), ranks[0])
if best:
t=best[2]
print('BEST', best[0], t.get('anchor_name'), t.get('room_id'), 'cover', bool(t.get('cover_url')), 'score', t.get('score'), 'avg', t.get('avg_viewers'), 'hours', [(h.get('label'), h.get('peak_viewers')) for h in (t.get('best_hours') or [])[:2]])
fleet=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/analytics/sources?days=30', timeout=300).read().decode())
print('fleet_ok', fleet.get('ok'), 'recs', len(fleet.get('recommendations') or []), 'rooms', len(fleet.get('rooms') or []))
if fleet.get('recommendations'):
r=fleet['recommendations'][0]
print('top_pair', r.get('anchor_name'), '->', r.get('channel_name'), 'score', r.get('score'), 'cover', bool(r.get('cover_url')))
PY
'''
def deploy(label, host, port, user, pw, *, sudo):
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 i, rel in enumerate(FILES):
data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
with sftp.file(f"/tmp/_dy_src2_{i}.bin", "wb") as f:
f.write(data)
with sftp.file(f"/tmp/_dy_src2_{i}.path", "w") as f:
f.write(rel.replace("\\", "/"))
with sftp.file("/tmp/_dy_src2_remote.sh", "w") as f:
f.write(REMOTE.replace("\r\n", "\n"))
sftp.close()
cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_src2_remote.sh" if sudo else "bash /tmp/_dy_src2_remote.sh"
_, o, e = c.exec_command(cmd, timeout=900)
print((o.read() + e.read()).decode("utf-8", "replace"))
c.close()
if __name__ == "__main__":
deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False)
deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True)
print("done")