Branchwell

Jotley / website / scripts / video-refresh / build-gallery.py

1#!/usr/bin/env python3
2"""Build the portable HTML gallery for the completed website/social delivery."""
3import base64
4import hashlib
5import html
6import json
7from pathlib import Path
8import re
9import subprocess
10from fractions import Fraction
11from urllib.parse import quote
12
13ROOT = Path(__file__).resolve().parents[2]
14OUT = ROOT / 'output/video-refresh-20261023/workspace/delivery'
15CDN = 'https://media.jotley.ai/'
16
17
18def title(path):
19 name = path.stem
20 if re.match(r'jotley-marketing-v\d+', name):
21 return 'Marketing film' + (' · portrait' if 'portrait' in name else '')
22 if name.startswith('jotley-tutorial-'):
23 return 'Jotley on ' + {'iphone': 'iPhone', 'ipad': 'iPad', 'mac': 'Mac'}[name.split('-')[2]]
24 if name.startswith('jotley-social-ui'):
25 return 'Short social promo' + (' · portrait' if 'portrait' in name else ' · landscape')
26 if '-Portrait-Tutorial-' in name:
27 return name.split('-')[1] + ' · full portrait tutorial'
28 if '-Portrait-Clip-' in name:
29 device = name.split('-')[1]
30 label = re.sub(r'-1080x1920-60fps$', '', name.split('-Portrait-Clip-')[1])
31 return device + ' · ' + re.sub(r'^\d+-', '', label).replace('-', ' ')
32 return name.replace('-v2', '').replace('-v3', '').replace('-', ' ').replace('iphone', 'iPhone').replace('mac', 'Mac')
33
34
35def main():
36 posters = OUT / 'posters'
37 posters.mkdir(exist_ok=True)
38 files = []
39 for path in sorted(OUT.rglob('*.mp4')):
40 if 'qc' in path.parts or not path.with_suffix('.verification.json').exists():
41 continue
42 probe = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-show_streams', '-show_format', '-of', 'json', str(path)]))
43 stream = next(s for s in probe['streams'] if s['codec_type'] == 'video')
44 relative = path.relative_to(OUT).as_posix()
45 key = relative.removeprefix('website/') if relative.startswith('website/') else 'social/20261023/' + path.relative_to(OUT / 'social').as_posix()
46 group = ('Website films' if '/films/' in relative else 'Website screen clips' if '/clips/' in relative else
47 'Social feature clips' if '-Portrait-Clip-' in path.name else 'Social portrait tutorials' if '-Portrait-Tutorial-' in path.name else 'Social marketing')
48 variant = re.search(r'-(2160p|1080p|720p)$', path.stem)
49 variant = variant[1] if variant else '1080 × 1920' if stream['height'] == 1920 else f"{stream['width']} × {stream['height']}"
50 poster = posters / (path.stem + '.webp')
51 if not poster.exists():
52 subprocess.run(['ffmpeg', '-v', 'error', '-y', '-ss', str(min(2, float(probe['format']['duration']) / 3)), '-i', str(path),
53 '-frames:v', '1', '-vf', 'scale=640:-1', '-c:v', 'libwebp', '-quality', '85', str(poster)], check=True)
54 files.append({'title': title(path), 'group': group, 'variant': variant, 'local': relative, 'key': key, 'url': CDN + quote(key, safe='/'),
55 'poster': poster.relative_to(OUT).as_posix(), 'width': stream['width'], 'height': stream['height'],
56 'seconds': float(probe['format']['duration']), 'fps': float(Fraction(stream['avg_frame_rate'])), 'bytes': path.stat().st_size,
57 'sha256': hashlib.file_digest(path.open('rb'), 'sha256').hexdigest()})
58 (OUT / 'videos.json').write_text(json.dumps(files, indent=2) + '\n')
59 grouped = {}
60 for file in files:
61 grouped.setdefault((file['group'], file['title']), []).append(file)
62 sections = []
63 for group in ['Website films', 'Social marketing', 'Social portrait tutorials', 'Social feature clips', 'Website screen clips']:
64 cards = []
65 for (category, label), variants in grouped.items():
66 if category != group:
67 continue
68 selected = next((f for f in variants if f['variant'] == '1080p'), variants[0])
69 data = html.escape(json.dumps(variants), quote=True)
70 seconds = round(selected['seconds'])
71 duration = f'{seconds // 60}:{seconds % 60:02d}'
72 options = ''.join(f'<option value="{i}" {"selected" if f is selected else ""}>{html.escape(f["variant"])}</option>' for i, f in enumerate(variants))
73 links = ' · '.join(f'<a href="{html.escape(f["url"])}" download>{html.escape(f["variant"])}</a>' for f in variants)
74 portrait = selected['height'] > selected['width']
75 marketing = bool(re.match(r'jotley-marketing-v\d+', Path(selected['local']).stem))
76 search = group + ' ' + label + (' six accent colors neutral gray titles tags' if marketing else '')
77 chapter = '<button type="button" data-jump="35.2">Titles &amp; tags · 0:35</button><button type="button" data-jump="54">Six colors · 0:54</button>' if marketing else ''
78 captions = ''
79 if selected['local'].startswith('website/films/jotley-tutorial-'):
80 stem = re.sub(r'-(2160p|1080p|720p)$', '', Path(selected['local']).stem)
81 captions = f'<track kind="captions" srclang="en" label="English" src="https://media.jotley.ai/films/{stem}.vtt">'
82 poster_data = 'data:image/webp;base64,' + base64.b64encode((OUT / selected['poster']).read_bytes()).decode()
83 cards.append(f'''<article data-search="{html.escape(search)}" data-files="{data}">
84<div class="screen {'portrait' if portrait else ''}"><video controls playsinline preload="none" crossorigin="anonymous" poster="{poster_data}" src="{selected['url']}">{captions}</video></div>
85<div class="info"><h3>{html.escape(label)}</h3><p class="meta">{duration} · {selected['width']} × {selected['height']} · {selected['fps']:g} fps</p>
86<div class="actions"><label>Quality <select aria-label="Quality for {html.escape(label)}">{options}</select></label><span class="downloads">{links}</span>{chapter}</div></div></article>''')
87 sections.append(f'<section id="{group.lower().replace(" ", "-")}"><h2>{group}</h2><div class="grid">' + ''.join(cards) + '</div></section>')
88 document = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
89<title>Jotley · Website & Social Video Library</title><style>
90:root{color-scheme:dark;font-family:system-ui,-apple-system,sans-serif;background:#100b18;color:#f7f3fc}*{box-sizing:border-box}body{margin:0}main{max-width:1480px;margin:auto;padding:48px 28px}header{max-width:880px;margin-bottom:36px}.eyebrow{color:#cbaaed;font-size:13px;letter-spacing:.14em;text-transform:uppercase}h1{font-size:clamp(32px,5vw,58px);line-height:1.1;letter-spacing:-.04em;margin:16px 0}header p{color:#c9c0d3;line-height:1.65}a{color:#d9b7ff}nav{display:flex;flex-wrap:wrap;gap:12px}nav a{background:#271a36;padding:10px 14px;border-radius:24px;text-decoration:none;font-size:13px}input{width:min(100%,460px);margin:24px 0 0;padding:12px 16px;border:1px solid #493454;border-radius:10px;background:#1c1326;color:white;font:inherit}h2{font-size:25px;margin:42px 0 18px}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:22px}article{overflow:hidden;background:#1c1426;border:1px solid #382743;border-radius:16px}.screen{background:#08060c;aspect-ratio:16/9;display:flex;justify-content:center}.screen.portrait{aspect-ratio:3/4}video{width:100%;height:100%;object-fit:contain}.info{padding:18px}h3{font-size:18px;margin:0 0 8px}.info p{color:#bcaec9;font-size:13px;margin:0 0 16px}.actions{display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:12px}button[data-jump]{background:#3d225c;color:#f7f3fc;border:1px solid #8054a7;border-radius:7px;padding:7px 9px;cursor:pointer;font:inherit}select{background:#2b1e39;color:white;border:1px solid #604377;border-radius:6px;padding:6px}.downloads{line-height:1.8}footer{color:#bcaec9;font-size:13px;margin-top:40px}article[hidden],section[hidden]{display:none}@media(max-width:480px){main{padding:28px 16px}.grid{grid-template-columns:1fr}}
91</style><main><header><div class="eyebrow">23 October 2026 · Updated app interface</div><h1>Jotley video library.</h1><p>All refreshed website films, tutorials and social videos, together in one place. The main marketing film keeps its established story and music, with the styling narration covering six accent colors, including neutral gray. The titles-and-tags section uses the current interface. Choose a quality to watch or use the links to download.</p><nav>NAV</nav><input type="search" placeholder="Find a video or device…" aria-label="Find videos"></header>SECTIONS<footer>COUNT video files. Website films include 4K, 1080p and 720p versions. Portrait videos are 1080 × 1920. This HTML streams the hosted videos and works when moved. Local video copies are also included in the delivery folders. Social files are ready to use and have not been posted to social accounts.</footer></main>
92<script>
93document.querySelectorAll('article').forEach(card => {
94 const files = JSON.parse(card.dataset.files), video = card.querySelector('video'), select = card.querySelector('select');
95 const source = file => file.url;
96 video.src = source(files[+select.value]);
97 video.addEventListener('error', () => { const remote=files[+select.value].url; if(video.src !== remote) video.src=remote; });
98 select.addEventListener('change', () => { const file=files[+select.value]; video.pause(); video.src=source(file); video.load(); const seconds=Math.round(file.seconds); card.querySelector('.meta').textContent=`${Math.floor(seconds/60)}:${String(seconds%60).padStart(2,'0')} · ${file.width} × ${file.height} · ${file.fps} fps`; });
99 video.addEventListener('play', () => document.querySelectorAll('video').forEach(other => { if(other!==video) other.pause(); }));
100 card.querySelectorAll('[data-jump]').forEach(button => button.addEventListener('click', () => { const target=Number(button.dataset.jump); const seek=()=>{ if(Math.abs(video.currentTime-target)>1) video.currentTime=target; }; video.addEventListener('loadedmetadata',seek,{once:true}); video.addEventListener('canplay',seek,{once:true}); if(video.readyState>=1) seek(); video.play().catch(()=>{}); }));
101});
102document.querySelector('input').addEventListener('input', event => {
103 const query=event.target.value.toLowerCase();
104 document.querySelectorAll('article').forEach(card => card.hidden=!card.dataset.search.toLowerCase().includes(query));
105 document.querySelectorAll('section').forEach(section => section.hidden=!section.querySelector('article:not([hidden])'));
106});
107</script></html>'''
108 nav = ''.join(f'<a href="#{group.lower().replace(" ", "-")}">{group}</a>' for group in ['Website films', 'Social marketing', 'Social portrait tutorials', 'Social feature clips', 'Website screen clips'])
109 document = document.replace('NAV', nav).replace('SECTIONS', ''.join(sections)).replace('COUNT', str(len(files)))
110 (OUT / 'Jotley-Video-Library.html').write_text(document)
111 print(f'Gallery: {len(files)} files, {len(grouped)} players')
112
113
114if __name__ == '__main__':
115 main()