Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / render-opengl-review-batch.py

Raw 7.5 KB on f7455f5645a899a3879cf752f3536fe6de471c90
1#!/usr/bin/env python3
2"""Render resumable, isolated preset review batches; never prune or change Finder tags."""
3import argparse, csv, datetime, hashlib, json, re, subprocess, time
4from pathlib import Path
5
6MUSIC_VOLUME = Path('/Volumes/Music')
7MEDIA_ROOT = MUSIC_VOLUME / 'Codex Media/PulseCanvas Studio'
8
9
10def sha(path):
11 return hashlib.sha256(path.read_bytes()).hexdigest()
12
13
14def run(command, **kwargs):
15 return subprocess.run(command, check=True, capture_output=True, **kwargs)
16
17
18def inspect_video(path):
19 info = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-show_streams', '-show_format', '-of', 'json', str(path)]).stdout)
20 video = next(s for s in info['streams'] if s['codec_type'] == 'video')
21 audio = next(s for s in info['streams'] if s['codec_type'] == 'audio')
22 rate = video['avg_frame_rate'].split('/')
23 duration = float(info['format']['duration'])
24 assert abs(duration - 10) < .06 and int(video['nb_read_frames']) == 300, info
25 assert (video['width'], video['height']) == (1280, 720) and int(rate[0])/int(rate[1]) == 30
26 pixels = run(['ffmpeg', '-v', 'error', '-i', str(path), '-vf', 'fps=1,scale=160:90', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']).stdout
27 assert len(pixels) >= 9 * 160 * 90 * 3
28 means = [sum(pixels[i:i+43200])/43200 for i in range(0,len(pixels)-43199,43200)]
29 return {'duration':duration,'decodedFrames':int(video['nb_read_frames']),'width':1280,'height':720,'fps':30,'audioCodec':audio['codec_name'],'sampledMeanRGB':means,'darkPreview':max(means)<2,'sha256':sha(path)}
30
31
32def main():
33 parser=argparse.ArgumentParser()
34 parser.add_argument('--source-root',type=Path,required=True)
35 parser.add_argument('--review-root',type=Path,default=MEDIA_ROOT/'Review and Renders/OpenGL-Effects-Review')
36 parser.add_argument('--work-root',type=Path,default=MEDIA_ROOT/'Render Work/OpenGL',help='Render scratch storage on the mounted Music drive.')
37 parser.add_argument('--batch',type=int,default=1)
38 parser.add_argument('--count',type=int,default=100)
39 parser.add_argument('--limit',type=int,help='Stop after this many completed clips; resume the same batch later.')
40 args=parser.parse_args();root=args.source_root.resolve();review=args.review_root.resolve();work_root=args.work_root.resolve()
41 if not MUSIC_VOLUME.is_mount():
42 parser.error('Mount the Music drive before rendering. No main-drive fallback is used.')
43 for destination in [review, work_root]:
44 if MUSIC_VOLUME != destination and MUSIC_VOLUME not in destination.parents:
45 parser.error('Review videos and render scratch files must be stored on /Volumes/Music.')
46 folder=review/f'Batch-{args.batch:03d}';folder.mkdir(parents=True,exist_ok=True)
47 work=work_root/f'batch-{args.batch:03d}';work.mkdir(parents=True,exist_ok=True)
48 catalog_path=root/'Sources/PulseCanvas/Resources/ProjectM/catalog.json';catalog=json.loads(catalog_path.read_text())
49 manifest_path=folder/'manifest.json'
50 if manifest_path.exists():
51 manifest=json.loads(manifest_path.read_text());assert manifest['catalogSHA256']==sha(catalog_path),'Catalog changed; preserve the old batch and use a new folder.'
52 assert manifest['requestedVideos']==args.count
53 for item in manifest['videos']:assert sha(folder/item['file'])==item['validation']['sha256'],'Existing rated video changed; do not overwrite it.'
54 else:
55 previous=review/f'Batch-{args.batch-1:03d}'/'manifest.json'
56 start=json.loads(previous.read_text())['nextCatalogIndex'] if args.batch>1 else 0
57 manifest={'batch':args.batch,'requestedVideos':args.count,'createdAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'sourceRoot':str(root),'catalogSHA256':sha(catalog_path),'catalogPresets':len(catalog),'startCatalogIndex':start,'nextCatalogIndex':start,'videos':[],'failures':[],'settings':{'durationSeconds':10,'warmupSeconds':2,'resolution':'1280x720','fps':30,'chaos':1,'brightness':1,'zoom':1,'motionBlur':0,'strobe':False,'audioStartSeconds':42,'intrinsicPresetColors':True},'status':'rendering'}
58 audio=work/'soundtrack-12s.wav'
59 if not audio.exists():run(['ffmpeg','-v','error','-ss','40','-i',str(root/'Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3'),'-t','12','-ar','44100','-ac','2','-c:a','pcm_s16le',str(audio)])
60 manifest['soundtrackSHA256']=sha(root/'Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3')
61 def save():
62 manifest['updatedAt']=datetime.datetime.now(datetime.timezone.utc).isoformat();temporary=manifest_path.with_suffix('.json.tmp');temporary.write_text(json.dumps(manifest,indent=2)+'\n');temporary.replace(manifest_path)
63 with (folder/'index.csv').open('w',newline='') as f:
64 writer=csv.writer(f);writer.writerow(['file','title','category','presetID','upstreamPath','originalTitle','presetSHA256','darkPreview'])
65 for v in manifest['videos']:writer.writerow([v['file'],v['title'],v['category'],v['id'],v['path'],v.get('originalTitle',''),v['presetSHA256'],v['validation']['darkPreview']])
66 save()
67 completed_this_run=0
68 while len(manifest['videos'])<args.count and manifest['nextCatalogIndex']<len(catalog):
69 index=manifest['nextCatalogIndex'];entry=catalog[index];number=index+1
70 title=re.sub(r'[/:\\\x00-\x1f]','-',entry['title'])
71 filename=f'{number:04d} - {title}.mp4';target=folder/filename
72 assert not target.exists(),'Refusing to overwrite a review clip with existing Finder tags.'
73 raw=work/f'{number:04d}-warmup.mp4';log=work/f'{number:04d}.log';began=time.monotonic()
74 print(f'RENDER {len(manifest["videos"])+1}/{args.count}: {filename}',flush=True)
75 try:
76 with log.open('wb') as f:
77 subprocess.run([str(root/'.build/curation/render-opengl-review'),str(index),str(audio),str(raw)],cwd=root,stdout=f,stderr=subprocess.STDOUT,check=True,timeout=180)
78 partial=work/f'{number:04d}-final.mp4'
79 run(['ffmpeg','-v','error','-ss','2','-i',str(raw),'-t','10','-map','0:v:0','-map','0:a:0','-c:v','h264_videotoolbox','-b:v','8M','-pix_fmt','yuv420p','-r','30','-c:a','aac','-b:a','192k','-movflags','+faststart','-metadata',f'title={entry["title"]}','-metadata',f'comment={entry["id"]}',str(partial)],timeout=60)
80 validation=inspect_video(partial)
81 partial.replace(target)
82 record=dict(entry,catalogIndex=index,file=filename,presetSHA256=sha(root/'Sources/PulseCanvas/Resources/ProjectM/Presets'/entry['path']),validation=validation,renderSeconds=round(time.monotonic()-began,2))
83 manifest['videos'].append(record);completed_this_run+=1
84 print(f'PASS {len(manifest["videos"])}/{args.count}: 300 decoded frames, 10s, audio, {record["renderSeconds"]}s render'+(' — dark preview flagged' if validation['darkPreview'] else ''),flush=True)
85 raw.unlink(missing_ok=True)
86 except Exception as error:
87 manifest['failures'].append(dict(entry,catalogIndex=index,error=str(error),log=str(log)))
88 print(f'FAILED {filename}: {error}; logged and continuing without changing the app library.',flush=True)
89 manifest['nextCatalogIndex']=index+1;save()
90 if args.limit and completed_this_run>=args.limit:break
91 if len(manifest['videos'])==args.count:manifest['status']='ready-for-review'
92 elif manifest['nextCatalogIndex']>=len(catalog):manifest['status']='catalog-exhausted'
93 save();print(f'BATCH {manifest["status"]}: {len(manifest["videos"])} videos, {len(manifest["failures"])} render failures, {folder}',flush=True)
94
95if __name__=='__main__':main()