617 lines
26 KiB
Python
617 lines
26 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Irregular upload scheduling — meet Beijing-day quota without metronomic spam.
|
||
|
||
Operator rules (Shorts live clips):
|
||
1. One Douyin room material → at most one Shorts channel (room-day uniqueness per channel).
|
||
2. Same channel uploads spaced ≥10 minutes normally; may compress only when behind deadline pace.
|
||
3. Prefer distinct Douyin rooms toward each channel's daily quota.
|
||
4. Within Beijing calendar day, prioritize meeting daily_min before daily_max.
|
||
5. Progress / 已满 = successful uploads only (not pending/queued).
|
||
6. Pace target: finish ~90% of fleet daily_max by Beijing 20:00; remaining 10% may use 20–24h.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import math
|
||
import random
|
||
import time
|
||
from typing import Any
|
||
|
||
from pathlib import Path
|
||
|
||
from . import db
|
||
from . import youtube_manage
|
||
from .timeutil import beijing_day_bounds, beijing_from_ts, beijing_now, push_date_from_ts
|
||
|
||
# Normal floor: same-channel upload interval must be >10 minutes.
|
||
CHANNEL_GAP_FLOOR_SEC = 600.0
|
||
GLOBAL_GAP_FLOOR_SEC = 300.0
|
||
# Behind 20:00 front-load pace / day-end catch-up.
|
||
EMERGENCY_CHANNEL_GAP_SEC = 90.0
|
||
EMERGENCY_GLOBAL_GAP_SEC = 45.0
|
||
|
||
# Finish this fraction of fleet daily_max by Beijing deadline hour.
|
||
QUOTA_DEADLINE_HOUR = 20
|
||
QUOTA_FRONTLOAD_RATIO = 0.90
|
||
|
||
|
||
def _day_end_ts(push_date: str) -> float:
|
||
"""Exclusive end of Beijing calendar day for push_date (next midnight)."""
|
||
return beijing_day_bounds(push_date)[1]
|
||
|
||
|
||
def _deadline_ts(push_date: str) -> float:
|
||
"""Beijing wall-clock target for front-loaded quota (default 20:00)."""
|
||
day_start, day_end = beijing_day_bounds(push_date)
|
||
return min(day_end - 30.0, day_start + float(QUOTA_DEADLINE_HOUR) * 3600.0)
|
||
|
||
|
||
def fleet_pace_plan(
|
||
push_date: str = "",
|
||
*,
|
||
now: float | None = None,
|
||
cfg: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Derive upload gaps from channel count + daily quotas vs Beijing 20:00 / 90% target."""
|
||
settings = cfg or db.get_settings_map()
|
||
now_ts = float(now if now is not None else time.time())
|
||
day = push_date or push_date_from_ts(now_ts)
|
||
day_start, day_end = beijing_day_bounds(day)
|
||
deadline = _deadline_ts(day)
|
||
summary = db.shorts_channels_quota_summary(day)
|
||
n_ch = max(1, len(summary))
|
||
uploaded = sum(int(r.get("uploaded") or r.get("used") or 0) for r in summary)
|
||
target = sum(int(r.get("daily_max") or 0) for r in summary)
|
||
if target <= 0:
|
||
target = n_ch * 9
|
||
front_target = max(1, int(math.ceil(float(QUOTA_FRONTLOAD_RATIO) * target)))
|
||
need_front = max(0, front_target - uploaded)
|
||
total_gap = sum(int(r.get("gap") or 0) for r in summary)
|
||
|
||
before_deadline = now_ts < deadline
|
||
span_to_deadline = max(1.0, deadline - day_start)
|
||
if before_deadline:
|
||
progress = max(0.0, min(1.0, (now_ts - day_start) / span_to_deadline))
|
||
time_left = max(60.0, deadline - now_ts)
|
||
else:
|
||
progress = 1.0
|
||
time_left = max(60.0, day_end - now_ts)
|
||
|
||
expected_by_now = int(front_target * progress) if before_deadline else front_target
|
||
behind = uploaded < expected_by_now and (need_front > 0 or total_gap > 0)
|
||
|
||
# Ideal global spacing so remaining front-load fits before deadline (fleet-wide).
|
||
ideal_global = time_left / max(1, need_front or total_gap or 1)
|
||
# Ideal per-channel: each channel still needs ~front_ratio*daily_max - used
|
||
per_ch_need = []
|
||
for r in summary:
|
||
dmax = max(1, int(r.get("daily_max") or 9))
|
||
used = int(r.get("uploaded") or r.get("used") or 0)
|
||
per_ch_need.append(max(0, int(math.ceil(QUOTA_FRONTLOAD_RATIO * dmax)) - used))
|
||
avg_ch_need = max(1, int(round(sum(per_ch_need) / max(1, len(per_ch_need))))) if per_ch_need else 1
|
||
ideal_channel = time_left / max(1, avg_ch_need)
|
||
|
||
configured_global = float(settings.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||
configured_channel = float(settings.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||
|
||
# When behind: use computed gaps (still respect floors unless truly impossible).
|
||
if behind or (before_deadline and need_front > 0 and progress > 0.15):
|
||
global_gap = min(configured_global, max(EMERGENCY_GLOBAL_GAP_SEC, ideal_global * 0.92))
|
||
channel_gap = min(configured_channel, max(CHANNEL_GAP_FLOOR_SEC, ideal_channel * 0.85))
|
||
# If even 10min/channel cannot finish fleet front-load, allow compress later via urgent.
|
||
slots_at_floor = (time_left / CHANNEL_GAP_FLOOR_SEC) * n_ch
|
||
urgent = need_front > slots_at_floor * 0.92 or (not before_deadline and total_gap > 0)
|
||
if urgent:
|
||
# Parallel channels: wall-clock ≈ need/n_ch * gap
|
||
per_wall = time_left / max(1.0, math.ceil(need_front / max(1, n_ch)))
|
||
channel_gap = max(EMERGENCY_CHANNEL_GAP_SEC, min(channel_gap, per_wall * 0.9))
|
||
global_gap = max(EMERGENCY_GLOBAL_GAP_SEC, min(global_gap, channel_gap * 0.75))
|
||
else:
|
||
# Ahead of pace: keep configured gaps, lightly stretch so we don't dump everything early.
|
||
global_gap = max(GLOBAL_GAP_FLOOR_SEC, configured_global)
|
||
channel_gap = max(CHANNEL_GAP_FLOOR_SEC, configured_channel, configured_global)
|
||
urgent = False
|
||
|
||
per_hour = (3600.0 / max(global_gap, 1.0)) if global_gap else 0.0
|
||
return {
|
||
"push_date": day,
|
||
"n_channels": n_ch,
|
||
"uploaded": uploaded,
|
||
"target": target,
|
||
"front_target": front_target,
|
||
"need_front": need_front,
|
||
"total_gap": total_gap,
|
||
"deadline_hour": QUOTA_DEADLINE_HOUR,
|
||
"deadline_ts": deadline,
|
||
"before_deadline": before_deadline,
|
||
"deadline_progress": round(progress, 4),
|
||
"expected_by_now": expected_by_now,
|
||
"behind": behind,
|
||
"urgent": urgent,
|
||
"time_left_sec": time_left,
|
||
"recommended_global_gap_sec": round(global_gap, 1),
|
||
"recommended_channel_gap_sec": round(channel_gap, 1),
|
||
"recommended_per_hour": round(per_hour, 2),
|
||
"frontload_ratio": QUOTA_FRONTLOAD_RATIO,
|
||
}
|
||
|
||
|
||
def _occupied_slots(push_date: str) -> list[tuple[float, str]]:
|
||
"""(upload_at_or_finished, channel_pk) for jobs that already claim a slot today."""
|
||
data = db.list_shorts_jobs(push_date=push_date, limit=500, offset=0)
|
||
slots: list[tuple[float, str]] = []
|
||
for j in data.get("jobs") or []:
|
||
st = str(j.get("status") or "")
|
||
ch = str(j.get("channel_pk") or "")
|
||
if st in {"scheduled", "recorded", "uploading"}:
|
||
ts = float(j.get("upload_at") or 0) or float(j.get("updated_at") or 0)
|
||
if ts > 0:
|
||
slots.append((ts, ch))
|
||
elif st in {"uploaded", "done"}:
|
||
ts = float(j.get("finished_at") or j.get("updated_at") or 0)
|
||
if ts > 0:
|
||
slots.append((ts, ch))
|
||
return slots
|
||
|
||
|
||
def _quota_pressure(
|
||
*,
|
||
channel_pk: str,
|
||
push_date: str,
|
||
now: float,
|
||
) -> tuple[float, float, bool, bool]:
|
||
"""Return (global_min_scale, channel_min_scale, behind_min, must_compress).
|
||
|
||
Scales against Beijing 20:00 / 90% front-load, not linear midnight pace.
|
||
"""
|
||
from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota
|
||
|
||
plan = fleet_pace_plan(push_date, now=now)
|
||
ch = db.get_shorts_channel(channel_pk) if channel_pk else None
|
||
used = db.shorts_channel_uploaded_count(channel_pk, push_date) if channel_pk else 0
|
||
daily_min = _normalize_daily_quota((ch or {}).get("daily_min"), default=SHORTS_DAILY_FORCE)
|
||
daily_max = _normalize_daily_quota((ch or {}).get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||
if daily_max < daily_min:
|
||
daily_max = daily_min
|
||
ch_front = max(1, int(math.ceil(QUOTA_FRONTLOAD_RATIO * daily_max)))
|
||
progress = float(plan.get("deadline_progress") or 0)
|
||
expected_ch = ch_front * progress if plan.get("before_deadline") else float(ch_front)
|
||
behind_min = used < daily_min and used < expected_ch
|
||
remaining_to_front = max(0, ch_front - used)
|
||
time_left = float(plan.get("time_left_sec") or 1)
|
||
must_compress = bool(plan.get("urgent")) or (
|
||
remaining_to_front > 0 and time_left < remaining_to_front * CHANNEL_GAP_FLOOR_SEC * 1.05
|
||
)
|
||
|
||
g_scale = 1.0
|
||
c_scale = 1.0
|
||
if plan.get("behind") or behind_min:
|
||
# Map recommended gaps onto configured floors via scale.
|
||
rec_g = float(plan.get("recommended_global_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||
rec_c = float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||
g_scale = min(1.0, rec_g / max(CHANNEL_GAP_FLOOR_SEC, 1.0))
|
||
c_scale = min(1.0, rec_c / max(CHANNEL_GAP_FLOOR_SEC, 1.0))
|
||
if must_compress:
|
||
g_scale = min(g_scale, 0.35)
|
||
c_scale = min(c_scale, 0.35)
|
||
return g_scale, c_scale, behind_min or bool(plan.get("behind")), must_compress
|
||
|
||
|
||
def _effective_gaps(
|
||
*,
|
||
channel_pk: str,
|
||
push_date: str,
|
||
now: float,
|
||
configured_global: float,
|
||
configured_channel: float,
|
||
) -> tuple[float, float, bool, bool]:
|
||
"""Scaled global/channel gaps; prefer fleet_pace_plan recommendations when behind."""
|
||
plan = fleet_pace_plan(push_date, now=now)
|
||
g_scale, c_scale, behind_min, urgent = _quota_pressure(
|
||
channel_pk=channel_pk, push_date=push_date, now=now
|
||
)
|
||
if plan.get("behind") or urgent:
|
||
global_min = float(plan.get("recommended_global_gap_sec") or GLOBAL_GAP_FLOOR_SEC)
|
||
channel_min = float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||
global_min = max(EMERGENCY_GLOBAL_GAP_SEC, min(configured_global, global_min))
|
||
channel_min = max(
|
||
EMERGENCY_CHANNEL_GAP_SEC if urgent else CHANNEL_GAP_FLOOR_SEC,
|
||
min(configured_channel, channel_min),
|
||
)
|
||
if not urgent:
|
||
channel_min = max(CHANNEL_GAP_FLOOR_SEC, channel_min)
|
||
global_min = max(GLOBAL_GAP_FLOOR_SEC, global_min)
|
||
else:
|
||
global_min = max(GLOBAL_GAP_FLOOR_SEC, configured_global * g_scale)
|
||
channel_min = max(CHANNEL_GAP_FLOOR_SEC, configured_channel * c_scale)
|
||
return global_min, channel_min, behind_min, urgent
|
||
|
||
|
||
def pick_upload_at(
|
||
*,
|
||
channel_pk: str,
|
||
push_date: str = "",
|
||
cfg: dict[str, Any] | None = None,
|
||
) -> float:
|
||
"""Pick upload time biased into Beijing 00:00–20:00 when still under 90% target."""
|
||
settings = cfg or db.get_settings_map()
|
||
now = time.time()
|
||
day = push_date or push_date_from_ts(now)
|
||
day_end = _day_end_ts(day)
|
||
deadline = _deadline_ts(day)
|
||
plan = fleet_pace_plan(day, now=now, cfg=settings)
|
||
# Soft cap: schedule inside front-load window while we still need 90% before 20:00.
|
||
if plan.get("before_deadline") and int(plan.get("need_front") or 0) > 0:
|
||
latest = min(day_end - 45.0, deadline - 30.0)
|
||
else:
|
||
latest = day_end - 45.0
|
||
latest = max(now + 20.0, latest)
|
||
|
||
if not settings.get("shorts_upload_spread", True):
|
||
return min(now + random.uniform(20, 120), latest)
|
||
|
||
configured_global = float(settings.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||
configured_channel = float(settings.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||
global_min, channel_min, behind_min, urgent = _effective_gaps(
|
||
channel_pk=channel_pk,
|
||
push_date=day,
|
||
now=now,
|
||
configured_global=max(GLOBAL_GAP_FLOOR_SEC, configured_global),
|
||
configured_channel=max(CHANNEL_GAP_FLOOR_SEC, configured_channel, configured_global),
|
||
)
|
||
|
||
if urgent or behind_min:
|
||
earliest = now + random.uniform(8, max(35.0, min(120.0, channel_min * 0.25)))
|
||
else:
|
||
# Ahead: mild jitter, still keep inside front-load window (not dump to 23:00).
|
||
earliest = now + random.uniform(60, min(900.0, channel_min * 0.8))
|
||
if earliest >= latest:
|
||
earliest = now + random.uniform(8, 45)
|
||
|
||
ch_last = db.shorts_channel_last_slot_ts(channel_pk, day) if channel_pk else 0.0
|
||
if ch_last > 0:
|
||
slotted = ch_last + channel_min + random.uniform(3, 25)
|
||
if (urgent or behind_min) and slotted > latest:
|
||
earliest = max(earliest, now + 8)
|
||
else:
|
||
earliest = max(earliest, slotted)
|
||
if urgent and earliest > latest:
|
||
return float(min(now + random.uniform(8, 25), max(now + 5, latest)))
|
||
|
||
slots = _occupied_slots(day)
|
||
|
||
def conflicts(ts: float) -> bool:
|
||
for other_ts, other_ch in slots:
|
||
gap = abs(ts - other_ts)
|
||
if gap < global_min * random.uniform(0.85, 1.15):
|
||
return True
|
||
if other_ch == channel_pk and gap < channel_min:
|
||
return True
|
||
return False
|
||
|
||
# Prefer near-term slots when behind; never sample the whole day until midnight.
|
||
if urgent or behind_min:
|
||
window_end = min(latest, max(earliest + 600.0, now + max(global_min * 4, 1800.0)))
|
||
else:
|
||
window_end = min(latest, max(earliest + 1800.0, now + 3 * 3600.0))
|
||
window_end = max(earliest + 60.0, window_end)
|
||
|
||
for _ in range(64):
|
||
if urgent or behind_min:
|
||
# Bias early: half near earliest, half uniform in short window.
|
||
if random.random() < 0.55:
|
||
cand = earliest + random.uniform(0, max(90.0, global_min * 1.2))
|
||
else:
|
||
cand = random.uniform(earliest, window_end)
|
||
else:
|
||
if random.random() < 0.4:
|
||
span = max(300.0, (window_end - earliest) / 6)
|
||
cand = earliest + random.expovariate(1.0 / span)
|
||
cand = min(cand, window_end)
|
||
else:
|
||
cand = random.uniform(earliest, window_end)
|
||
if cand < earliest:
|
||
cand = earliest + random.uniform(0, 90)
|
||
if not conflicts(cand):
|
||
return float(min(cand, latest))
|
||
|
||
last_ts = max((s[0] for s in slots), default=now)
|
||
cand = max(earliest, last_ts + random.uniform(global_min, global_min * 2.2))
|
||
ch_last2 = max((s[0] for s in slots if s[1] == channel_pk), default=ch_last)
|
||
if ch_last2:
|
||
cand = max(cand, ch_last2 + channel_min + random.uniform(3, 40))
|
||
return float(min(cand, latest))
|
||
|
||
|
||
def pull_forward_due_uploads(cfg: dict[str, Any] | None = None) -> int:
|
||
"""Reschedule far-future slots when behind Beijing 20:00 / 90% pace."""
|
||
settings = cfg or db.get_settings_map()
|
||
if not settings.get("shorts_auto_upload", True):
|
||
return 0
|
||
now = time.time()
|
||
day = push_date_from_ts(now)
|
||
plan = fleet_pace_plan(day, now=now, cfg=settings)
|
||
if int(plan.get("total_gap") or 0) <= 0:
|
||
return 0
|
||
# Always pull when behind front-load; also near midnight if still gapped.
|
||
if not plan.get("behind") and not plan.get("urgent"):
|
||
if plan.get("before_deadline") and float(plan.get("deadline_progress") or 0) < 0.85:
|
||
return 0
|
||
if float(plan.get("time_left_sec") or 0) > 7200 and int(plan.get("total_gap") or 0) < 20:
|
||
return 0
|
||
slam = bool(plan.get("urgent")) or (
|
||
not plan.get("before_deadline") and float(plan.get("time_left_sec") or 0) < 2400
|
||
)
|
||
behind = bool(plan.get("behind"))
|
||
rec_g = max(EMERGENCY_GLOBAL_GAP_SEC, float(plan.get("recommended_global_gap_sec") or GLOBAL_GAP_FLOOR_SEC))
|
||
rec_c = max(
|
||
EMERGENCY_CHANNEL_GAP_SEC if slam else CHANNEL_GAP_FLOOR_SEC,
|
||
float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC),
|
||
)
|
||
# When behind: anything parked beyond ~2× recommended global gap must come forward.
|
||
park_limit = now + (max(120.0, rec_g * 2.5) if (behind or slam) else 3600.0)
|
||
deadline = float(plan.get("deadline_ts") or _deadline_ts(day))
|
||
latest = min(_day_end_ts(day) - 45.0, deadline - 30.0) if plan.get("before_deadline") else _day_end_ts(day) - 45.0
|
||
|
||
data = db.list_shorts_jobs(push_date=day, status="scheduled", limit=300, offset=0)
|
||
extra = db.list_shorts_jobs(push_date=day, status="recorded", limit=100, offset=0)
|
||
jobs = list(data.get("jobs") or []) + list(extra.get("jobs") or [])
|
||
# Stable order: soonest first so we pack from "now"
|
||
jobs.sort(key=lambda j: float(j.get("upload_at") or 0) or 1e18)
|
||
|
||
# Cursor per channel + global for packing
|
||
next_global = now + random.uniform(5, 25)
|
||
next_ch: dict[str, float] = {}
|
||
moved = 0
|
||
for job in jobs:
|
||
if not str(job.get("clip_path") or "").strip():
|
||
continue
|
||
upload_at = float(job.get("upload_at") or 0)
|
||
if upload_at <= 0:
|
||
upload_at = now + 3600
|
||
if not slam and not behind and upload_at <= park_limit:
|
||
continue
|
||
if (behind or slam) and upload_at <= park_limit:
|
||
continue
|
||
ch_pk = str(job.get("channel_pk") or "")
|
||
if slam or behind:
|
||
cand = max(next_global, next_ch.get(ch_pk, now))
|
||
cand += random.uniform(2, 18)
|
||
cand = min(cand, max(now + 30.0, latest))
|
||
new_at = float(cand)
|
||
next_global = new_at + rec_g
|
||
next_ch[ch_pk] = new_at + rec_c
|
||
else:
|
||
new_at = pick_upload_at(channel_pk=ch_pk, push_date=day, cfg=settings)
|
||
if slam or behind or new_at < upload_at - 30:
|
||
db.update_shorts_job(str(job["id"]), upload_at=new_at, error="")
|
||
moved += 1
|
||
return moved
|
||
|
||
|
||
def schedule_board(limit: int = 24) -> dict[str, Any]:
|
||
"""Upcoming scheduled uploads + per-channel today usage for UI."""
|
||
day = push_date_from_ts(time.time())
|
||
now = time.time()
|
||
day_start, day_end = beijing_day_bounds(day)
|
||
seconds_left = max(0, int(day_end - now))
|
||
data = db.list_shorts_jobs(push_date=day, limit=500, offset=0)
|
||
upcoming: list[dict[str, Any]] = []
|
||
by_ch: dict[str, dict[str, int]] = {}
|
||
for j in data.get("jobs") or []:
|
||
ch = str(j.get("channel_pk") or "")
|
||
st = str(j.get("status") or "")
|
||
bucket = by_ch.setdefault(
|
||
ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0, "recorded": 0, "recording": 0}
|
||
)
|
||
if st in db._SHORTS_QUOTA_STATUSES:
|
||
bucket["used"] += 1
|
||
if st == "uploaded" or st == "done":
|
||
bucket["uploaded"] += 1
|
||
if st == "scheduled":
|
||
bucket["scheduled"] += 1
|
||
if st == "recorded":
|
||
bucket["recorded"] += 1
|
||
if st == "recording":
|
||
bucket["recording"] += 1
|
||
if st == "pending":
|
||
bucket["pending"] += 1
|
||
clip = str(j.get("clip_path") or "").strip()
|
||
clip_ready = bool(clip) and Path(clip).is_file()
|
||
if st == "scheduled" and clip_ready:
|
||
upcoming.append(j)
|
||
elif st == "recorded" and clip_ready:
|
||
upcoming.append(j)
|
||
upcoming.sort(
|
||
key=lambda x: (
|
||
float(x.get("upload_at") or 0) or float(x.get("updated_at") or 0),
|
||
float(x.get("created_at") or 0),
|
||
)
|
||
)
|
||
channels = db.list_shorts_channels(enabled=None)
|
||
channel_map = {str(c["id"]): c for c in channels}
|
||
enriched = []
|
||
orphan_pks: list[str] = []
|
||
for j in upcoming[: max(limit * 3, limit)]:
|
||
pk = str(j.get("channel_pk") or "")
|
||
ch = channel_map.get(pk, {})
|
||
if not ch:
|
||
if pk:
|
||
orphan_pks.append(pk)
|
||
continue
|
||
clip = str(j.get("clip_path") or "").strip()
|
||
clip_ready = bool(clip) and Path(clip).is_file()
|
||
enriched.append(
|
||
{
|
||
"id": j.get("id"),
|
||
"upload_at": j.get("upload_at"),
|
||
"anchor_name": j.get("anchor_name"),
|
||
"room_id": j.get("room_id"),
|
||
"channel_pk": j.get("channel_pk"),
|
||
"channel_name": ch.get("name") or "",
|
||
"oauth_profile_id": str(ch.get("oauth_profile_id") or "").strip().upper(),
|
||
"status": j.get("status"),
|
||
"clip_ready": clip_ready,
|
||
"can_upload_now": str(j.get("status") or "") in {"scheduled", "recorded"}
|
||
and clip_ready,
|
||
}
|
||
)
|
||
if len(enriched) >= limit:
|
||
break
|
||
if orphan_pks:
|
||
try:
|
||
db.purge_orphan_shorts_jobs(limit=200)
|
||
except Exception:
|
||
pass
|
||
channel_rows = []
|
||
day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start)))
|
||
total_gap = 0
|
||
min_unmet = 0
|
||
from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota
|
||
from .upload_timeline import build_timeline
|
||
from .yt_channel_meta import oauth_meta_from_channel
|
||
|
||
ypp_by_shorts = {}
|
||
try:
|
||
from . import yt_long_db
|
||
|
||
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
|
||
except Exception:
|
||
ypp_by_shorts = {}
|
||
|
||
for c in channels:
|
||
cid = str(c["id"])
|
||
daily_min = _normalize_daily_quota(c.get("daily_min"), default=SHORTS_DAILY_FORCE)
|
||
daily_max = _normalize_daily_quota(c.get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||
if daily_max < daily_min:
|
||
daily_max = daily_min
|
||
stats = by_ch.get(
|
||
cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0, "recorded": 0, "recording": 0}
|
||
)
|
||
pipeline = int(stats["used"])
|
||
uploaded = int(stats["uploaded"])
|
||
# UI progress / 缺 / 已满 = uploads only; pipeline stays in stats.used for ops.
|
||
gap = max(0, daily_max - uploaded)
|
||
min_met = uploaded >= daily_min
|
||
if c.get("enabled") and not min_met:
|
||
min_unmet += 1
|
||
if c.get("enabled"):
|
||
total_gap += gap
|
||
expected_min = daily_min * min(1.0, day_progress * 1.15 + 0.05)
|
||
meta = oauth_meta_from_channel(c)
|
||
channel_rows.append(
|
||
{
|
||
"id": cid,
|
||
"name": c.get("name"),
|
||
"youtube_channel_id": c.get("youtube_channel_id"),
|
||
"oauth_profile_id": str(c.get("oauth_profile_id") or "").strip().upper(),
|
||
"enabled": bool(c.get("enabled")),
|
||
"authorized": bool(str(c.get("refresh_token") or "").strip()),
|
||
"daily_min": daily_min,
|
||
"daily_max": daily_max,
|
||
"gap": gap,
|
||
"min_met": min_met,
|
||
"max_met": uploaded >= daily_max,
|
||
"behind_pace": bool(c.get("enabled") and uploaded < expected_min and uploaded < daily_min),
|
||
"pipeline": pipeline,
|
||
"yt_profile": youtube_manage._snippet_from_channel_row(c),
|
||
"last_status": str(c.get("last_status") or "offline"),
|
||
"last_title": str(c.get("last_title") or ""),
|
||
"last_live_url": str(c.get("last_live_url") or ""),
|
||
"oauth_ok": meta.get("oauth_ok", c.get("oauth_ok")),
|
||
"oauth_error": meta.get("oauth_error", str(c.get("oauth_error") or "")),
|
||
"brand_hint": meta.get("brand_hint") or "",
|
||
"note": str(c.get("note") or ""),
|
||
"ypp_ok": (
|
||
int(c.get("ypp_ok"))
|
||
if c.get("ypp_ok") is not None and int(c.get("ypp_ok")) in (0, 1)
|
||
else ypp_by_shorts.get(cid, -1)
|
||
),
|
||
**stats,
|
||
# Progress fields must win over stats.used (pipeline occupancy).
|
||
"used": uploaded,
|
||
"uploaded": uploaded,
|
||
"pipeline": pipeline,
|
||
}
|
||
)
|
||
timeline = build_timeline(enriched, now=now, day_start=day_start, day_end=day_end)
|
||
enabled_rows = [c for c in channel_rows if c.get("enabled")]
|
||
uploaded_total = sum(int(c.get("uploaded") or 0) for c in enabled_rows)
|
||
target_total = sum(int(c.get("daily_max") or 0) for c in enabled_rows)
|
||
pending_record = sum(int(c.get("pending") or 0) + int(c.get("recording") or 0) for c in enabled_rows)
|
||
queued_upload = sum(
|
||
int(c.get("scheduled") or 0) + int(c.get("recorded") or 0) for c in enabled_rows
|
||
)
|
||
clip_ready = sum(1 for x in enriched if str(x.get("status") or "") in {"scheduled", "recorded"})
|
||
plan = fleet_pace_plan(day, now=now)
|
||
hours_left = max(0.1, (day_end - now) / 3600.0)
|
||
hours_to_deadline = max(0.0, (float(plan["deadline_ts"]) - now) / 3600.0) if plan.get("before_deadline") else 0.0
|
||
impossible = total_gap > 0 and hours_left * 3600.0 < total_gap * CHANNEL_GAP_FLOOR_SEC * 0.85
|
||
warn = (
|
||
bool(plan.get("behind"))
|
||
or (total_gap >= 8 and hours_left < 4)
|
||
or impossible
|
||
or (pending_record >= 20 and hours_left < 2)
|
||
)
|
||
# Human order: uploaded/target first, then gap, then in-flight pipeline (not additive to gap).
|
||
parts: list[str] = [f"已上传 {uploaded_total}/{target_total or '—'}"]
|
||
if total_gap > 0:
|
||
parts.append(f"缺口 {total_gap}")
|
||
else:
|
||
parts.append("已满")
|
||
pipe_bits: list[str] = []
|
||
if queued_upload > 0:
|
||
pipe_bits.append(f"待传 {queued_upload}")
|
||
if pending_record > 0:
|
||
pipe_bits.append(f"待录 {pending_record}")
|
||
if pipe_bits:
|
||
parts.append("管道 " + " + ".join(pipe_bits))
|
||
else:
|
||
parts.append("管道空")
|
||
parts.append(f"剩 {hours_left:.1f}h")
|
||
parts.append(
|
||
f"目标{QUOTA_DEADLINE_HOUR}:00前{int(QUOTA_FRONTLOAD_RATIO * 100)}%"
|
||
f"({plan.get('uploaded')}/{plan.get('front_target')})"
|
||
)
|
||
if plan.get("behind"):
|
||
parts.append(
|
||
f"建议间隔≈{int(round(float(plan.get('recommended_global_gap_sec') or 0) / 60))}分"
|
||
f"/同频道≈{int(round(float(plan.get('recommended_channel_gap_sec') or 0) / 60))}分"
|
||
)
|
||
if impossible:
|
||
parts.append("日末加速中")
|
||
elif plan.get("behind"):
|
||
parts.append("落后已加速")
|
||
elif warn:
|
||
parts.append("节奏偏紧")
|
||
quota_forecast = {
|
||
"uploaded": uploaded_total,
|
||
"target": target_total,
|
||
"total_gap": total_gap,
|
||
"pending_record": pending_record,
|
||
"queued_upload": queued_upload,
|
||
"clip_ready": clip_ready,
|
||
"pending_uploads": queued_upload,
|
||
"hours_left": round(hours_left, 2),
|
||
"hours_to_deadline": round(hours_to_deadline, 2),
|
||
"per_hour_pace": round(float(plan.get("recommended_per_hour") or 0), 2),
|
||
"warn": warn,
|
||
"pace": plan,
|
||
"message": " · ".join(parts),
|
||
}
|
||
return {
|
||
"push_date": day,
|
||
"now": now,
|
||
"day_start": day_start,
|
||
"day_end": day_end,
|
||
"seconds_left": seconds_left,
|
||
"day_progress": round(day_progress, 4),
|
||
"total_gap": total_gap,
|
||
"min_unmet_channels": min_unmet,
|
||
"beijing_window": f"{day} 00:00–24:00",
|
||
"upcoming": enriched,
|
||
"timeline": timeline,
|
||
"quota_forecast": quota_forecast,
|
||
"channels": channel_rows,
|
||
"beijing_hint": beijing_from_ts(now).strftime("%Y-%m-%d %H:%M"),
|
||
}
|