Skip to content

Commit fde7660

Browse files
bazilinskyyclaude
andcommitted
Analysis: step times in the log; downloads that stall fail in 30 s; one stream request per video
Four weeks of worker logs (user, 2026-11-27: make the processing faster): lin5080 lost 95 h to yt-dlp downloads hanging until their 10-20 min timeouts, and batches killed as silent for 45 min lost ~100 h across the workers, most right after "analysing" (the 240p download has no time limit). - every yt-dlp call has --socket-timeout 30, and a clip's ffmpeg (--download-sections) -rw_timeout 30 s; ffmpeg reading the 720p stream too (_stream_ffmpeg) - whole downloads have a time limit (240p 30 min, 720p 60 min): a hung one fails the video, not the batch - the 720p stream's address is asked once per video (an hour): the opening, GPS overlay, maps, captions and rear camera each asked YouTube again, more requests and more "Sign in to confirm you're not a bot" - one log line per video with each step's own seconds ("step times"), yt-dlp, CLIP and tesseract by step Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 60a2ff4 commit fde7660

1 file changed

Lines changed: 76 additions & 5 deletions

File tree

‎propose_segments.py‎

Lines changed: 76 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@
128128
YT_DLP = os.environ.get('YT_DLP', 'yt-dlp')
129129

130130

131+
STALL_S = 30 # a connection silent this long has stalled (_yt_dlp, _stream_ffmpeg)
132+
133+
131134
class BotCheck(RuntimeError):
132135
"""YouTube wants a signed-in session; further requests will fail until it lifts."""
133136

@@ -144,7 +147,12 @@ def _yt_dlp(*args, timeout=None):
144147
# yt-dlp solves YouTube's JavaScript challenge only with a JS runtime and uses just deno unless told,
145148
# so offer node: without it YouTube hands out thumbnails instead of the video
146149
js = ['--js-runtimes', 'node'] if shutil.which('node') else []
147-
with subprocess.Popen([YT_DLP, '--no-warnings', *js, *cookies, *args], stdout=subprocess.PIPE,
150+
# a stalled connection fails in STALL_S instead of waiting out the timeout: on lin5080 305 downloads in 4 weeks
151+
# (2026-10-30 to 11-27) hung until it, 95 h; a clip's (--download-sections) through the ffmpeg yt-dlp runs
152+
stall = ['--socket-timeout', str(STALL_S)]
153+
if '--download-sections' in args:
154+
stall += ['--downloader-args', f'ffmpeg_i:-rw_timeout {STALL_S * 10 ** 6}']
155+
with subprocess.Popen([YT_DLP, '--no-warnings', *js, *cookies, *stall, *args], stdout=subprocess.PIPE,
148156
stderr=subprocess.PIPE, text=True, start_new_session=True) as proc:
149157
try:
150158
out, err = proc.communicate(timeout=timeout)
@@ -244,11 +252,15 @@ def fetch_metadata(video_id):
244252
}
245253

246254

255+
WHOLE_DOWNLOAD_S = 1800 # a whole video's download (240p; 720p twice that) still going after this has hung
256+
257+
247258
def download_low_res(video_id, out_dir):
248259
template = os.path.join(out_dir, f'{video_id}_low.%(ext)s')
249260
# H.264 first: OpenCV (YOLO, CLIP frames) cannot decode AV1 ("Missing Sequence Header", AbaoAmbience)
261+
# (a time limit: a download that hangs kept the batch silent until run_channels.py stopped it, its analysis lost)
250262
_yt_dlp('-q', '-f', 'bv*[height<=240][vcodec^=avc1]/bv*[height<=360][vcodec^=avc1]/bv*[height<=240][ext=mp4]'
251-
'/bv*[height<=360]/wv*', '-o', template, _url(video_id))
263+
'/bv*[height<=360]/wv*', '-o', template, _url(video_id), timeout=WHOLE_DOWNLOAD_S)
252264
for name in os.listdir(out_dir):
253265
if name.startswith(f'{video_id}_low.'):
254266
return os.path.join(out_dir, name)
@@ -3127,6 +3139,7 @@ def _parse_gps(text):
31273139
def _stream_ffmpeg(cmd):
31283140
"""ffmpeg reading frames of YouTube's stream, once more when it times out: YouTube is slow for a while at times
31293141
(lin5080, 2026-10-17: the opening, its caption and the GPS overlay lost on several videos; user: retry once)."""
3142+
cmd = [cmd[0], '-rw_timeout', str(STALL_S * 10 ** 6), *cmd[1:]] # a stalled read fails, not waits (STALL_S)
31303143
try:
31313144
return subprocess.run(cmd, capture_output=True, timeout=120)
31323145
except subprocess.TimeoutExpired:
@@ -3491,9 +3504,21 @@ def _overlay_text(stream, t):
34913504
return ''
34923505

