279 lines
11 KiB
Python
279 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Irregular 24h upload scheduling — avoid dense / metronomic YouTube uploads."""
|
||
from __future__ import annotations
|
||
|
||
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
|
||
|
||
|
||
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 _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)."""
|
||
ch = db.get_shorts_channel(channel_pk) if channel_pk else None
|
||
used = db.shorts_channel_upload_count(channel_pk, push_date) if channel_pk else 0
|
||
from .db import SHORTS_DAILY_FORCE
|
||
|
||
daily_max = SHORTS_DAILY_FORCE
|
||
daily_min = SHORTS_DAILY_FORCE
|
||
day_start, day_end = beijing_day_bounds(push_date)
|
||
span = max(1.0, day_end - day_start)
|
||
day_progress = max(0.0, min(1.0, (now - day_start) / span))
|
||
time_left = max(0.0, day_end - now)
|
||
remaining_slots = max(0, daily_max - used)
|
||
|
||
expected_min = daily_min * min(1.0, day_progress * 1.15 + 0.05)
|
||
behind_min = used < daily_min and used < expected_min
|
||
behind_max = remaining_slots > 0 and used < daily_max * day_progress * 0.9
|
||
must_compress = remaining_slots > 0 and time_left < 3600 * remaining_slots * 0.55
|
||
|
||
g_scale = 1.0
|
||
c_scale = 1.0
|
||
if behind_min:
|
||
g_scale = min(g_scale, 0.45)
|
||
c_scale = min(c_scale, 0.3)
|
||
elif behind_max and day_progress > 0.35:
|
||
g_scale = min(g_scale, 0.65)
|
||
c_scale = min(c_scale, 0.5)
|
||
if must_compress or (day_progress > 0.82 and remaining_slots > 0):
|
||
per_slot = time_left / max(1, remaining_slots)
|
||
c_scale = min(c_scale, max(0.15, per_slot / 2400.0))
|
||
g_scale = min(g_scale, max(0.2, c_scale * 0.75))
|
||
return g_scale, c_scale, behind_min, must_compress or (day_progress > 0.9 and remaining_slots > 0)
|
||
|
||
|
||
def pick_upload_at(
|
||
*,
|
||
channel_pk: str,
|
||
push_date: str = "",
|
||
cfg: dict[str, Any] | None = None,
|
||
) -> float:
|
||
"""Pick a jittered upload time within the Beijing day, avoiding clustering."""
|
||
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)
|
||
latest = day_end - 45
|
||
|
||
if not settings.get("shorts_upload_spread", True):
|
||
return min(now + random.uniform(20, 120), latest)
|
||
|
||
global_min = max(300.0, float(settings.get("shorts_upload_min_gap_sec") or 720))
|
||
channel_min = max(global_min, float(settings.get("shorts_channel_min_gap_sec") or 2400))
|
||
g_scale, c_scale, behind_min, urgent = _quota_pressure(
|
||
channel_pk=channel_pk, push_date=day, now=now
|
||
)
|
||
global_min *= g_scale
|
||
channel_min *= c_scale
|
||
|
||
if urgent or behind_min:
|
||
earliest = now + random.uniform(45, 240)
|
||
else:
|
||
earliest = now + random.uniform(180, 1500)
|
||
if earliest >= latest:
|
||
earliest = now + random.uniform(30, max(90.0, global_min * 0.4))
|
||
|
||
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 * random.uniform(0.9, 1.2):
|
||
return True
|
||
return False
|
||
|
||
window_end = max(earliest + 60, latest)
|
||
for _ in range(48):
|
||
if random.random() < 0.35:
|
||
span = max(600.0, (window_end - earliest) / 8)
|
||
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, 120)
|
||
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.8))
|
||
ch_last = max((s[0] for s in slots if s[1] == channel_pk), default=0.0)
|
||
if ch_last:
|
||
cand = max(cand, ch_last + random.uniform(channel_min, channel_min * 1.8))
|
||
return float(min(cand, latest))
|
||
|
||
|
||
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})
|
||
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 in {"pending", "recording"}:
|
||
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
|
||
|
||
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})
|
||
used = int(stats["used"])
|
||
gap = max(0, daily_max - used)
|
||
min_met = used >= 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)
|
||
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": used >= daily_max,
|
||
"behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min),
|
||
"yt_profile": youtube_manage._snippet_from_channel_row(c),
|
||
**stats,
|
||
}
|
||
)
|
||
timeline = build_timeline(enriched, now=now, day_start=day_start, day_end=day_end)
|
||
# Lightweight YT quota forecast: if many uploads still pending vs remaining day hours
|
||
pending_uploads = sum(1 for x in enriched if str(x.get("status") or "") in {"scheduled", "recorded"})
|
||
hours_left = max(0.1, (day_end - now) / 3600.0)
|
||
quota_forecast = {
|
||
"pending_uploads": pending_uploads,
|
||
"hours_left": round(hours_left, 2),
|
||
"per_hour_pace": round(pending_uploads / hours_left, 2) if hours_left else pending_uploads,
|
||
"warn": pending_uploads >= 8 and hours_left < 4,
|
||
"message": (
|
||
f"今日仍有 {pending_uploads} 条待传,约剩 {hours_left:.1f} 小时"
|
||
+ (",节奏偏紧,建议错开或延后低优任务" if pending_uploads >= 8 and hours_left < 4 else "")
|
||
),
|
||
}
|
||
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"),
|
||
}
|