34933506

3507+
_STREAMS = {} # video id -> (time, (url, headers)): one request for the steps reading its 720p stream
3508+
STREAM_REUSE_S = 3600 # YouTube's stream addresses last about 6 h
3509+
3510+
34943511
def _stream(video_id):
34953512
"""(url, HTTP headers) of the video's 720p stream: YouTube refuses it (403) without the headers yt-dlp asked
3496-
for it with."""
3513+
for it with. Asked once per STREAM_REUSE_S: the opening, the GPS overlay, maps, captions and the rear camera
3514+
each asked YouTube again (more requests, more "Sign in to confirm you're not a bot")."""
3515+
if (got := _STREAMS.get(video_id)) and time.time() - got[0] < STREAM_REUSE_S:
3516+
return got[1]
3517+
_STREAMS[video_id] = (time.time(), _stream_ask(video_id))
3518+
return _STREAMS[video_id][1]
3519+
3520+
3521+
def _stream_ask(video_id):
34973522
# an https stream first: ffmpeg seeks an HLS playlist slowly, past its timeout (lin5080 got only format 609 for
34983523
# Ejsknub-vjQ on 2026-11-13, an hour after mini and the workers got https ones)
34993524
m = json.loads(_yt_dlp('-j', '-f', 'bv*[height<=720][ext=mp4][protocol=https]/bv*[height<=720][protocol=https]/'
@@ -3626,7 +3651,7 @@ def rear_camera(video_id):
36263651
w = tempfile.mkdtemp(prefix='crowd_rear_')
36273652
try:
36283653
_yt_dlp('-q', '-f', 'bv*[height<=720][ext=mp4]/bv*[height<=720]', '-o', os.path.join(w, 'v.%(ext)s'),
3629-
_url(video_id))
3654+
_url(video_id), timeout=2 * WHOLE_DOWNLOAD_S)
36303655
path = next(os.path.join(w, n) for n in os.listdir(w) if n.startswith('v.'))
36313656
subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-vf',
36323657
f"fps=1/{REAR_STEP_S},crop=iw*0.32:ih*0.05:0:ih*0.905,scale=-2:120,format=gray,"
@@ -3751,7 +3776,7 @@ def read_signs(video_id, step=None, duration=None):
37513776
work_dir = tempfile.mkdtemp(prefix='crowd_signs_')
37523777
try:
37533778
_yt_dlp('-q', '-f', 'bv*[height<=720][ext=mp4]/bv*[height<=720]', '-o', os.path.join(work_dir, 'v.%(ext)s'),
3754-
_url(video_id))
3779+
_url(video_id), timeout=2 * WHOLE_DOWNLOAD_S)
37553780
path = next(os.path.join(work_dir, n) for n in os.listdir(work_dir) if n.startswith('v.'))
37563781
subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-vf', f'fps=1/{step}', '-q:v', '3',
37573782
os.path.join(work_dir, 's%05d.jpg')], capture_output=True, timeout=4 * 3600)
@@ -4612,6 +4637,8 @@ def night_from_title(segments, notes, sig, title):
46124637
def analyse_video(video_id, out_dir, meta=None, signs=False, keep=False):
46134638
"""Download a low resolution copy, propose segments, write a contact sheet; the copy is deleted, or with keep
46144639
left for the review page (LOCAL_KEPT). signs: also read the road signs (read_signs), for a drive between towns."""
4640+
STEP_TIMES['own'].clear()
4641+
started = time.time()
46154642
meta = meta or fetch_metadata(video_id)
46164643
work_dir = tempfile.mkdtemp(prefix='crowd_')
46174644
path = download_low_res(video_id, work_dir)
@@ -4713,6 +4740,7 @@ def analyse_video(video_id, out_dir, meta=None, signs=False, keep=False):
47134740
sig['on_bus'] = np.array(title_vehicle(title_text(meta.get('title') or '')) == 1)
47144741
segments, notes = night_from_title(*propose(sig), sig, meta.get('title'))
47154742
np.savez_compressed(os.path.join(out_dir, f'{video_id}_signals.npz'), **sig)
4743+
print(step_times_line(time.time() - started), flush=True)
47164744
return {'meta': meta, 'segments': segments, 'notes': notes}
47174745

47184746

@@ -13703,6 +13731,49 @@ def _apply(plan, log):
1370313731
app.run(host=os.environ.get('REVIEW_HOST', '127.0.0.1'), port=port, debug=False) # see review_hub.py
1370413732

1370513733

13734+
# how long each step of an analysis takes, one log line per video (user, 2026-11-27: "make the processing faster";
13735+
# 4 weeks of worker logs gave no step times): each step's own seconds, a step's time inside another timed step
13736+
# counted for the inner one only; yt-dlp and CLIP calls apart from the steps calling them
13737+
TIMED_STEPS = ('fetch_metadata', 'download_low_res', 'signals', 'skip_events', 'skip_norm', 'fade_events',
13738+
'dusk_colours', 'ghost_and_urban', 'garage_edges', 'lit_garages', 'car_park_stretches', 'parked_edges',
13739+
'parking_lots', 'kerb_stops', 'cross_traffic', 'walk_cadence', 'repeated_frames', 'clip_intro',
13740+
'clip_outro', 'town_scene_track', 'night_scene_track', 'night_clip_track', 'light_spots_track',
13741+
'aerial_track', 'driver_clip_track', 'step_bob_track', 'opening_texts', 'rear_camera', 'caption_end',
13742+
'montage_label', 'map_frame', 'read_signs', 'head_signs', 'gps_track', 'refine_clock_cuts',
13743+
'side_forward_track', 'off_road_track', 'contact_sheet', '_yt_dlp', '_clip_run', '_frame_text')
13744+
STEP_TIMES = {'stack': [], 'own': Counter()}
13745+
13746+
13747+
def _timed(name, fn):
13748+
"""fn, its own seconds added to STEP_TIMES['own'][name]; a yt-dlp, CLIP or tesseract call's under its step's
13749+
name too ("yt_dlp/head_signs")."""
13750+
@functools.wraps(fn)
13751+
def run(*args, **kwargs):
13752+
stack, t0 = STEP_TIMES['stack'], time.time()
13753+
key = name if not name.startswith('_') or not stack else f'{name.strip("_")}/{stack[-1][0]}'
13754+
stack.append([name.strip('_'), 0.0])
13755+
try:
13756+
return fn(*args, **kwargs)
13757+
finally:
13758+
spent = time.time() - t0
13759+
inner = stack.pop()[1]
13760+
STEP_TIMES['own'][key] += spent - inner
13761+
if stack:
13762+
stack[-1][1] += spent
13763+
return run
13764+
13765+
13766+
def step_times_line(total):
13767+
"""The log line of an analysis' step times (STEP_TIMES), the longest first, steps under 5 s left out."""
13768+
own = STEP_TIMES['own']
13769+
parts = [f'{k.strip("_")} {v:.0f}' for k, v in own.most_common() if v >= 5]
13770+
return f" step times (s, of {total:.0f}): {', '.join(parts)}"
13771+
13772+
13773+
for _name in TIMED_STEPS:
13774+
globals()[_name] = _timed(_name, globals()[_name])
13775+
13776+
1370613777
if __name__ == '__main__':
1370713778
ap = argparse.ArgumentParser(description=__doc__)
1370813779
ap.add_argument('--channel', metavar='URL', help='propose segments for every new video of a channel')

0 commit comments

Comments
 (0)