From 2b687f38348ba36c4ec68692672b52f7f6e6928f Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Mon, 16 Nov 2026 23:34:33 +0200 Subject: [PATCH 01/14] Audit, deduplicate, and optimize test suite --- tests/browser/test_map_palettes.py | 112 +++++---- tests/browser/test_video_studio.py | 69 +++--- tests/test_audio_upload.py | 49 ++-- tests/test_auto_map.py | 41 ++-- tests/test_batch_csv.py | 62 +++-- tests/test_music_upload_proxy.py | 56 +++-- tests/test_video_render.py | 94 +++++--- tests/test_web.py | 358 +++++++++++++++-------------- tests/test_web_input_validation.py | 66 +++--- tests/test_worker.py | 6 +- tests/test_worker_audit.py | 13 -- 11 files changed, 486 insertions(+), 440 deletions(-) diff --git a/tests/browser/test_map_palettes.py b/tests/browser/test_map_palettes.py index 4f4522f..81c56bd 100644 --- a/tests/browser/test_map_palettes.py +++ b/tests/browser/test_map_palettes.py @@ -13,6 +13,7 @@ # limitations under the License. """Exercise palette selection and request ordering in the actual map UI.""" +import atexit import base64 import io from pathlib import Path @@ -27,43 +28,65 @@ VALUES = {'ukraine': 'Alpha', 'poland': 'Beta'} -@pytest.fixture -def map_page(web): - with sync_playwright() as playwright: +_PLAYWRIGHT = None +_BROWSER = None + + +def _close_browser(): + global _PLAYWRIGHT, _BROWSER + if _BROWSER is not None: + _BROWSER.close() + _BROWSER = None + if _PLAYWRIGHT is not None: + _PLAYWRIGHT.stop() + _PLAYWRIGHT = None + + +def get_browser(): + global _PLAYWRIGHT, _BROWSER + if _BROWSER is None: + _PLAYWRIGHT = sync_playwright().start() chrome = Path('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome') kwargs = {'executable_path': str(chrome)} if chrome.exists() else {} - browser = playwright.chromium.launch(headless=True, **kwargs) - page = browser.new_page() - errors = [] - page.on('pageerror', lambda error: errors.append(str(error))) - - def route_request(route): - request = route.request - url = urlsplit(request.url) - if url.hostname == 'automap.test': - response = web.app.test_client().open( - url.path + ('?' + url.query if url.query else ''), method=request.method, data=request.post_data, - content_type=request.headers.get('content-type')) - route.fulfill(status=response.status_code, body=response.data, - content_type=response.content_type) - elif url.hostname == 'cdn.tailwindcss.com': - route.fulfill(content_type='application/javascript', body='window.tailwind = {};') - else: - route.fulfill(content_type='text/css', body='') - - page.route('**/*', route_request) - try: - page.goto('http://automap.test/') - page.add_style_tag(content='.hidden {display:none!important}') - page.evaluate('''({analysis, values}) => { - applyAnalysisToFillingStudio(analysis, values, false); - }''', {'analysis': web._build_analysis_from_ai( - VALUES, mode='text', palette_theme='heatmap'), 'values': VALUES}) - page.click('#openFillingStudioBtn') - yield page - assert not errors, errors - finally: - browser.close() + _BROWSER = _PLAYWRIGHT.chromium.launch(headless=True, **kwargs) + atexit.register(_close_browser) + return _BROWSER + + +@pytest.fixture +def map_page(web): + context = get_browser().new_context() + page = context.new_page() + errors = [] + page.on('pageerror', lambda error: errors.append(str(error))) + + def route_request(route): + request = route.request + url = urlsplit(request.url) + if url.hostname == 'automap.test': + response = web.app.test_client().open( + url.path + ('?' + url.query if url.query else ''), method=request.method, data=request.post_data, + content_type=request.headers.get('content-type')) + route.fulfill(status=response.status_code, body=response.data, + content_type=response.content_type) + elif url.hostname == 'cdn.tailwindcss.com': + route.fulfill(content_type='application/javascript', body='window.tailwind = {};') + else: + route.fulfill(content_type='text/css', body='') + + page.route('**/*', route_request) + try: + page.goto('http://automap.test/') + page.add_style_tag(content='.hidden {display:none!important}') + page.evaluate('''({analysis, values}) => { + applyAnalysisToFillingStudio(analysis, values, false); + }''', {'analysis': web._build_analysis_from_ai( + VALUES, mode='text', palette_theme='heatmap'), 'values': VALUES}) + page.click('#openFillingStudioBtn') + yield page + assert not errors, errors + finally: + context.close() def test_auto_preview_is_not_reused_as_manual_generation_rules(map_page): @@ -212,25 +235,14 @@ def test_repaint_shows_busy_state_until_image_or_error_is_ready(map_page, status def test_new_palette_is_selectable_and_analyzed(map_page): page = map_page + labels = page.locator('#fillingPaletteTheme option').all_inner_texts() for label in ('Greens', 'Blues', 'Reds', 'Oranges', 'Yellows', 'Purples', 'Teals', 'Pinks', 'Earth Tones'): - assert page.locator('#fillingPaletteTheme option', has_text=label).count() == 1 + assert sum(label in text for text in labels) == 1 page.select_option('#fillingPaletteTheme', 'greens') page.wait_for_function("lastMapAnalysis.resolved_theme === 'greens' && !paletteAnalysisPending") assert set(page.evaluate('fillingTxtRules.map(rule => rule.hex)')) == {'#bbf7d0', '#86efac'} -def test_selected_palette_survives_reload_and_is_used_for_next_generation(map_page): - page = map_page - page.select_option('#fillingPaletteTheme', 'greens') - page.wait_for_function("!paletteAnalysisPending && lastMapAnalysis.resolved_theme === 'greens'") - page.reload() - assert page.locator('#fillingPaletteTheme').input_value() == 'greens' - state = page.evaluate('getFormState()') - assert state['palette_theme'] == 'greens' - assert state['auto_style'] is True - assert 'filling_txt' not in state - - def test_removed_saved_palette_falls_back_to_auto(map_page): page = map_page page.evaluate("localStorage.setItem(MAP_PALETTE_STORAGE_KEY, 'removed-theme')") @@ -285,6 +297,10 @@ def generate(route): assert 'filling_txt' not in payloads[0] page.reload() assert page.locator('#fillingPaletteTheme').input_value() == 'greens' + state = page.evaluate('getFormState()') + assert state['palette_theme'] == 'greens' + assert state['auto_style'] is True + assert 'filling_txt' not in state assert page.locator('#aiTemperature').input_value() == '0' assert page.locator('#aiTemperatureValue').inner_text() == '0.00' assert '--temperature 0' in page.locator('#cliCommandDisplay').inner_text() diff --git a/tests/browser/test_video_studio.py b/tests/browser/test_video_studio.py index 268c79f..67655c4 100644 --- a/tests/browser/test_video_studio.py +++ b/tests/browser/test_video_studio.py @@ -19,16 +19,16 @@ """ import base64 import json -from pathlib import Path from urllib.parse import urlsplit from unittest.mock import Mock import pytest import requests from PIL import Image -from playwright.sync_api import sync_playwright from werkzeug.wrappers import Request +from test_map_palettes import get_browser + pytestmark = pytest.mark.browser @@ -76,39 +76,38 @@ def get_upstream(url, **kwargs): response.status_code, response._content = result.status_code, result.data return response monkeypatch.setattr(requests, 'get', Mock(side_effect=get_upstream)) - with sync_playwright() as playwright: - chrome = Path('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome') - kwargs = {'executable_path': str(chrome)} if chrome.exists() else {} - browser = playwright.chromium.launch(headless=True, **kwargs) - page = browser.new_page(viewport={'width': 1200, 'height': 900}) - errors = [] - previews = [] - page.on('pageerror', lambda error: errors.append(str(error))) - - def route_request(route): - request = route.request - url = urlsplit(request.url) - if url.hostname == 'automap.test': - if url.path == '/api/video_title_preview': - previews.append(request.post_data_json) - result = web.app.test_client().open( - url.path + ('?' + url.query if url.query else ''), - method=request.method, data=request.post_data_buffer, - content_type=request.headers.get('content-type'), - ) - route.fulfill(status=result.status_code, body=result.data, - content_type=result.content_type) - elif url.hostname == 'cdn.tailwindcss.com': - route.fulfill(content_type='application/javascript', body='window.tailwind = {};') - else: - route.fulfill(content_type='text/css', body='') - - page.route('**/*', route_request) + context = get_browser().new_context(viewport={'width': 1200, 'height': 900}) + page = context.new_page() + errors = [] + previews = [] + page.on('pageerror', lambda error: errors.append(str(error))) + + def route_request(route): + request = route.request + url = urlsplit(request.url) + if url.hostname == 'automap.test': + if url.path == '/api/video_title_preview': + previews.append(request.post_data_json) + result = web.app.test_client().open( + url.path + ('?' + url.query if url.query else ''), + method=request.method, data=request.post_data_buffer, + content_type=request.headers.get('content-type'), + ) + route.fulfill(status=result.status_code, body=result.data, + content_type=result.content_type) + elif url.hostname == 'cdn.tailwindcss.com': + route.fulfill(content_type='application/javascript', body='window.tailwind = {};') + else: + route.fulfill(content_type='text/css', body='') + + page.route('**/*', route_request) + try: page.goto('http://automap.test/studio') page.add_style_tag(content=OFFLINE_CSS) yield page, previews assert not errors, errors - browser.close() + finally: + context.close() def wait_for_title(page): @@ -671,10 +670,12 @@ def test_slow_map_restore_does_not_replace_a_title_edited_in_the_meantime(studio def test_new_stickers_exist_on_both_sides_and_preview_offline(studio): page, previews = studio + expected = {'mountain', 'volcano', 'island', 'rainbow', 'moon', 'rain', 'robot', 'satellite', + 'laptop', 'graduation', 'medal', 'cat', 'dog', 'fish', 'burger', 'train'} for side in ('Left', 'Right'): - for kind in ('mountain', 'volcano', 'island', 'rainbow', 'moon', 'rain', 'robot', 'satellite', - 'laptop', 'graduation', 'medal', 'cat', 'dog', 'fish', 'burger', 'train'): - assert page.locator(f'#top{side}StickerSelect option[value="{kind}"]').count() == 1 + values = page.locator(f'#top{side}StickerSelect option').evaluate_all( + 'opts => opts.map(o => o.value)') + assert expected.issubset(values) page.locator('#topLeftStickerSelect').select_option('robot') page.locator('#topRightStickerSelect').select_option('mountain') page.wait_for_function("document.querySelector('#stageTopLeftSticker img')?.naturalWidth > 0") diff --git a/tests/test_audio_upload.py b/tests/test_audio_upload.py index 2182bcb..43d6b69 100644 --- a/tests/test_audio_upload.py +++ b/tests/test_audio_upload.py @@ -14,6 +14,7 @@ """Real audio uploads and browser-restored sources without external downloads.""" import base64 +from functools import lru_cache import io from pathlib import Path import re @@ -24,7 +25,8 @@ import pytest -def wav_bytes(seconds=1.2): +@lru_cache(maxsize=4) +def wav_bytes(seconds=0.3): import math import struct output = io.BytesIO() @@ -39,10 +41,11 @@ def payload(raw, filename='My music.wav'): return {'audio_file': 'data:audio/wav;base64,' + base64.b64encode(raw).decode(), 'filename': filename} -def test_real_wav_upload_is_normalized_to_mp3_with_unique_safe_title(worker, tmp_path): +def test_real_wav_upload_is_normalized_to_mp3_with_unique_safe_title(worker): from moviepy import AudioFileClip client = worker.app.test_client() - responses = [client.post('/api/music_upload', json=payload(wav_bytes(), '../../Моя музика.wav')) + raw_wav = wav_bytes(0.3) + responses = [client.post('/api/music_upload', json=payload(raw_wav, '../../Моя музика.wav')) for _ in range(2)] titles = [] for response in responses: @@ -55,18 +58,18 @@ def test_real_wav_upload_is_normalized_to_mp3_with_unique_safe_title(worker, tmp assert path.read_bytes() == raw assert not raw.startswith(b'RIFF') with AudioFileClip(str(path)) as audio: - assert audio.duration == pytest.approx(1.2, abs=.15) + assert audio.duration == pytest.approx(0.3, abs=.15) titles.append(title) assert titles[0] != titles[1] -@pytest.mark.parametrize('value', [None, '', 'data:audio/mp3;base64,', '!', 123, - 'data:audio/wav,not-base64', 'eA==!']) -def test_upload_rejects_empty_or_invalid_base64(worker, monkeypatch, value): +def test_upload_rejects_empty_or_invalid_base64(worker, monkeypatch): convert = Mock() monkeypatch.setattr(worker, '_convert_uploaded_audio', convert) - response = worker.app.test_client().post('/api/music_upload', json={'audio_file': value}) - assert response.status_code == 400 + client = worker.app.test_client() + for value in (None, '', 'data:audio/mp3;base64,', '!', 123, 'data:audio/wav,not-base64', 'eA==!'): + response = client.post('/api/music_upload', json={'audio_file': value}) + assert response.status_code == 400, value convert.assert_not_called() assert not list(Path(worker.DOWNLOADS).iterdir()) @@ -88,13 +91,14 @@ def test_upload_rejects_file_without_actual_audio(worker): assert not list(Path(worker.DOWNLOADS).iterdir()) -@pytest.mark.parametrize('error,status', [(subprocess.TimeoutExpired('ffmpeg', 30), 504), - (FileNotFoundError('ffmpeg unavailable'), 503)]) -def test_upload_conversion_failures_are_bounded_and_do_not_save_file(worker, monkeypatch, error, status): - monkeypatch.setattr(worker.subprocess, 'run', Mock(side_effect=error)) - response = worker.app.test_client().post('/api/music_upload', json=payload(wav_bytes())) - assert response.status_code == status - assert not list(Path(worker.DOWNLOADS).iterdir()) +def test_upload_conversion_failures_are_bounded_and_do_not_save_file(worker, monkeypatch): + client = worker.app.test_client() + for error, status in ((subprocess.TimeoutExpired('ffmpeg', 30), 504), + (FileNotFoundError('ffmpeg unavailable'), 503)): + monkeypatch.setattr(worker.subprocess, 'run', Mock(side_effect=error)) + response = client.post('/api/music_upload', json=payload(wav_bytes())) + assert response.status_code == status + assert not list(Path(worker.DOWNLOADS).iterdir()) def test_converted_audio_limit_and_subprocess_timeout(worker, monkeypatch): @@ -134,12 +138,13 @@ def test_inline_cut_rejects_start_beyond_audio(worker): assert not list(Path(worker.CUT_DIR).iterdir()) -@pytest.mark.parametrize('raw', ['', 'bad!']) -def test_inline_cut_requires_valid_source(worker, raw): - response = worker.app.test_client().post('/api/music_cut', json={ - 'title': 'restored', 'audio_file': raw, 'start_time': '00:00', - }) - assert response.status_code == 400 +def test_inline_cut_requires_valid_source(worker): + client = worker.app.test_client() + for raw in ('', 'bad!'): + response = client.post('/api/music_cut', json={ + 'title': 'restored', 'audio_file': raw, 'start_time': '00:00', + }) + assert response.status_code == 400, raw def test_inline_cut_rejects_oversize_source(worker, monkeypatch): diff --git a/tests/test_auto_map.py b/tests/test_auto_map.py index fce880b..7841be1 100644 --- a/tests/test_auto_map.py +++ b/tests/test_auto_map.py @@ -24,25 +24,31 @@ ROOT = Path(__file__).resolve().parents[1] -@pytest.fixture -def scene(monkeypatch, tmp_path): - """Small real Pillow images keep compositing tests quick and deterministic.""" - monkeypatch.chdir(ROOT) - monkeypatch.setattr(renderer, '__file__', str(tmp_path / 'map' / 'auto_map.py')) +@pytest.fixture(scope='module') +def _scene_assets(tmp_path_factory): + """Create minimal 640x640 PNGs once per module so renderer caches hit across tests.""" + root = tmp_path_factory.mktemp('automap_scene') + (root / 'map').mkdir() + maps_dir = root / 'resources' / 'maps' + maps_dir.mkdir(parents=True) base = Image.new('RGBA', (640, 640), 'white') draw = ImageDraw.Draw(base) draw.line((210, 0, 210, 639), fill='black') draw.line((420, 0, 420, 639), fill='black') - real_open = Image.open + for name in ('default_map.png', 'flag_map.png', 'world_map.png'): + base.save(maps_dir / name) + empty = Image.new('RGBA', (640, 640)) + for name in ('map_relief.png', 'default_map_blured.png', 'world_map_relief.png', 'world_map_blured.png'): + empty.save(maps_dir / name) + return root - def open_image(path, *args, **kwargs): - if isinstance(path, (str, Path)) and str(path).endswith('.png'): - if Path(path).name in ('default_map.png', 'flag_map.png', 'world_map.png'): - return base.copy() - return Image.new('RGBA', base.size) - return real_open(path, *args, **kwargs) - monkeypatch.setattr(Image, 'open', open_image) +@pytest.fixture +def scene(monkeypatch, _scene_assets): + """Small real Pillow images keep compositing tests quick and deterministic.""" + monkeypatch.chdir(ROOT) + monkeypatch.setenv('AUTOMAP_REGION_CACHE_DIR', str(_scene_assets / 'rcache')) + monkeypatch.setattr(renderer, '__file__', str(_scene_assets / 'map' / 'auto_map.py')) coords = {'one': [(80, 80)], 'two': [(290, 80)], 'three': [(500, 80)]} monkeypatch.setattr(renderer, 'europe_coords', coords) monkeypatch.setattr(renderer, 'world_coords', coords) @@ -54,7 +60,7 @@ def open_image(path, *args, **kwargs): )) random = Mock(return_value=160) monkeypatch.setattr(renderer.random, 'randint', random) - return answer, random, real_open + return answer, random, Image.open def render(**changes): @@ -214,12 +220,13 @@ def test_unknown_modes_return_no_image(scene, changes): @pytest.mark.parametrize('show', [False, True]) -def test_disk_output_and_optional_viewer(scene, monkeypatch, tmp_path, show): +def test_disk_output_and_optional_viewer(scene, monkeypatch, _scene_assets, show): viewer = Mock() monkeypatch.setattr(Image.Image, 'show', viewer) output = render(io_res=False, show_result=show) - assert output == tmp_path / 'result.png' + assert output == _scene_assets / 'result.png' assert output.read_bytes().startswith(b'\x89PNG') + output.unlink(missing_ok=True) if show: viewer.assert_called_once_with('Map') else: @@ -441,6 +448,8 @@ def test_global_label_shift_moves_all_labels_but_not_country_fill_seeds(scene, m output = render(map_type=map_type, label_style={'offset_x': offset}) assert [call.args[0] for call in draw.call_args_list] == [(x + offset, y) for x, y in baseline] assert [call.kwargs['xy'] for call in fill.call_args_list] == seeds + if map_type != 'flag': + assert scene[2](output).getpixel((80, 600)) == (255, 0, 0, 255) assert output.map_meta['label_style']['offset_x'] == offset diff --git a/tests/test_batch_csv.py b/tests/test_batch_csv.py index a8e6772..9afa7cb 100644 --- a/tests/test_batch_csv.py +++ b/tests/test_batch_csv.py @@ -31,41 +31,33 @@ def authenticated_batch_client(monkeypatch): monkeypatch.setattr(app, 'test_client_class', AuthenticatedWebClient) -def test_parse_ideas_rejects_non_csv_extensions(tmp_path: Path): - for ext in (".txt", ".md", ".json", ".yaml"): - with pytest.raises(ValueError, match="Only .csv files"): - parse_ideas_content("prompt\nEurope population\n", filename=f"ideas{ext}") - - file_path = tmp_path / f"ideas{ext}" - file_path.write_text("prompt\nEurope population\n", encoding="utf-8") - with pytest.raises(ValueError, match="Only .csv files"): - load_ideas_from_file(file_path) - - -def test_parse_ideas_validates_schema_and_values(): - with pytest.raises(ValueError, match="Unknown CSV column"): - parse_ideas_content("prompt,unknown_col\nTest,1\n", filename="ideas.csv") - - with pytest.raises(ValueError, match="Missing required CSV column"): - parse_ideas_content("mode,map_type\ntext,default\n", filename="ideas.csv") - - with pytest.raises(ValueError, match="cannot be empty"): - parse_ideas_content("prompt,mode\n,text\n", filename="ideas.csv") - - with pytest.raises(ValueError, match="invalid mode"): - parse_ideas_content("prompt,mode\nTest,invalid\n", filename="ideas.csv") - - with pytest.raises(ValueError, match="invalid map_type"): - parse_ideas_content("prompt,map_type\nTest,mars\n", filename="ideas.csv") - - with pytest.raises(ValueError, match="invalid extra_option"): - parse_ideas_content("prompt,extra_option\nTest,bad_opt\n", filename="ideas.csv") - - with pytest.raises(ValueError, match="invalid gsm"): - parse_ideas_content("prompt,gsm\nTest,abc\n", filename="ideas.csv") - - with pytest.raises(ValueError, match="invalid gsm"): - parse_ideas_content("prompt,gsm\nTest,101\n", filename="ideas.csv") +@pytest.mark.parametrize("ext", [".txt", ".md", ".json", ".yaml"]) +def test_parse_ideas_rejects_non_csv_extensions(tmp_path: Path, ext: str): + with pytest.raises(ValueError, match="Only .csv files"): + parse_ideas_content("prompt\nEurope population\n", filename=f"ideas{ext}") + + file_path = tmp_path / f"ideas{ext}" + file_path.write_text("prompt\nEurope population\n", encoding="utf-8") + with pytest.raises(ValueError, match="Only .csv files"): + load_ideas_from_file(file_path) + + +@pytest.mark.parametrize( + "csv_text,match", + [ + ("prompt,unknown_col\nTest,1\n", "Unknown CSV column"), + ("mode,map_type\ntext,default\n", "Missing required CSV column"), + ("prompt,mode\n,text\n", "cannot be empty"), + ("prompt,mode\nTest,invalid\n", "invalid mode"), + ("prompt,map_type\nTest,mars\n", "invalid map_type"), + ("prompt,extra_option\nTest,bad_opt\n", "invalid extra_option"), + ("prompt,gsm\nTest,abc\n", "invalid gsm"), + ("prompt,gsm\nTest,101\n", "invalid gsm"), + ], +) +def test_parse_ideas_validates_schema_and_values(csv_text: str, match: str): + with pytest.raises(ValueError, match=match): + parse_ideas_content(csv_text, filename="ideas.csv") def test_batch_template_endpoint_and_parsing(): diff --git a/tests/test_music_upload_proxy.py b/tests/test_music_upload_proxy.py index c1fc85b..89c570a 100644 --- a/tests/test_music_upload_proxy.py +++ b/tests/test_music_upload_proxy.py @@ -14,34 +14,40 @@ from unittest.mock import Mock -import pytest import requests -@pytest.mark.parametrize('status', [200, 400, 504]) -def test_upload_proxy_forwards_file_and_worker_status(web, monkeypatch, status): - response = Mock(status_code=status) - response.json.return_value = {'status':'success' if status == 200 else 'error'} - post = Mock(return_value=response) - monkeypatch.setattr(requests, 'post', post) - payload = {'filename':'My song.wav', 'audio_file':'data:audio/wav;base64,d2F2'} - result = web.app.test_client().post('/api/music_upload', json=payload) - assert result.status_code == status - assert result.json == response.json.return_value - post.assert_called_once_with(f'{web.WORKER_URL}/api/music_upload', json=payload, timeout=90) - - -@pytest.mark.parametrize('audio', [None, '', 12, []]) -def test_missing_audio_is_rejected(web, audio): - assert web.app.test_client().post('/api/music_upload', json={'audio_file':audio}).status_code == 400 - - -@pytest.mark.parametrize('failure', [requests.Timeout(), ValueError('not JSON')]) -def test_upload_proxy_failure(web, monkeypatch, failure): - post = Mock(side_effect=failure) if isinstance(failure, requests.RequestException) else Mock(return_value=Mock(json=Mock(side_effect=failure))) - monkeypatch.setattr(requests, 'post', post) - result = web.app.test_client().post('/api/music_upload', json={'audio_file':'d2F2'}) - assert result.status_code == 502 +def test_upload_proxy_forwards_file_and_worker_status(web, monkeypatch): + client = web.app.test_client() + payload = {'filename': 'My song.wav', 'audio_file': 'data:audio/wav;base64,d2F2'} + for status in (200, 400, 504): + response = Mock(status_code=status) + response.json.return_value = {'status': 'success' if status == 200 else 'error'} + post = Mock(return_value=response) + monkeypatch.setattr(requests, 'post', post) + result = client.post('/api/music_upload', json=payload) + assert result.status_code == status + assert result.json == response.json.return_value + post.assert_called_once_with(f'{web.WORKER_URL}/api/music_upload', json=payload, timeout=90) + + +def test_missing_audio_is_rejected(web): + client = web.app.test_client() + for audio in (None, '', 12, []): + assert client.post('/api/music_upload', json={'audio_file': audio}).status_code == 400, audio + + +def test_upload_proxy_failure(web, monkeypatch): + client = web.app.test_client() + for failure in (requests.Timeout(), ValueError('not JSON')): + post = ( + Mock(side_effect=failure) + if isinstance(failure, requests.RequestException) + else Mock(return_value=Mock(json=Mock(side_effect=failure))) + ) + monkeypatch.setattr(requests, 'post', post) + result = client.post('/api/music_upload', json={'audio_file': 'd2F2'}) + assert result.status_code == 502 def test_cut_proxy_forwards_inline_source(web, monkeypatch): diff --git a/tests/test_video_render.py b/tests/test_video_render.py index ec47176..a4c9828 100644 --- a/tests/test_video_render.py +++ b/tests/test_video_render.py @@ -20,10 +20,39 @@ import pytest import numpy as np -from moviepy import ColorClip, VideoFileClip +from moviepy import AudioClip, ColorClip, VideoFileClip from PIL import Image, ImageFont +@pytest.fixture(autouse=True) +def fast_x264_preset(monkeypatch): + monkeypatch.setenv('VIDEO_X264_PRESET', 'ultrafast') + + +def _encode_bg_b64(path, duration): + with ColorClip((160, 90), color=(50, 100, 150), duration=duration) as clip: + clip.write_videofile(str(path), fps=15, codec='libx264', preset='ultrafast', logger=None) + return base64.b64encode(path.read_bytes()).decode() + + +@pytest.fixture(scope='module') +def sample_bg_b64(tmp_path_factory): + return _encode_bg_b64(tmp_path_factory.mktemp('bg') / 'background.mp4', 0.25) + + +@pytest.fixture(scope='module') +def sample_bg_half_sec_b64(tmp_path_factory): + return _encode_bg_b64(tmp_path_factory.mktemp('bg_half') / 'background.mp4', 0.5) + + +@pytest.fixture(scope='module') +def sample_audio_bytes(tmp_path_factory): + track = tmp_path_factory.mktemp('audio') / 'track.mp3' + with AudioClip(lambda t: .2 * np.sin(2 * np.pi * 440 * t), duration=.25, fps=44100) as audio: + audio.write_audiofile(str(track), logger=None) + return track.read_bytes() + + @pytest.mark.parametrize('title', [ 'Найкрасивіші країни Європи', 'A long title about the most beautiful places around the world ' * 3, @@ -83,23 +112,23 @@ def test_default_preview_matches_default_render_title(worker): ) -@pytest.mark.parametrize('font,size,effects', [('DIN Condensed.ttf', 100, True), ('Bips.ttf', 72, False)]) -@pytest.mark.parametrize('map_size', [(800, 400), (400, 800), (600, 600)]) -def test_portrait_render_with_centered_title_and_right_aligned_map(worker, tmp_path, font, size, effects, map_size): - background = tmp_path / 'background.mp4' - with ColorClip((640, 360), color=(50, 100, 150), duration=1) as clip: - clip.write_videofile(str(background), fps=30, codec='libx264', logger=None) +@pytest.mark.parametrize('font,size,effects,map_size', [ + ('DIN Condensed.ttf', 100, True, (800, 400)), + ('Bips.ttf', 72, False, (400, 800)), + ('DIN Condensed.ttf', 100, True, (600, 600)), +]) +def test_portrait_render_with_centered_title_and_right_aligned_map(worker, tmp_path, sample_bg_b64, font, size, effects, map_size): map_file = tmp_path / 'map.png' Image.new('RGB', map_size, (0, 255, 0)).save(map_file) render_id = str(uuid4()) response = worker.app.test_client().post('/api/render_video', json={ 'render_id': render_id, 'map_file': base64.b64encode(map_file.read_bytes()).decode(), - 'background_video': base64.b64encode(background.read_bytes()).decode(), + 'background_video': sample_bg_b64, 'video_title': 'Найкрасивіші країни Європи', 'title_font': font, 'title_font_size': size, 'visual_effects': effects, - 'duration': 1, 'include_audio': False, + 'duration': 0.2, 'include_audio': False, }) assert response.status_code == 200, response.json progress = worker.app.test_client().get(f'/api/render_progress/{render_id}').json @@ -110,8 +139,8 @@ def test_portrait_render_with_centered_title_and_right_aligned_map(worker, tmp_p assert result.size == [1080, 1920] assert result.audio is None assert response.json['has_audio'] is False - assert result.duration == pytest.approx(1, abs=.05) - frame = result.get_frame(.5) + assert result.duration == pytest.approx(0.25, abs=.05) + frame = result.get_frame(.1) green = (frame[:, :, 1] > 220) & (frame[:, :, 0] < 30) ys, xs = np.where(green) assert abs((xs.min() + xs.max()) / 2 - 540) < 3 @@ -134,25 +163,21 @@ def test_portrait_render_with_centered_title_and_right_aligned_map(worker, tmp_p @pytest.mark.parametrize('inline_audio', [False, True]) -def test_render_attaches_audio_and_limits_duration(worker, tmp_path, inline_audio): +def test_render_attaches_audio_and_limits_duration(worker, tmp_path, sample_bg_b64, sample_audio_bytes, inline_audio): from pathlib import Path - from moviepy import AudioClip - background = tmp_path / 'background.mp4' - with ColorClip((180, 320), color=(50, 100, 150), duration=1) as clip: - clip.write_videofile(str(background), fps=30, codec='libx264', logger=None) track = Path(worker.CUT_DIR) / 'Selected_song_cut.mp3' - with AudioClip(lambda t: .2 * np.sin(2 * np.pi * 440 * t), duration=.4, fps=44100) as audio: - audio.write_audiofile(str(track), logger=None) - audio_b64 = base64.b64encode(track.read_bytes()).decode() if inline_audio else '' if inline_audio: # The browser's saved fragment must work even after worker storage is lost. - track.unlink() + audio_b64 = base64.b64encode(sample_audio_bytes).decode() + else: + track.write_bytes(sample_audio_bytes) + audio_b64 = '' map_file = tmp_path / 'map.png' Image.new('RGB', (100, 50), 'green').save(map_file) response = worker.app.test_client().post('/api/render_video', json={ 'map_file': base64.b64encode(map_file.read_bytes()).decode(), - 'background_video': base64.b64encode(background.read_bytes()).decode(), + 'background_video': sample_bg_b64, 'video_title': 'Audio title', 'duration': 'invalid', 'audio_title': 'Selected_song', 'audio_file': audio_b64, 'include_audio': False, # An old checkbox preference must not mute selected music. @@ -161,10 +186,10 @@ def test_render_attaches_audio_and_limits_duration(worker, tmp_path, inline_audi with VideoFileClip(response.json['file_path']) as result: assert result.audio is not None assert response.json['has_audio'] is True - assert .35 <= result.duration <= .55 + assert .2 <= result.duration <= .4 # Sample inside the clip: MoviePy's bulk reader has a short-clip # buffer bug, so read scalar frames without crossing chunk boundaries. - samples = np.array([result.audio.get_frame(float(t)) for t in np.linspace(.05, .25, 64)]) + samples = np.array([result.audio.get_frame(float(t)) for t in np.linspace(.05, .18, 32)]) assert np.max(np.abs(samples)) > .05 @@ -263,15 +288,12 @@ def test_mixed_case_title_and_auto_montage_previews(worker): assert np.any(arr[:, :, 3] > 200) -def test_shorts_auto_montage_render_with_stickers_subscribe_and_stars(worker, tmp_path): - background = tmp_path / 'background.mp4' - with ColorClip((180, 320), color=(40, 80, 120), duration=1.0) as clip: - clip.write_videofile(str(background), fps=30, codec='libx264', logger=None) +def test_shorts_auto_montage_render_with_stickers_subscribe_and_stars(worker, sample_bg_half_sec_b64): map_buffer = io.BytesIO() Image.new('RGBA', (500, 500), (0, 255, 0, 255)).save(map_buffer, format='PNG') response = worker.app.test_client().post('/api/render_video', json={ 'map_file': base64.b64encode(map_buffer.getvalue()).decode(), - 'background_video': base64.b64encode(background.read_bytes()).decode(), + 'background_video': sample_bg_half_sec_b64, 'video_title': 'When is Saint Nicholas\nDay in your country?', 'title_uppercase': False, 'top_left_sticker': 'santa', @@ -283,13 +305,13 @@ def test_shorts_auto_montage_render_with_stickers_subscribe_and_stars(worker, tm 'watermark_color': '#ffffff', 'watermark_stars': True, 'intro_fade': True, - 'duration': 1, + 'duration': 0.5, }) assert response.status_code == 200, response.json with VideoFileClip(response.json['file_path']) as result: assert result.size == [1080, 1920] frame_start = result.get_frame(0.0) - frame_mid = result.get_frame(0.8) + frame_mid = result.get_frame(0.35) # Intro fade-in starts darker at t=0.0 than at t=0.8 assert frame_start.mean() < frame_mid.mean() # Map green pixels are positioned below the title + subscribe pill and above the footer @@ -356,11 +378,7 @@ def test_all_sticker_kinds_and_auto_preview(worker): @pytest.mark.parametrize('overlays_enabled', [True, False]) -def test_custom_subscribe_stars_and_top_sticker_images_render(worker, tmp_path, overlays_enabled): - background = tmp_path / 'background.mp4' - with ColorClip((180, 320), color=(30, 50, 70), duration=1.0) as clip: - clip.write_videofile(str(background), fps=30, codec='libx264', logger=None) - +def test_custom_subscribe_stars_and_top_sticker_images_render(worker, sample_bg_half_sec_b64, overlays_enabled): map_buf, sub_buf, stars_buf, sticker_buf = io.BytesIO(), io.BytesIO(), io.BytesIO(), io.BytesIO() Image.new('RGBA', (500, 500), (0, 255, 0, 255)).save(map_buf, format='PNG') # Custom magenta subscribe badge @@ -372,7 +390,7 @@ def test_custom_subscribe_stars_and_top_sticker_images_render(worker, tmp_path, response = worker.app.test_client().post('/api/render_video', json={ 'map_file': base64.b64encode(map_buf.getvalue()).decode(), - 'background_video': base64.b64encode(background.read_bytes()).decode(), + 'background_video': sample_bg_half_sec_b64, 'video_title': 'Custom Overlays Test', 'top_left_sticker_image': base64.b64encode(sticker_buf.getvalue()).decode(), 'top_right_sticker': 'auto', @@ -382,11 +400,11 @@ def test_custom_subscribe_stars_and_top_sticker_images_render(worker, tmp_path, 'watermark_text': 'TERRAMAPPER', 'watermark_stars_image': base64.b64encode(stars_buf.getvalue()).decode(), 'watermark_stars': overlays_enabled, - 'duration': 1, + 'duration': 0.5, }) assert response.status_code == 200, response.json with VideoFileClip(response.json['file_path']) as result: - frame = result.get_frame(0.5) + frame = result.get_frame(0.45) # Stickers stay at the top above the headline and subscribe badge. cyan_top = (frame[:220, 120:320, 1] > 210) & (frame[:220, 120:320, 2] > 210) & (frame[:220, 120:320, 0] < 50) diff --git a/tests/test_web.py b/tests/test_web.py index 9b45e6f..7754932 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -20,17 +20,18 @@ import requests -@pytest.mark.parametrize('path', ['/', '/studio', '/api/status', '/api/fonts', '/api/fonts/']) -def test_pages_and_discovery(web, path): - response = web.app.test_client().get(path) - assert response.status_code == 200 - if path.startswith('/api/fonts'): - assert 'DIN Condensed.ttf' in response.json['fonts'] - assert response.json['count'] == len(response.json['fonts']) - elif path == '/api/status': - assert response.json == {'needs_api_key': True} - elif path == '/studio': - assert b'titleFontSelect' in response.data and b'titleFontSize' in response.data +def test_pages_and_discovery(web): + client = web.app.test_client() + for path in ('/', '/studio', '/api/status', '/api/fonts', '/api/fonts/'): + response = client.get(path) + assert response.status_code == 200, path + if path.startswith('/api/fonts'): + assert 'DIN Condensed.ttf' in response.json['fonts'] + assert response.json['count'] == len(response.json['fonts']) + elif path == '/api/status': + assert response.json == {'needs_api_key': True} + elif path == '/studio': + assert b'titleFontSelect' in response.data and b'titleFontSize' in response.data @pytest.fixture @@ -51,39 +52,41 @@ def test_generate_forwards_options_and_encodes_png(web, monkeypatch, generation_ assert 'form-key' not in response.json['command'] -@pytest.mark.parametrize('temperature', [0, 0.4, 2]) -def test_generate_forwards_temperature_including_zero(web, monkeypatch, generation_request, temperature): +def test_generate_forwards_temperature_including_zero(web, monkeypatch, generation_request): generate = Mock(return_value=io.BytesIO(b'png')) monkeypatch.setattr(web, 'auto_map', generate) - response = web.app.test_client().post('/api/generate', json={ - **generation_request, 'temperature': temperature}) - assert response.status_code == 200 - assert generate.call_args.kwargs['temperature'] == temperature - assert f'--temperature {temperature:g}' in response.json['command'] + client = web.app.test_client() + for temperature in (0, 0.4, 2): + response = client.post('/api/generate', json={**generation_request, 'temperature': temperature}) + assert response.status_code == 200 + assert generate.call_args.kwargs['temperature'] == temperature + assert f'--temperature {temperature:g}' in response.json['command'] -@pytest.mark.parametrize('temperature', [-1, 3, 'NaN', 'Infinity', True, None, 'invalid', {}]) -def test_generate_rejects_invalid_temperature_before_rendering(web, monkeypatch, generation_request, temperature): +def test_generate_rejects_invalid_temperature_before_rendering(web, monkeypatch, generation_request): generate = Mock() monkeypatch.setattr(web, 'auto_map', generate) - response = web.app.test_client().post('/api/generate', json={ - **generation_request, 'temperature': temperature}) - assert response.status_code == 400 - assert 'Temperature' in response.json['error'] + client = web.app.test_client() + for temperature in (-1, 3, 'NaN', 'Infinity', True, None, 'invalid', {}): + response = client.post('/api/generate', json={**generation_request, 'temperature': temperature}) + assert response.status_code == 400, temperature + assert 'Temperature' in response.json['error'], temperature generate.assert_not_called() -@pytest.mark.parametrize('gsm', [None, 'bad', 15]) -@pytest.mark.parametrize('extra', ['none', '', None]) -def test_generate_defaults_and_invalid_font_fallback(web, monkeypatch, generation_request, gsm, extra): +def test_generate_defaults_and_invalid_font_fallback(web, monkeypatch, generation_request): generate = Mock(return_value=io.BytesIO(b'png')) monkeypatch.setattr(web, 'auto_map', generate) - response = web.app.test_client().post('/api/generate/', json={**generation_request, - 'font': '../bad.ttf', 'gsm': gsm, 'extra_option': extra}) - assert response.status_code == 200 - assert generate.call_args.kwargs['font_name'] == 'Bips.ttf' - assert generate.call_args.kwargs['size_mod'] == 15 - assert generate.call_args.kwargs['optional_feature'] is None + client = web.app.test_client() + for gsm in (None, 'bad', 15): + for extra in ('none', '', None): + response = client.post('/api/generate/', json={ + **generation_request, 'font': '../bad.ttf', 'gsm': gsm, 'extra_option': extra, + }) + assert response.status_code == 200 + assert generate.call_args.kwargs['font_name'] == 'Bips.ttf' + assert generate.call_args.kwargs['size_mod'] == 15 + assert generate.call_args.kwargs['optional_feature'] is None def test_generate_requires_key_without_server_key(web, monkeypatch, generation_request): @@ -103,15 +106,6 @@ def test_generate_server_key_does_not_require_form_key(web, monkeypatch, generat assert generate.call_args.kwargs['api_key'] is None -@pytest.mark.parametrize('failure,status', [(KeyError('topic'), 400), (RuntimeError('broken'), 500), (None, 500)]) -def test_generation_errors(web, monkeypatch, generation_request, failure, status): - generate = Mock(side_effect=failure) if failure else Mock(return_value=None) - monkeypatch.setattr(web, 'auto_map', generate) - response = web.app.test_client().post('/api/generate', json=generation_request) - assert response.status_code == status - assert response.json['status'] == 'error' - - PROXIES = [ ('/api/music_download', {'url': 'https://example.test/song'}, 150), ('/api/music_cut', {'title': 'song', 'start_time': '00:01'}, 40), @@ -119,45 +113,52 @@ def test_generation_errors(web, monkeypatch, generation_request, failure, status ] -@pytest.mark.parametrize('path,payload,timeout', PROXIES) -@pytest.mark.parametrize('status', [200, 400, 500]) -def test_json_proxy_passes_response(web, monkeypatch, path, payload, timeout, status): - upstream = Mock(status_code=status) - upstream.json.return_value = {'status': 'success' if status == 200 else 'error', 'file': 'data'} - post = Mock(return_value=upstream) - monkeypatch.setattr(requests, 'post', post) - response = web.app.test_client().post(path, json=payload) - assert response.status_code == status and response.json == upstream.json.return_value - assert post.call_args.kwargs['timeout'] == timeout - if path.endswith('render_video'): - assert post.call_args.kwargs['json']['title_font'] == 'DIN Condensed.ttf' - assert post.call_args.kwargs['json']['title_font_size'] == 100 - assert post.call_args.kwargs['json']['include_audio'] is False - - -@pytest.mark.parametrize('path,payload,timeout', PROXIES) -@pytest.mark.parametrize('failure', ['network', 'json']) -def test_proxy_failure_returns_bad_gateway(web, monkeypatch, path, payload, timeout, failure): - upstream = Mock() - upstream.json.side_effect = ValueError('not json') - post = Mock(side_effect=requests.ConnectionError('offline')) if failure == 'network' else Mock(return_value=upstream) - monkeypatch.setattr(requests, 'post', post) - assert web.app.test_client().post(path, json=payload).status_code == 502 - - -@pytest.mark.parametrize('path', ['/api/music_download', '/api/music_cut', '/api/download_video']) -def test_missing_proxy_fields(web, path): +def test_json_proxy_passes_response(web, monkeypatch): client = web.app.test_client() - response = client.get(path) if 'download_video' in path else client.post(path, json={}) - assert response.status_code == 400 + for path, payload, timeout in PROXIES: + for status in (200, 400, 500): + upstream = Mock(status_code=status) + upstream.json.return_value = {'status': 'success' if status == 200 else 'error', 'file': 'data'} + post = Mock(return_value=upstream) + monkeypatch.setattr(requests, 'post', post) + response = client.post(path, json=payload) + assert response.status_code == status and response.json == upstream.json.return_value + assert post.call_args.kwargs['timeout'] == timeout + if path.endswith('render_video'): + assert post.call_args.kwargs['json']['title_font'] == 'DIN Condensed.ttf' + assert post.call_args.kwargs['json']['title_font_size'] == 100 + assert post.call_args.kwargs['json']['include_audio'] is False + + +def test_proxy_failure_returns_bad_gateway(web, monkeypatch): + client = web.app.test_client() + for path, payload, _ in PROXIES: + for failure in ('network', 'json'): + upstream = Mock() + upstream.json.side_effect = ValueError('not json') + post = ( + Mock(side_effect=requests.ConnectionError('offline')) + if failure == 'network' + else Mock(return_value=upstream) + ) + monkeypatch.setattr(requests, 'post', post) + assert client.post(path, json=payload).status_code == 502, (path, failure) + + +def test_missing_proxy_fields(web): + client = web.app.test_client() + for path in ('/api/music_download', '/api/music_cut', '/api/download_video'): + response = client.get(path) if 'download_video' in path else client.post(path, json={}) + assert response.status_code == 400, path -@pytest.mark.parametrize('raw,expected', [(0, 1), (100, 30), ('bad', 8), (None, 8), ('12', 12)]) -def test_cut_duration_normalization(web, monkeypatch, raw, expected): - post = Mock(return_value=Mock(status_code=200, json=lambda: {})) - monkeypatch.setattr(requests, 'post', post) - web.app.test_client().post('/api/music_cut', json={'title': 'song', 'duration': raw}) - assert post.call_args.kwargs['json']['duration'] == expected +def test_cut_duration_normalization(web, monkeypatch): + client = web.app.test_client() + for raw, expected in ((0, 1), (100, 30), ('bad', 8), (None, 8), ('12', 12)): + post = Mock(return_value=Mock(status_code=200, json=lambda: {})) + monkeypatch.setattr(requests, 'post', post) + client.post('/api/music_cut', json={'title': 'song', 'duration': raw}) + assert post.call_args.kwargs['json']['duration'] == expected, raw def test_render_forwards_title_style_and_legacy_title(web, monkeypatch): @@ -186,19 +187,20 @@ def test_render_forwards_title_style_and_legacy_title(web, monkeypatch): assert post.call_args.kwargs['json']['visual_effects'] is False -@pytest.mark.parametrize('status', [200, 400]) -def test_title_preview_proxy_preserves_content(web, monkeypatch, status): - upstream = Mock(status_code=status, content=b'png-or-error', headers={'Content-Type': 'image/png'}) - post = Mock(return_value=upstream) - monkeypatch.setattr(requests, 'post', post) - response = web.app.test_client().post('/api/video_title_preview', json={ - 'video_title': 'Title', 'title_font': 'Bips.ttf', 'title_font_size': 72, 'ignore': True, - 'title_first_line_color': '#ff6600', 'title_other_lines_color': '#3366ff'}) - assert response.status_code == status and response.data == b'png-or-error' - assert response.mimetype == 'image/png' - assert 'ignore' not in post.call_args.kwargs['json'] - assert post.call_args.kwargs['json']['title_first_line_color'] == '#ff6600' - assert post.call_args.kwargs['json']['title_other_lines_color'] == '#3366ff' +def test_title_preview_proxy_preserves_content(web, monkeypatch): + client = web.app.test_client() + for status in (200, 400): + upstream = Mock(status_code=status, content=b'png-or-error', headers={'Content-Type': 'image/png'}) + post = Mock(return_value=upstream) + monkeypatch.setattr(requests, 'post', post) + response = client.post('/api/video_title_preview', json={ + 'video_title': 'Title', 'title_font': 'Bips.ttf', 'title_font_size': 72, 'ignore': True, + 'title_first_line_color': '#ff6600', 'title_other_lines_color': '#3366ff'}) + assert response.status_code == status and response.data == b'png-or-error' + assert response.mimetype == 'image/png' + assert 'ignore' not in post.call_args.kwargs['json'] + assert post.call_args.kwargs['json']['title_first_line_color'] == '#ff6600' + assert post.call_args.kwargs['json']['title_other_lines_color'] == '#3366ff' def test_title_preview_unavailable(web, monkeypatch): @@ -218,16 +220,23 @@ def test_video_download_streaming(web, monkeypatch): assert get.call_args.kwargs['stream'] is True -@pytest.mark.parametrize('kind', ['network', 'json', 'text', 'invalid-json']) -def test_video_download_errors(web, monkeypatch, kind): - upstream = Mock(status_code=404, headers={'Content-Type': 'application/json' if 'json' in kind else 'text/plain'}, text='missing') - upstream.json.return_value = {'error': 'missing'} - if kind == 'invalid-json': - upstream.json.side_effect = ValueError() - get = Mock(side_effect=requests.ConnectionError()) if kind == 'network' else Mock(return_value=upstream) - monkeypatch.setattr(requests, 'get', get) - response = web.app.test_client().get('/api/download_video?path=clip.mp4') - assert response.status_code == (502 if kind == 'network' else 404) +def test_video_download_errors(web, monkeypatch): + client = web.app.test_client() + for kind in ('network', 'json', 'text', 'invalid-json'): + upstream = Mock( + status_code=404, + headers={'Content-Type': 'application/json' if 'json' in kind else 'text/plain'}, + text='missing', + ) + upstream.json.return_value = {'error': 'missing'} + if kind == 'invalid-json': + upstream.json.side_effect = ValueError() + get = Mock(side_effect=requests.ConnectionError()) if kind == 'network' else Mock(return_value=upstream) + monkeypatch.setattr(requests, 'get', get) + response = client.get('/api/download_video?path=clip.mp4') + assert response.status_code == (502 if kind == 'network' else 404), kind + + def test_codec_proxy_returns_worker_capabilities(web, monkeypatch): monkeypatch.setattr(requests, 'get', Mock(return_value=Mock( status_code=200, json=lambda: {'codecs': ['libx264']}))) @@ -243,12 +252,13 @@ def test_worker_url_environment_override(monkeypatch, request): get.assert_called_once_with('http://127.0.0.1:9090/api/codecs', timeout=20) -@pytest.mark.parametrize('failure', [requests.Timeout(), ValueError('bad JSON')]) -def test_codec_proxy_failure(web, monkeypatch, failure): - response = Mock() - response.json.side_effect = failure - monkeypatch.setattr(requests, 'get', Mock(return_value=response)) - assert web.app.test_client().get('/api/codecs').status_code == 502 +def test_codec_proxy_failure(web, monkeypatch): + client = web.app.test_client() + for failure in (requests.Timeout(), ValueError('bad JSON')): + response = Mock() + response.json.side_effect = failure + monkeypatch.setattr(requests, 'get', Mock(return_value=response)) + assert client.get('/api/codecs').status_code == 502 def test_analyze_map_endpoint_returns_rules_and_style(web): @@ -317,17 +327,8 @@ def test_analyze_map_validates_and_inspects_uploaded_image(web): from PIL import Image client = web.app.test_client() - # Invalid base64/image must return 400 error instead of sample data - bad_res = client.post('/api/analyze_map', json={ - 'image_data': 'data:image/png;base64,invalid', - 'topic': 'Any', - 'prefer_cached': False, - }) - assert bad_res.status_code == 400 - assert bad_res.json['status'] == 'error' - # Valid PNG image is inspected for its actual pixel colors - img = Image.new('RGBA', (220, 180), (20, 180, 90, 255)) + img = Image.new('RGBA', (32, 32), (20, 180, 90, 255)) buf = io.BytesIO() img.save(buf, format='PNG') b64 = base64.b64encode(buf.getvalue()).decode('ascii') @@ -346,22 +347,23 @@ def test_analyze_map_validates_and_inspects_uploaded_image(web): assert '#14b45a' in ok_res.json['analysis']['filling_txt'] -@pytest.mark.parametrize('theme', [ - 'auto', 'viridis', 'heatmap', 'emerald_gold', 'festive', 'oceanic', 'categorical', - 'greens', 'blues', 'reds', 'oranges', 'yellows', 'purples', 'teals', 'pinks', 'earth_tones', - 'pastel', 'neon', 'monochrome', 'sunset', -]) -def test_analyze_map_supports_every_ui_palette_theme(web, theme): +def test_analyze_map_supports_every_ui_palette_theme(web): client = web.app.test_client() - res = client.post('/api/analyze_map', json={ - 'topic': 'Population', - 'mode': 'number', - 'palette_theme': theme, - 'map_values': {'germany': 84, 'france': 68, 'estonia': 1}, - }) - assert res.status_code == 200 - expected = 'viridis' if theme == 'auto' else theme - assert res.json['analysis']['resolved_theme'] == expected + themes = ( + 'auto', 'viridis', 'heatmap', 'emerald_gold', 'festive', 'oceanic', 'categorical', + 'greens', 'blues', 'reds', 'oranges', 'yellows', 'purples', 'teals', 'pinks', 'earth_tones', + 'pastel', 'neon', 'monochrome', 'sunset', + ) + for theme in themes: + res = client.post('/api/analyze_map', json={ + 'topic': 'Population', + 'mode': 'number', + 'palette_theme': theme, + 'map_values': {'germany': 84, 'france': 68, 'estonia': 1}, + }) + assert res.status_code == 200, theme + expected = 'viridis' if theme == 'auto' else theme + assert res.json['analysis']['resolved_theme'] == expected, theme def test_analyze_map_prefer_cached_false_does_not_leak_previous_state(web): @@ -401,27 +403,31 @@ def test_generate_returns_request_values_and_effective_style(web, monkeypatch, g assert kwargs[key] == style[key] -@pytest.mark.parametrize('failure', [None, RuntimeError('repaint failed')]) -def test_restyle_reports_renderer_failure(web, monkeypatch, failure): - generate = Mock(side_effect=failure) if failure else Mock(return_value=None) - monkeypatch.setattr(web, 'auto_map', generate) - response = web.app.test_client().post('/api/restyle_map', json={'map_values': {'ukraine': 'Yes'}}) - assert response.status_code == 500 - assert response.json['status'] == 'error' - assert 'image_url' not in response.json - - -@pytest.mark.parametrize('image_data,error', [ - ('', 'Empty image data'), - ('data:text/plain;base64,YQ==', 'Unsupported data URL media type'), - ('data:image/png;base64,', 'Decoded image payload is empty'), - ('data:image/png;base64,YQ==', 'not a valid image'), -]) -def test_palette_inspection_rejects_invalid_uploads(web, image_data, error): - response = web.app.test_client().post('/api/analyze_map', json={'image_data': image_data}) - assert response.status_code == 400 - assert error in response.json['error'] - assert 'map_values' not in response.json +def test_restyle_reports_renderer_failure(web, monkeypatch): + client = web.app.test_client() + for failure in (None, RuntimeError('repaint failed')): + generate = Mock(side_effect=failure) if failure else Mock(return_value=None) + monkeypatch.setattr(web, 'auto_map', generate) + response = client.post('/api/restyle_map', json={'map_values': {'ukraine': 'Yes'}}) + assert response.status_code == 500 + assert response.json['status'] == 'error' + assert 'image_url' not in response.json + + +def test_palette_inspection_rejects_invalid_uploads(web): + client = web.app.test_client() + cases = ( + ('', 'Empty image data'), + ('data:text/plain;base64,YQ==', 'Unsupported data URL media type'), + ('data:image/png;base64,', 'Decoded image payload is empty'), + ('data:image/png;base64,YQ==', 'not a valid image'), + ('data:image/png;base64,invalid', 'Invalid base64 image payload'), + ) + for image_data, error in cases: + response = client.post('/api/analyze_map', json={'image_data': image_data}) + assert response.status_code == 400, image_data + assert error in response.json['error'], image_data + assert 'map_values' not in response.json def test_palette_inspection_rejects_images_too_small_for_sampling(web): @@ -434,24 +440,24 @@ def test_palette_inspection_rejects_images_too_small_for_sampling(web): assert 'too small' in response.json['error'] -@pytest.mark.parametrize('mode', ['text', 'number']) -def test_topic_preview_is_explicitly_identified_as_sample_data(web, mode): - response = web.app.test_client().post('/api/analyze_map', json={'topic': 'Example', 'mode': mode}) - assert response.status_code == 200 - assert response.json['source'] == 'topic_preview' - assert response.json['analysis']['detected_type'] == mode - assert response.json['map_values'] - - +def test_topic_preview_is_explicitly_identified_as_sample_data(web): + client = web.app.test_client() + for mode in ('text', 'number'): + response = client.post('/api/analyze_map', json={'topic': 'Example', 'mode': mode}) + assert response.status_code == 200 + assert response.json['source'] == 'topic_preview' + assert response.json['analysis']['detected_type'] == mode + assert response.json['map_values'] -@pytest.mark.parametrize('code,phrase', [(503, 'overloaded'), (429, 'quota'), (504, '45 seconds')]) -def test_generate_displays_upstream_service_reason(web, monkeypatch, generation_request, code, phrase): +def test_generate_displays_upstream_service_reason(web, monkeypatch, generation_request): from map.functions import AIServiceError - monkeypatch.setattr(web, 'auto_map', Mock(side_effect=AIServiceError(phrase, code))) - response = web.app.test_client().post('/api/generate', json=generation_request) - assert response.status_code == code - assert response.json['error'] == phrase + client = web.app.test_client() + for code, phrase in ((503, 'overloaded'), (429, 'quota'), (504, '45 seconds')): + monkeypatch.setattr(web, 'auto_map', Mock(side_effect=AIServiceError(phrase, code))) + response = client.post('/api/generate', json=generation_request) + assert response.status_code == code + assert response.json['error'] == phrase def test_analysis_preserves_fractional_values_and_rendered_bounds(web): @@ -505,10 +511,14 @@ def generate(**kwargs): assert client.get('/api/generate_progress/unknown').json['stage'] == 1 -@pytest.mark.parametrize('error,status', [(KeyError('x'), 400), (RuntimeError('failed'), 500), (None, 500)]) -def test_map_progress_records_generation_failure(web, monkeypatch, generation_request, error, status): - monkeypatch.setattr(web, 'auto_map', Mock(side_effect=error, return_value=None)) +def test_map_progress_records_generation_failure(web, monkeypatch, generation_request): client = web.app.test_client() - response = client.post('/api/generate', json={**generation_request, 'progress_id': 'failed'}) - assert response.status_code == status - assert client.get('/api/generate_progress/failed').json['status'] == 'error' + for error, status in ((KeyError('x'), 400), (RuntimeError('failed'), 500), (None, 500)): + monkeypatch.setattr(web, 'auto_map', Mock(side_effect=error, return_value=None)) + no_progress = client.post('/api/generate', json=generation_request) + assert no_progress.status_code == status + assert no_progress.json['status'] == 'error' + response = client.post('/api/generate', json={**generation_request, 'progress_id': 'failed'}) + assert response.status_code == status + assert response.json['status'] == 'error' + assert client.get('/api/generate_progress/failed').json['status'] == 'error' diff --git a/tests/test_web_input_validation.py b/tests/test_web_input_validation.py index 3ad01b4..5898068 100644 --- a/tests/test_web_input_validation.py +++ b/tests/test_web_input_validation.py @@ -15,19 +15,19 @@ """Malformed client requests and interrupted downloads stay controlled.""" from unittest.mock import Mock -import pytest - - -@pytest.mark.parametrize('path', [ - '/api/generate', '/api/generate_batch', '/api/analyze_map', '/api/restyle_map', - '/api/music_download', '/api/music_cut', '/api/render_video', '/api/models', - '/api/video_title_preview', -]) -@pytest.mark.parametrize('body', ['[1]', '"text"', '12', 'null', '{broken']) -def test_non_object_json_is_a_client_error(web, path, body): - response = web.app.test_client().post(path, data=body, content_type='application/json') - assert response.status_code == 400 - assert response.json['status'] == 'error' + +def test_non_object_json_is_a_client_error(web): + client = web.app.test_client() + paths = ( + '/api/generate', '/api/generate_batch', '/api/analyze_map', '/api/restyle_map', + '/api/music_download', '/api/music_cut', '/api/render_video', '/api/models', + '/api/video_title_preview', + ) + for path in paths: + for body in ('[1]', '"text"', '12', 'null', '{broken'): + response = client.post(path, data=body, content_type='application/json') + assert response.status_code == 400, (path, body) + assert response.json['status'] == 'error', (path, body) def test_upload_limit_returns_json(web): @@ -38,22 +38,24 @@ def test_upload_limit_returns_json(web): assert response.json['status'] == 'error' -@pytest.mark.parametrize('path,field', [('/api/generate', 'api_key'), ('/api/music_download', 'url')]) -@pytest.mark.parametrize('value', [42, True, ['value'], {'value': 'text'}]) -def test_invalid_string_fields_are_client_errors(web, path, field, value): - response = web.app.test_client().post(path, json={field: value}) - assert response.status_code == 400 - assert field in response.json['error'] - - -@pytest.mark.parametrize('status', [200, 404]) -def test_video_proxy_releases_connection(web, monkeypatch, status): - upstream = Mock(status_code=status, headers={'Content-Type': 'application/json'}) - upstream.json.return_value = {'error': 'missing'} - upstream.iter_content.return_value = iter([b'video']) - monkeypatch.setattr(web.requests, 'get', Mock(return_value=upstream)) - response = web.app.test_client().get('/api/download_video?path=clip.mp4', buffered=True) - assert response.status_code == status - if status == 200: - assert response.data == b'video' - assert upstream.close.called +def test_invalid_string_fields_are_client_errors(web): + client = web.app.test_client() + for path, field in (('/api/generate', 'api_key'), ('/api/music_download', 'url')): + for value in (42, True, ['value'], {'value': 'text'}): + response = client.post(path, json={field: value}) + assert response.status_code == 400, (path, field, value) + assert field in response.json['error'], (path, field, value) + + +def test_video_proxy_releases_connection(web, monkeypatch): + client = web.app.test_client() + for status in (200, 404): + upstream = Mock(status_code=status, headers={'Content-Type': 'application/json'}) + upstream.json.return_value = {'error': 'missing'} + upstream.iter_content.return_value = iter([b'video']) + monkeypatch.setattr(web.requests, 'get', Mock(return_value=upstream)) + response = client.get('/api/download_video?path=clip.mp4', buffered=True) + assert response.status_code == status + if status == 200: + assert response.data == b'video' + assert upstream.close.called diff --git a/tests/test_worker.py b/tests/test_worker.py index dda2b92..4ce05d5 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -162,7 +162,7 @@ def test_audio_cut_read_failure(worker, monkeypatch): {'map_file': ''}, {'background_video': ''}, {'video_title': ''}, {'video_title': 'a' * 1001}, {'codec': 'unsupported'}, {'map_file': 'data:image/png;base64,'}, {'map_file': 'a'}, - {'background_video': '!!!'}, + {'map_file': 'eA==!'}, {'background_video': '!!!'}, ]) def test_render_validation(worker, changes): data = dict(map_file='eA==', background_video='eA==', video_title='test') @@ -223,11 +223,11 @@ def test_download_video_stream(worker): response.close() -@pytest.mark.parametrize('kind,status', [('empty', 400), ('missing', 404), ('outside', 400), ('sibling', 400), ('symlink', 400)]) +@pytest.mark.parametrize('kind,status', [('empty', 400), ('null', 400), ('missing', 404), ('outside', 400), ('sibling', 400), ('symlink', 400)]) def test_download_path_validation(worker, tmp_path, kind, status): outside = tmp_path / 'secret.mp4' outside.write_bytes(b'private') - paths = {'empty': '', 'missing': str(Path(worker.RENDER_DIR) / 'missing.mp4'), + paths = {'empty': '', 'null': '\0', 'missing': str(Path(worker.RENDER_DIR) / 'missing.mp4'), 'outside': str(outside), 'sibling': worker.RENDER_DIR + '-other/secret.mp4'} if kind == 'symlink': link = Path(worker.RENDER_DIR) / 'link.mp4' diff --git a/tests/test_worker_audit.py b/tests/test_worker_audit.py index fe85619..e2cd3c0 100644 --- a/tests/test_worker_audit.py +++ b/tests/test_worker_audit.py @@ -84,19 +84,6 @@ def test_download_accepts_storage_relative_filename(worker): response.close() -def test_download_rejects_null_byte_path(worker): - response = worker.app.test_client().get('/api/download_video', query_string={'path': '\0'}) - assert response.status_code == 400 - - -def test_render_rejects_garbage_after_base64_material(worker): - response = worker.app.test_client().post('/api/render_video', json={ - 'map_file': 'eA==!', 'background_video': 'eA==', 'video_title': 'Title', - }) - assert response.status_code == 400 - assert 'not valid base64' in response.json['error'] - - @pytest.mark.parametrize('titles', [ ('Same title', 'Same title'), ('Same / title', 'Same ? title'), From df2174204792bdda8fb1b55dba5e96809a01d904 Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 11:53:04 +0200 Subject: [PATCH 02/14] refactor: moved some dictionaries to constants.py Moved to constants.py: WORLD_COUNTRY_ALIASES (auto_map.py) _RELIEF_ALPHA_LUT (auto_map.py) _PALETTE_THEMES (auto_map.py, L399) _AUTO_PALETTE (auto_map.py) _SEMANTIC_COLORS (auto_map.py, L456-L457) _DEFAULT_UI_TXT_KEYS (auto_map.py) _DEFAULT_UI_NUM_BOUNDS (auto_map.py) _PAINTED_MAP_TYPES (auto_map.py, L922, L1030) _EUROPE_LABEL_SIZES (auto_map.py) _WORLD_LABEL_SIZES (auto_map.py) _WORLD_COUNTRIES_MIN_LABEL (auto_map.py) etc. --- map/auto_map.py | 241 +++++------------------------------------------ map/constants.py | 201 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 222 insertions(+), 220 deletions(-) diff --git a/map/auto_map.py b/map/auto_map.py index 39222fd..5c9c288 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -28,210 +28,11 @@ import numpy as np from PIL import Image, ImageDraw, ImageFont -from .constants import europe_coords, world_coords +from . import constants + from .functions import ai_request, load_filling, _warning as showwarning, _error as showerror from . import log -FONTS_DIR = Path(__file__).resolve().parent.parent / "resources" / "fonts" - -_AUTO_PALETTE: tuple[tuple[int, int, int, int], ...] = ( - (56, 189, 248, 255), # #38bdf8 Sky - (99, 102, 241, 255), # #6366f1 Indigo - (16, 185, 129, 255), # #10b981 Emerald - (245, 158, 11, 255), # #f59e0b Amber - (244, 63, 94, 255), # #f43f5e Rose - (168, 85, 247, 255), # #a855f7 Purple - (20, 184, 166, 255), # #14b8a6 Teal - (236, 72, 153, 255), # #ec4899 Pink - (234, 179, 8, 255), # #eab308 Gold - (249, 115, 22, 255), # #f97316 Orange -) - -_PALETTE_THEMES: dict[str, tuple[tuple[int, int, int, int], ...]] = { - "auto": _AUTO_PALETTE, - "viridis": ( - (68, 1, 84, 255), (59, 82, 139, 255), (33, 145, 140, 255), - (94, 201, 98, 255), (253, 231, 37, 255), - ), - "sunset": ( - (124, 45, 18, 255), (194, 65, 12, 255), (234, 88, 12, 255), - (245, 158, 11, 255), (253, 224, 71, 255), - ), - "ocean": ( - (12, 74, 110, 255), (3, 105, 161, 255), (2, 132, 199, 255), - (56, 189, 248, 255), (125, 211, 252, 255), - ), - "festive": ( - (220, 38, 38, 255), (22, 163, 74, 255), (234, 179, 8, 255), - (37, 99, 235, 255), (147, 51, 234, 255), - ), - "emerald": ( - (6, 78, 59, 255), (4, 120, 87, 255), (16, 185, 129, 255), - (52, 211, 153, 255), (167, 243, 208, 255), - ), - "neon": ( - (236, 72, 153, 255), (139, 92, 246, 255), (6, 182, 212, 255), - (16, 185, 129, 255), (250, 204, 21, 255), - ), - "pastel": ( - (147, 197, 253, 255), (196, 181, 253, 255), (167, 243, 208, 255), - (253, 230, 138, 255), (253, 164, 175, 255), - ), - "monochrome": ( - (51, 65, 85, 255), (71, 85, 105, 255), (100, 116, 139, 255), - (148, 163, 184, 255), (203, 213, 225, 255), - ), - "heatmap": ( - (37, 99, 235, 255), (16, 185, 129, 255), (245, 158, 11, 255), - (239, 68, 68, 255), (185, 28, 28, 255), - ), - "emerald_gold": ( - (244, 63, 94, 255), (245, 158, 11, 255), (234, 179, 8, 255), - (16, 185, 129, 255), (5, 150, 105, 255), - ), - "oceanic": ( - (56, 189, 248, 255), (14, 165, 233, 255), (37, 99, 235, 255), - (99, 102, 241, 255), (139, 92, 246, 255), - ), - "categorical": _AUTO_PALETTE + ( - (14, 165, 233, 255), (132, 204, 22, 255), - ), - "greens": ( - (187, 247, 208, 255), (134, 239, 172, 255), (74, 222, 128, 255), - (22, 163, 74, 255), (20, 83, 45, 255), - ), - "blues": ( - (191, 219, 254, 255), (147, 197, 253, 255), (96, 165, 250, 255), - (37, 99, 235, 255), (30, 58, 138, 255), - ), - "reds": ( - (254, 202, 202, 255), (252, 165, 165, 255), (248, 113, 113, 255), - (220, 38, 38, 255), (127, 29, 29, 255), - ), - "oranges": ( - (254, 215, 170, 255), (253, 186, 116, 255), (251, 146, 60, 255), - (234, 88, 12, 255), (124, 45, 18, 255), - ), - "yellows": ( - (254, 240, 138, 255), (253, 224, 71, 255), (250, 204, 21, 255), - (202, 138, 4, 255), (133, 77, 14, 255), - ), - "purples": ( - (233, 213, 255, 255), (216, 180, 254, 255), (192, 132, 252, 255), - (147, 51, 234, 255), (88, 28, 135, 255), - ), - "teals": ( - (153, 246, 228, 255), (94, 234, 212, 255), (45, 212, 191, 255), - (13, 148, 136, 255), (19, 78, 74, 255), - ), - "pinks": ( - (251, 207, 232, 255), (249, 168, 212, 255), (244, 114, 182, 255), - (219, 39, 119, 255), (131, 24, 67, 255), - ), - "earth_tones": ( - (231, 229, 176, 255), (194, 178, 128, 255), (163, 137, 87, 255), - (120, 113, 62, 255), (75, 85, 45, 255), - ), -} - -_SEMANTIC_COLORS: dict[str, tuple[int, int, int, int]] = { - "yes": (46, 204, 113, 255), "так": (46, 204, 113, 255), "true": (46, 204, 113, 255), - "no": (231, 76, 60, 255), "ні": (231, 76, 60, 255), "false": (231, 76, 60, 255), - "tea": (16, 185, 129, 255), "coffee": (245, 158, 11, 255), "coffe": (245, 158, 11, 255), - "beer": (234, 179, 8, 255), "wine": (225, 29, 72, 255), -} - -_DEFAULT_UI_TXT_KEYS = {"yes", "no", "tea", "coffee"} -_DEFAULT_UI_NUM_BOUNDS = {(0, 100), (100, 1000), (1000, 10000), (10000, 100000000)} -_RELIEF_ALPHA_LUT: list[int] = [int(p * 0.3) for p in range(256)] - -_EUROPE_LABEL_SIZES: dict[str, int] = { - **{k: 70 for k in ( - "cyprus", "kosovo", "montenegro", "slovenia", "latvia", "lithuania", - "estonia", "switzerland", "austria", "slovakia", "hungary", "croatia", - "netherlands", "belgium", "czechia", "moldova", "bosnia_and_herzegovina", - "serbia", "bulgaria", "albania", "greece", "ireland", "iceland", - "norway", "finland", "sweden", "denmark", "portugal", - )}, - **{k: 100 for k in ("sweden", "norway", "finland")}, - **{k: 125 for k in ("north_macedonia", "bosnia")}, - **{k: 175 for k in ( - "ukraine", "poland", "france", "spain", "turkey", - "romania", "italy", "belarus", "united_kingdom", "germany", - )}, - **{k: 250 for k in ("russia", "usa")}, -} - -_WORLD_LABEL_SIZES: dict[str, int] = { - "asia": 200, - "africa": 100, - "europe": 110, - "australia": 50, - "south_america": 100, - "north_america": 120, -} - -# Map types whose regions are painted from the cached region-ID map. -# Flag-filled maps (``flag``, ``world_countries``) keep their underlying flag artwork. -_PAINTED_MAP_TYPES: frozenset[str] = frozenset({"default", "world"}) - -# Smallest base label size (before the global size modifier) still drawn on the -# world countries map; smaller countries stay unlabeled to keep the map readable. -_WORLD_COUNTRIES_MIN_LABEL = 1 - -# Common alternative AI spellings mapped to canonical snake_case country keys. -# Applied only when the alias target exists in the coordinates dictionary. -_WORLD_COUNTRY_ALIASES: dict[str, tuple[str, ...]] = { - "usa": ("united_states", "united_states_of_america"), - "us": ("united_states", "united_states_of_america"), - "united_states_of_america": ("united_states",), - "america": ("united_states", "united_states_of_america"), - "uk": ("united_kingdom",), - "great_britain": ("united_kingdom",), - "britain": ("united_kingdom",), - "russian_federation": ("russia",), - "czech_republic": ("czechia",), - "turkiye": ("turkey",), - "ivory_coast": ("cote_d_ivoire", "cote_divoire"), - "cote_d_ivoire": ("ivory_coast",), - "cote_divoire": ("ivory_coast", "cote_d_ivoire"), - "drc": ("democratic_republic_of_the_congo", "dr_congo"), - "dr_congo": ("democratic_republic_of_the_congo",), - "congo_kinshasa": ("democratic_republic_of_the_congo", "dr_congo"), - "democratic_republic_of_congo": ("democratic_republic_of_the_congo", "dr_congo"), - "congo_brazzaville": ("republic_of_the_congo", "congo"), - "republic_of_congo": ("republic_of_the_congo", "congo"), - "south_korea": ("korea_south", "republic_of_korea"), - "korea": ("south_korea",), - "korea_south": ("south_korea",), - "republic_of_korea": ("south_korea",), - "north_korea": ("korea_north", "dprk"), - "korea_north": ("north_korea",), - "dprk": ("north_korea",), - "burma": ("myanmar",), - "swaziland": ("eswatini",), - "eswatini": ("swaziland",), - "macedonia": ("north_macedonia",), - "holland": ("netherlands",), - "the_netherlands": ("netherlands",), - "uae": ("united_arab_emirates",), - "east_timor": ("timor_leste",), - "timor_leste": ("east_timor",), - "cabo_verde": ("cape_verde",), - "cape_verde": ("cabo_verde",), - "vatican_city": ("vatican",), - "bosnia": ("bosnia_and_herzegovina",), - "the_gambia": ("gambia",), - "the_bahamas": ("bahamas",), - "united_republic_of_tanzania": ("tanzania",), - "republic_of_serbia": ("serbia",), - "state_of_palestine": ("palestine",), - "brunei_darussalam": ("brunei",), - "viet_nam": ("vietnam",), - "lao_pdr": ("laos",), -} - - def _country_key(name: object) -> str: """Normalize a country name to snake_case ASCII ("Côte d'Ivoire" -> "cote_d_ivoire").""" text = unicodedata.normalize("NFKD", str(name)).encode("ascii", "ignore").decode("ascii") @@ -244,7 +45,7 @@ def _world_countries_answer_norm(ai_answer: dict[str, object], keys: object) -> for k, v in (ai_answer or {}).items(): norm.setdefault(_country_key(k), v) known = {_country_key(k) for k in keys} - for alias, targets in _WORLD_COUNTRY_ALIASES.items(): + for alias, targets in constants._WORLD_COUNTRY_ALIASES.items(): if alias not in norm: continue for target in targets: @@ -310,7 +111,7 @@ def _prepared_relief(path: Path, size: tuple[int, int]) -> Image.Image: relief = _load_rgba(path) relief = relief.resize(size) if relief.size != tuple(size) else relief.copy() _, _, _, a = relief.split() - relief.putalpha(a.point(_RELIEF_ALPHA_LUT)) + relief.putalpha(a.point(constants._RELIEF_ALPHA_LUT)) if ckey is not None: with _CACHE_LOCK: _RELIEF_CACHE[ckey] = relief @@ -432,7 +233,7 @@ def _paint_regions(img: Image.Image, flat: np.ndarray, ids: np.ndarray, def _resolve_theme_name(palette_theme: str = "auto", prompt: str = "", mode: str = "text") -> str: """Pick a palette theme name from an explicit choice, prompt keywords, or mode.""" theme = (palette_theme or "auto").strip().lower() - if theme in _PALETTE_THEMES and theme != "auto": + if theme in constants._PALETTE_THEMES and theme != "auto": return theme low = (prompt or "").lower() if any(w in low for w in ("nicholas", "christmas", "santa", "holiday", "xmas")): @@ -596,7 +397,7 @@ def _auto_fill_from_ai( auto_txt: dict[str, tuple[int, int, int, int]] = {} auto_num: dict[tuple[float, float], tuple[int, int, int, int]] = {} resolved = _resolve_theme_name(palette_theme, prompt=prompt, mode=mode) - palette = _PALETTE_THEMES.get(resolved, _AUTO_PALETTE) + palette = constants._PALETTE_THEMES.get(resolved, constants._AUTO_PALETTE) use_semantic = (palette_theme or "auto").strip().lower() == "auto" if mode == "number": @@ -645,7 +446,7 @@ def _auto_fill_from_ai( b_idx = sum(1 for t in thresholds if num > t) auto_txt[lbl] = palette[b_idx % len(palette)] else: - auto_txt.setdefault(lbl, _SEMANTIC_COLORS.get(lbl.lower(), palette[-1])) + auto_txt.setdefault(lbl, constants._SEMANTIC_COLORS.get(lbl.lower(), palette[-1])) else: canonical: dict[str, str] = {} for lbl in labels: @@ -653,8 +454,8 @@ def _auto_fill_from_ai( idx = 0 for low_lbl, _ in Counter(lbl.lower() for lbl in labels).most_common(): orig = canonical[low_lbl] - if use_semantic and low_lbl in _SEMANTIC_COLORS: - auto_txt[orig] = _SEMANTIC_COLORS[low_lbl] + if use_semantic and low_lbl in constants._SEMANTIC_COLORS: + auto_txt[orig] = constants._SEMANTIC_COLORS[low_lbl] else: auto_txt[orig] = palette[idx % len(palette)] idx += 1 @@ -819,7 +620,7 @@ def auto_map(prompt: str, mode: str, map_type: str, size_mod: int, def get_font(size): key = (font_name, size) if key not in _font_cache: - font_path = FONTS_DIR / font_name + font_path = constants.FONTS_DIR / font_name _font_cache[key] = ImageFont.truetype(str(font_path), size) return _font_cache[key] @@ -896,13 +697,13 @@ def _parse_optional_features(value: object) -> set[str]: wc_label_sizes: dict[str, int] = {} if map_type == "default": path = Path(__file__).parent.parent / "./resources/maps/default_map.png" - dict_ = europe_coords + dict_ = constants.europe_coords elif map_type == 'flag': path = Path(__file__).parent.parent / "./resources/maps/flag_map.png" - dict_ = europe_coords + dict_ = constants.europe_coords elif map_type == 'world': path = Path(__file__).parent.parent / "./resources/maps/world_map.png" - dict_ = world_coords + dict_ = constants.world_coords elif map_type == 'world_countries': path = Path(__file__).parent.parent / "./resources/maps/world_countries_map.png" dict_, wc_label_sizes = _load_world_countries() @@ -958,7 +759,7 @@ def _report(stage: int, label: str) -> None: if mode == "text": merged_txt = dict(auto_txt) req_keys_low = {k.strip().lower() for k in req_txt} - if req_txt and (not theme_requested or req_keys_low != _DEFAULT_UI_TXT_KEYS): + if req_txt and (not theme_requested or req_keys_low != constants._DEFAULT_UI_TXT_KEYS): ci_to_orig = {k.strip().lower(): k for k in merged_txt} for rk, rv in req_txt.items(): short_rk = str(_format_short_number(rk)).strip() if has_short_form else rk @@ -967,7 +768,7 @@ def _report(stage: int, label: str) -> None: filling_txt = merged_txt filling_txt_ci = {str(k).strip().lower(): v for k, v in filling_txt.items()} elif mode == "number": - if req_num and set(req_num.keys()) != _DEFAULT_UI_NUM_BOUNDS and not theme_requested: + if req_num and set(req_num.keys()) != constants._DEFAULT_UI_NUM_BOUNDS and not theme_requested: filling_num = dict(req_num) elif auto_num: filling_num = dict(auto_num) @@ -1099,7 +900,7 @@ def _report(stage: int, label: str) -> None: # so "Yes", "yes" and " yes " all find the same colour. color = filling_txt_ci[info.lower()] except KeyError: - if map_type in _PAINTED_MAP_TYPES: + if map_type in constants._PAINTED_MAP_TYPES: log.info(f"No filling color for '{info}'; using random") # Repeated answers share a color so categories remain recognizable. try: @@ -1119,7 +920,7 @@ def _report(stage: int, label: str) -> None: # Flag maps retain their original artwork. Other maps use every seed point # to fill disconnected pieces of a region, such as islands. # Painting is applied after the loop from a cached region-ID map. - if map_type in _PAINTED_MAP_TYPES: + if map_type in constants._PAINTED_MAP_TYPES: region_colors[index] = tuple(int(c) for c in color) if not points: @@ -1137,7 +938,7 @@ def _report(stage: int, label: str) -> None: elif len(info) >= 2: x -= 30 - size = _EUROPE_LABEL_SIZES.get(name, 125) + size = constants._EUROPE_LABEL_SIZES.get(name, 125) if name in ('russia', 'usa'): y -= 10 elif name in ('north_macedonia', 'bosnia'): @@ -1162,7 +963,7 @@ def _report(stage: int, label: str) -> None: stroke_fill=label_stroke_fill) elif map_type == 'world': # text size for World map - size = _WORLD_LABEL_SIZES.get(name, 100) + size = constants._WORLD_LABEL_SIZES.get(name, 100) if label_auto_fit and len(info) >= 6: size = max(40, int(size * max(0.55, 5.0 / len(info)))) @@ -1180,7 +981,7 @@ def _report(stage: int, label: str) -> None: base_size = wc_label_sizes.get(name) if base_size is None: base_size = wc_label_sizes.get(name_key, 0) - if base_size and base_size >= _WORLD_COUNTRIES_MIN_LABEL: + if base_size and base_size >= constants._WORLD_COUNTRIES_MIN_LABEL: size = base_size if label_auto_fit and len(info) >= 6: size = max(14, int(size * max(0.55, 5.0 / len(info)))) @@ -1227,7 +1028,7 @@ def _report(stage: int, label: str) -> None: }, } - if map_type in _PAINTED_MAP_TYPES: + if map_type in constants._PAINTED_MAP_TYPES: flat, ids = _region_index(path, img, dict_) img = _paint_regions(img, flat, ids, region_colors) diff --git a/map/constants.py b/map/constants.py index a9942a8..f1cc378 100644 --- a/map/constants.py +++ b/map/constants.py @@ -14,6 +14,9 @@ # Pixel coordinates in the bundled map artwork, rather than geographic coordinates. # The first point anchors the label; additional points fill disconnected land areas. +from pathlib import Path + + europe_coords = { "ukraine": [(3144, 2440), (3565, 2805)], "poland": [(2370, 2338)], @@ -130,3 +133,201 @@ "africa": }""" +FONTS_DIR = Path(__file__).resolve().parent.parent / "resources" / "fonts" + +_AUTO_PALETTE: tuple[tuple[int, int, int, int], ...] = ( + (56, 189, 248, 255), # #38bdf8 Sky + (99, 102, 241, 255), # #6366f1 Indigo + (16, 185, 129, 255), # #10b981 Emerald + (245, 158, 11, 255), # #f59e0b Amber + (244, 63, 94, 255), # #f43f5e Rose + (168, 85, 247, 255), # #a855f7 Purple + (20, 184, 166, 255), # #14b8a6 Teal + (236, 72, 153, 255), # #ec4899 Pink + (234, 179, 8, 255), # #eab308 Gold + (249, 115, 22, 255), # #f97316 Orange +) + +_PALETTE_THEMES: dict[str, tuple[tuple[int, int, int, int], ...]] = { + "auto": _AUTO_PALETTE, + "viridis": ( + (68, 1, 84, 255), (59, 82, 139, 255), (33, 145, 140, 255), + (94, 201, 98, 255), (253, 231, 37, 255), + ), + "sunset": ( + (124, 45, 18, 255), (194, 65, 12, 255), (234, 88, 12, 255), + (245, 158, 11, 255), (253, 224, 71, 255), + ), + "ocean": ( + (12, 74, 110, 255), (3, 105, 161, 255), (2, 132, 199, 255), + (56, 189, 248, 255), (125, 211, 252, 255), + ), + "festive": ( + (220, 38, 38, 255), (22, 163, 74, 255), (234, 179, 8, 255), + (37, 99, 235, 255), (147, 51, 234, 255), + ), + "emerald": ( + (6, 78, 59, 255), (4, 120, 87, 255), (16, 185, 129, 255), + (52, 211, 153, 255), (167, 243, 208, 255), + ), + "neon": ( + (236, 72, 153, 255), (139, 92, 246, 255), (6, 182, 212, 255), + (16, 185, 129, 255), (250, 204, 21, 255), + ), + "pastel": ( + (147, 197, 253, 255), (196, 181, 253, 255), (167, 243, 208, 255), + (253, 230, 138, 255), (253, 164, 175, 255), + ), + "monochrome": ( + (51, 65, 85, 255), (71, 85, 105, 255), (100, 116, 139, 255), + (148, 163, 184, 255), (203, 213, 225, 255), + ), + "heatmap": ( + (37, 99, 235, 255), (16, 185, 129, 255), (245, 158, 11, 255), + (239, 68, 68, 255), (185, 28, 28, 255), + ), + "emerald_gold": ( + (244, 63, 94, 255), (245, 158, 11, 255), (234, 179, 8, 255), + (16, 185, 129, 255), (5, 150, 105, 255), + ), + "oceanic": ( + (56, 189, 248, 255), (14, 165, 233, 255), (37, 99, 235, 255), + (99, 102, 241, 255), (139, 92, 246, 255), + ), + "categorical": _AUTO_PALETTE + ( + (14, 165, 233, 255), (132, 204, 22, 255), + ), + "greens": ( + (187, 247, 208, 255), (134, 239, 172, 255), (74, 222, 128, 255), + (22, 163, 74, 255), (20, 83, 45, 255), + ), + "blues": ( + (191, 219, 254, 255), (147, 197, 253, 255), (96, 165, 250, 255), + (37, 99, 235, 255), (30, 58, 138, 255), + ), + "reds": ( + (254, 202, 202, 255), (252, 165, 165, 255), (248, 113, 113, 255), + (220, 38, 38, 255), (127, 29, 29, 255), + ), + "oranges": ( + (254, 215, 170, 255), (253, 186, 116, 255), (251, 146, 60, 255), + (234, 88, 12, 255), (124, 45, 18, 255), + ), + "yellows": ( + (254, 240, 138, 255), (253, 224, 71, 255), (250, 204, 21, 255), + (202, 138, 4, 255), (133, 77, 14, 255), + ), + "purples": ( + (233, 213, 255, 255), (216, 180, 254, 255), (192, 132, 252, 255), + (147, 51, 234, 255), (88, 28, 135, 255), + ), + "teals": ( + (153, 246, 228, 255), (94, 234, 212, 255), (45, 212, 191, 255), + (13, 148, 136, 255), (19, 78, 74, 255), + ), + "pinks": ( + (251, 207, 232, 255), (249, 168, 212, 255), (244, 114, 182, 255), + (219, 39, 119, 255), (131, 24, 67, 255), + ), + "earth_tones": ( + (231, 229, 176, 255), (194, 178, 128, 255), (163, 137, 87, 255), + (120, 113, 62, 255), (75, 85, 45, 255), + ), +} + +_SEMANTIC_COLORS: dict[str, tuple[int, int, int, int]] = { + "yes": (46, 204, 113, 255), "так": (46, 204, 113, 255), "true": (46, 204, 113, 255), + "no": (231, 76, 60, 255), "ні": (231, 76, 60, 255), "false": (231, 76, 60, 255), + "tea": (16, 185, 129, 255), "coffee": (245, 158, 11, 255), "coffe": (245, 158, 11, 255), + "beer": (234, 179, 8, 255), "wine": (225, 29, 72, 255), +} + +_DEFAULT_UI_TXT_KEYS = {"yes", "no", "tea", "coffee"} +_DEFAULT_UI_NUM_BOUNDS = {(0, 100), (100, 1000), (1000, 10000), (10000, 100000000)} +_RELIEF_ALPHA_LUT: list[int] = [int(p * 0.3) for p in range(256)] + +_EUROPE_LABEL_SIZES: dict[str, int] = { + **{k: 70 for k in ( + "cyprus", "kosovo", "montenegro", "slovenia", "latvia", "lithuania", + "estonia", "switzerland", "austria", "slovakia", "hungary", "croatia", + "netherlands", "belgium", "czechia", "moldova", "bosnia_and_herzegovina", + "serbia", "bulgaria", "albania", "greece", "ireland", "iceland", + "norway", "finland", "sweden", "denmark", "portugal", + )}, + **{k: 100 for k in ("sweden", "norway", "finland")}, + **{k: 125 for k in ("north_macedonia", "bosnia")}, + **{k: 175 for k in ( + "ukraine", "poland", "france", "spain", "turkey", + "romania", "italy", "belarus", "united_kingdom", "germany", + )}, + **{k: 250 for k in ("russia", "usa")}, +} + +_WORLD_LABEL_SIZES: dict[str, int] = { + "asia": 200, + "africa": 100, + "europe": 110, + "australia": 50, + "south_america": 100, + "north_america": 120, +} + +# Map types whose regions are painted from the cached region-ID map. +# Flag-filled maps (``flag``, ``world_countries``) keep their underlying flag artwork. +_PAINTED_MAP_TYPES: frozenset[str] = frozenset({"default", "world"}) + +# Smallest base label size (before the global size modifier) still drawn on the +# world countries map; smaller countries stay unlabeled to keep the map readable. +_WORLD_COUNTRIES_MIN_LABEL = 1 + +# Common alternative AI spellings mapped to canonical snake_case country keys. +# Applied only when the alias target exists in the coordinates dictionary. +_WORLD_COUNTRY_ALIASES: dict[str, tuple[str, ...]] = { + "usa": ("united_states", "united_states_of_america"), + "us": ("united_states", "united_states_of_america"), + "united_states_of_america": ("united_states",), + "america": ("united_states", "united_states_of_america"), + "uk": ("united_kingdom",), + "great_britain": ("united_kingdom",), + "britain": ("united_kingdom",), + "russian_federation": ("russia",), + "czech_republic": ("czechia",), + "turkiye": ("turkey",), + "ivory_coast": ("cote_d_ivoire", "cote_divoire"), + "cote_d_ivoire": ("ivory_coast",), + "cote_divoire": ("ivory_coast", "cote_d_ivoire"), + "drc": ("democratic_republic_of_the_congo", "dr_congo"), + "dr_congo": ("democratic_republic_of_the_congo",), + "congo_kinshasa": ("democratic_republic_of_the_congo", "dr_congo"), + "democratic_republic_of_congo": ("democratic_republic_of_the_congo", "dr_congo"), + "congo_brazzaville": ("republic_of_the_congo", "congo"), + "republic_of_congo": ("republic_of_the_congo", "congo"), + "south_korea": ("korea_south", "republic_of_korea"), + "korea": ("south_korea",), + "korea_south": ("south_korea",), + "republic_of_korea": ("south_korea",), + "north_korea": ("korea_north", "dprk"), + "korea_north": ("north_korea",), + "dprk": ("north_korea",), + "burma": ("myanmar",), + "swaziland": ("eswatini",), + "eswatini": ("swaziland",), + "macedonia": ("north_macedonia",), + "holland": ("netherlands",), + "the_netherlands": ("netherlands",), + "uae": ("united_arab_emirates",), + "east_timor": ("timor_leste",), + "timor_leste": ("east_timor",), + "cabo_verde": ("cape_verde",), + "cape_verde": ("cabo_verde",), + "vatican_city": ("vatican",), + "bosnia": ("bosnia_and_herzegovina",), + "the_gambia": ("gambia",), + "the_bahamas": ("bahamas",), + "united_republic_of_tanzania": ("tanzania",), + "republic_of_serbia": ("serbia",), + "state_of_palestine": ("palestine",), + "brunei_darussalam": ("brunei",), + "viet_nam": ("vietnam",), + "lao_pdr": ("laos",), +} \ No newline at end of file From c2a4dcca0d207435b0b8ff8431a0140228ffa996 Mon Sep 17 00:00:00 2001 From: bibed234 Date: Tue, 17 Nov 2026 13:46:55 +0200 Subject: [PATCH 03/14] Add Highlight Min/Max Countries glow overlay with customizable colors --- main.py | 16 +++++- map/auto_map.py | 120 +++++++++++++++++++++++++++++++++++++++++-- templates/index.html | 46 ++++++++++++++++- 3 files changed, 175 insertions(+), 7 deletions(-) diff --git a/main.py b/main.py index 1205907..a52f126 100644 --- a/main.py +++ b/main.py @@ -623,14 +623,25 @@ def generate(): command += f" --temperature {temperature_options['temperature']:g}" show_legend = bool(data.get("show_legend", False)) + highlight_extrema = bool(data.get("highlight_extrema", False)) if show_legend: command += " --legend" + if highlight_extrema: + command += " --highlight-extrema" progress_id = str(data.get("progress_id") or "").strip()[:64] if progress_id: _set_map_progress(progress_id, 1, "Querying AI model...") - style_kwargs: dict[str, object] = {"show_legend": show_legend} + style_kwargs: dict[str, object] = { + "show_legend": show_legend, + "highlight_extrema": highlight_extrema, + } + if highlight_extrema: + if "highlight_high_color" in data: + style_kwargs["highlight_high_color"] = str(data.get("highlight_high_color") or "#00e5ff") + if "highlight_low_color" in data: + style_kwargs["highlight_low_color"] = str(data.get("highlight_low_color") or "#ff2daa") if progress_id: style_kwargs["progress_callback"] = lambda stage, label: _set_map_progress(progress_id, stage, label) for style_key, kw_name in ( @@ -1056,6 +1067,9 @@ def api_restyle_map(): palette_theme=palette_theme, ai_answer_override=map_values, show_legend=bool(data.get("show_legend", False)), + highlight_extrema=bool(data.get("highlight_extrema", False)), + highlight_high_color=str(data.get("highlight_high_color") or "#00e5ff"), + highlight_low_color=str(data.get("highlight_low_color") or "#ff2daa"), ) except Exception as e: # noqa: BLE001 return jsonify({"status": "error", "error": str(e)}), 500 diff --git a/map/auto_map.py b/map/auto_map.py index 5c9c288..82e0fa4 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -584,6 +584,97 @@ def _draw_legend_overlay( return layer +_RESERVED_HIGHLIGHT_COLORS: tuple[tuple[int, int, int], ...] = ( + (0, 229, 255), # Electric cyan (highest) + (255, 45, 170), # Neon magenta (lowest) +) + + +def _random_region_color() -> tuple[int, int, int, int]: + """Pick a random bright RGBA color that stays distinct from reserved highlight colors.""" + for _ in range(16): + c = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255)) + if all(sum((c[i] - r[i]) ** 2 for i in range(3)) >= 90 ** 2 for r in _RESERVED_HIGHLIGHT_COLORS): + return (*c, 255) + return (120, 180, 120, 255) + + +def _build_extrema_highlight_layer( + size: tuple[int, int], + highest_idx: int | None, + lowest_idx: int | None, + map_type: str, + dict_: dict, + flat: np.ndarray | None, + ids: np.ndarray | None, + borders: Image.Image | None, + high_rgb: tuple[int, int, int] = _RESERVED_HIGHLIGHT_COLORS[0], + low_rgb: tuple[int, int, int] = _RESERVED_HIGHLIGHT_COLORS[1], +) -> Image.Image | None: + """Create a soft tint + inner glow highlight layer for the highest and lowest regions.""" + from PIL import ImageChops, ImageFilter + + targets: list[tuple[int, tuple[int, int, int]]] = [] + if highest_idx is not None: + targets.append((highest_idx, high_rgb)) + if lowest_idx is not None and lowest_idx != highest_idx: + targets.append((lowest_idx, low_rgb)) + if not targets: + return None + + w, h = size + layer = Image.new("RGBA", size, (0, 0, 0, 0)) + coords_list = list(dict_.values()) + + if map_type == "flag" and (flat is None or ids is None): + mask_path = Path(__file__).parent.parent / "resources" / "maps" / "default_map.png" + flat, ids = _region_index(mask_path, _load_rgba(mask_path), dict_) + + inner_size = 37 if w >= 3000 else 21 + outer_size = 25 if w >= 3000 else 15 + border_work = borders.copy() if (map_type == "world_countries" and borders is not None) else None + border_orig_alpha = np.asarray(borders)[..., 3] if border_work is not None else None + + for region_idx, rgb in targets: + mask: Image.Image | None = None + if flat is not None and ids is not None: + pix_mask = np.zeros(w * h, dtype=np.uint8) + pix_mask[flat[ids == region_idx]] = 255 + if pix_mask.any(): + mask = Image.fromarray(pix_mask.reshape((h, w)), mode="L") + elif border_work is not None and 1 <= region_idx <= len(coords_list): + work = border_work.copy() + for coord in coords_list[region_idx - 1]: + ImageDraw.floodfill(work, xy=tuple(coord), value=(255, 255, 255, 255), thresh=60) + work_arr = np.asarray(work) + filled = (work_arr[..., 3] == 255) & (border_orig_alpha < 60) + if filled.any(): + mask = Image.fromarray((filled.astype(np.uint8) * 255), mode="L") + + if mask is None: + continue + + # Downscale the binary mask before morphological filters so MinFilter/MaxFilter + # run in milliseconds instead of O(k^2) over 16M full-res pixels. + ds = 4 if w >= 2400 else 2 + small_size = (max(1, w // ds), max(1, h // ds)) + small_mask = mask.resize(small_size, Image.Resampling.BILINEAR) + small_inner = small_mask.filter(ImageFilter.MinFilter(9)) + small_outer = small_mask.filter(ImageFilter.MaxFilter(7)) + inner_ring = ImageChops.subtract(small_mask, small_inner).filter(ImageFilter.GaussianBlur(2)) + outer_halo = ImageChops.subtract(small_outer, small_mask).filter(ImageFilter.GaussianBlur(2.5)) + glow_small = ImageChops.lighter(inner_ring, outer_halo.point(lambda p: min(255, int(p * 0.95)))) + glow_alpha = glow_small.resize((w, h), Image.Resampling.BILINEAR) + tint_alpha = mask.point(lambda p: 75 if p else 0) + combined_alpha = ImageChops.lighter(tint_alpha, glow_alpha) + + overlay = Image.new("RGBA", size, (*rgb, 255)) + overlay.putalpha(combined_alpha) + layer = Image.alpha_composite(layer, overlay) + + return layer + + def auto_map(prompt: str, mode: str, map_type: str, size_mod: int, optional_feature: str, model: str, font_name: str, show_result: bool = True, io_res = False, api_key: str | None = None, @@ -598,6 +689,9 @@ def auto_map(prompt: str, mode: str, map_type: str, size_mod: int, web_search: bool = False, max_search_requests: int = 5, show_legend: bool = False, + highlight_extrema: bool = False, + highlight_high_color: str = "#00e5ff", + highlight_low_color: str = "#ff2daa", progress_callback=None): """Create a map from an AI query and save it as ``result.png``. @@ -845,6 +939,7 @@ def _report(stage: int, label: str) -> None: raw_ai_answer_norm["australia"] = raw_ai_answer_norm["oceania"] region_colors: dict[int, tuple[int, int, int, int]] = {} + numeric_region_values: dict[int, float] = {} for index, (name, points) in enumerate(dict_.items(), start=1): name_key = ( @@ -856,13 +951,15 @@ def _report(stage: int, label: str) -> None: if mode == 'number': try: info = ai_answer_norm[name_key] - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() num_value = _parse_short_number(info) raw_num_value = _parse_short_number(raw_ai_answer_norm.get(name_key)) if num_value is None: log.warning(f"Non-numeric value for {name}: {info!r}; using random color") if num_value is not None: + if highlight_extrema: + numeric_region_values[index] = float(raw_num_value if raw_num_value is not None else num_value) # Pick the colour of the first matching range. Ranges are # treated as (low < value <= high) per the docs. matched_bounds = None @@ -885,7 +982,7 @@ def _report(stage: int, label: str) -> None: except KeyError as e: info = "" log.warning(f"No data / color for {e}; using random color") - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() random_colors[name] = color elif mode == 'text': @@ -906,10 +1003,10 @@ def _report(stage: int, label: str) -> None: try: color = random_colors[info] except KeyError: - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() random_colors[info] = color else: - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() used_txt_rules.setdefault(info, color) else: showerror("Error", f"Unknown mode: {mode}") @@ -1028,10 +1125,16 @@ def _report(stage: int, label: str) -> None: }, } + flat = ids = None if map_type in constants._PAINTED_MAP_TYPES: flat, ids = _region_index(path, img, dict_) img = _paint_regions(img, flat, ids, region_colors) + highest_idx = lowest_idx = None + if highlight_extrema and mode == "number" and numeric_region_values: + highest_idx = max(numeric_region_values, key=numeric_region_values.get) + lowest_idx = min(numeric_region_values, key=numeric_region_values.get) + # adding relief map _report(3, "Adding relief, borders & overlays...") log.step("Compositing layers") @@ -1051,6 +1154,15 @@ def _report(stage: int, label: str) -> None: # Restore borders above the relief, then put readable labels on top. borders = _load_rgba(maps_dir / borders_name) + if highest_idx is not None: + high_rgb = _hex_to_rgba(highlight_high_color, (*_RESERVED_HIGHLIGHT_COLORS[0], 255))[:3] + low_rgb = _hex_to_rgba(highlight_low_color, (*_RESERVED_HIGHLIGHT_COLORS[1], 255))[:3] + hl_layer = _build_extrema_highlight_layer( + img.size, highest_idx, lowest_idx, map_type, dict_, flat, ids, borders, + high_rgb=high_rgb, low_rgb=low_rgb, + ) + if hl_layer is not None: + result = Image.alpha_composite(result, hl_layer) result = Image.alpha_composite(result, borders) result = Image.alpha_composite(result, text_layer) diff --git a/templates/index.html b/templates/index.html index 014db8c..92e01a5 100644 --- a/templates/index.html +++ b/templates/index.html @@ -653,6 +653,29 @@

+ + @@ -2119,6 +2142,9 @@

gsm, extra_option: extraOption, show_legend: !!document.getElementById('showLegendToggle')?.checked, + highlight_extrema: !!document.getElementById('highlightExtremaToggle')?.checked, + highlight_high_color: document.getElementById('highlightHighColor')?.value || '#00e5ff', + highlight_low_color: document.getElementById('highlightLowColor')?.value || '#ff2daa', model, font, topic, @@ -2189,8 +2215,11 @@

const escapedTopic = (state.topic || '').replace(/"/g, '\\"'); let cmd = `python cli.py make "${escapedTopic}" -m ${state.mode} -mp ${state.map_type} -gsm ${state.gsm} -eop ${state.extra_option} --model ${state.model} --font "${state.font}" --temperature ${state.temperature}`; if (state.show_legend) cmd += ' --legend'; + if (state.highlight_extrema) cmd += ' --highlight-extrema'; document.getElementById('cliCommandDisplay').textContent = cmd; + const hlColorsRow = document.getElementById('highlightColorsRow'); + if (hlColorsRow) hlColorsRow.classList.toggle('hidden', !state.highlight_extrema); updateActiveBadges(state); updateCompatibilityHint(state); updateHudCoords(state); @@ -2200,8 +2229,8 @@

const hint = document.getElementById('extraOptionHint'); if (!hint) return; const hasMostLeast = String(state.extra_option || '').includes('show_most_least'); - if (hasMostLeast && state.mode === 'text') { - hint.textContent = 'Note: show_most_least is designed for numeric mode (-m number).'; + if ((hasMostLeast || state.highlight_extrema) && state.mode === 'text') { + hint.textContent = 'Note: Most/Least and Min/Max highlighting only apply in numeric mode.'; hint.className = 'text-[11px] text-amber-400/90 mt-1.5 block'; } else if (hasMostLeast && state.map_type === 'world') { hint.textContent = 'Note: show_most_least overlay is supported on default, flag, and world_countries maps.'; @@ -2233,6 +2262,7 @@

{ label: `gsm: ${state.gsm}`, color: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30' }, { label: `eop: ${state.extra_option}`, color: 'bg-amber-500/20 text-amber-300 border-amber-500/30' }, ...(state.show_legend ? [{ label: 'legend', color: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30' }] : []), + ...(state.highlight_extrema ? [{ label: 'highlight min/max', color: 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30' }] : []), { label: state.model, color: 'bg-sky-500/20 text-sky-300 border-sky-500/30' }, { label: state.font, color: 'bg-slate-900/90 text-slate-300 border-slate-700' } ]; @@ -3246,6 +3276,12 @@

setSelectedExtraOption(s.extra_option); const legendToggle = document.getElementById('showLegendToggle'); if (legendToggle) legendToggle.checked = !!s.show_legend; + const hlToggle = document.getElementById('highlightExtremaToggle'); + if (hlToggle) hlToggle.checked = !!s.highlight_extrema; + const hlHigh = document.getElementById('highlightHighColor'); + if (hlHigh && s.highlight_high_color) hlHigh.value = s.highlight_high_color; + const hlLow = document.getElementById('highlightLowColor'); + if (hlLow && s.highlight_low_color) hlLow.value = s.highlight_low_color; document.getElementById('modelSelect').value = s.model; document.getElementById('fontSelect').value = s.font; document.getElementById('topicInput').value = s.topic || ''; @@ -3309,6 +3345,12 @@

setSelectedExtraOption('none'); const legendToggle = document.getElementById('showLegendToggle'); if (legendToggle) legendToggle.checked = false; + const hlToggle = document.getElementById('highlightExtremaToggle'); + if (hlToggle) hlToggle.checked = false; + const hlHigh = document.getElementById('highlightHighColor'); + if (hlHigh) hlHigh.value = '#00e5ff'; + const hlLow = document.getElementById('highlightLowColor'); + if (hlLow) hlLow.value = '#ff2daa'; changeAiProvider('gemini', fallbackModels.find(model => modelProvider(model) === 'gemini')); document.getElementById('fontSelect').selectedIndex = 0; document.getElementById('topicInput').value = ''; From f10fddab71b9fa372274c3193a3cf21a76886121 Mon Sep 17 00:00:00 2001 From: bibed234 Date: Tue, 17 Nov 2026 14:06:38 +0200 Subject: [PATCH 04/14] Fix world_countries extrema highlight border isolation --- map/auto_map.py | 81 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 70 insertions(+), 11 deletions(-) diff --git a/map/auto_map.py b/map/auto_map.py index 82e0fa4..ae49edf 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -599,6 +599,53 @@ def _random_region_color() -> tuple[int, int, int, int]: return (120, 180, 120, 255) +def _floodfill_bool_mask(interior: np.ndarray, seeds: list, max_pixels: int) -> np.ndarray | None: + """4-connected BFS flood fill on a boolean ``(H, W)`` interior mask, aborting if it exceeds ``max_pixels``.""" + from collections import deque + + h, w = interior.shape + visited = np.zeros((h, w), dtype=bool) + q: deque[tuple[int, int]] = deque() + for coord in seeds: + cx, cy = int(round(coord[0])), int(round(coord[1])) + seed = None + for dy in (0, -2, 2, -4, 4, -8, 8): + for dx in (0, -2, 2, -4, 4, -8, 8): + nx, ny = cx + dx, cy + dy + if 0 <= nx < w and 0 <= ny < h and interior[ny, nx]: + seed = (nx, ny) + break + if seed is not None: + break + if seed is not None and not visited[seed[1], seed[0]]: + visited[seed[1], seed[0]] = True + q.append(seed) + + if not q: + return None + + count = 0 + while q: + x, y = q.popleft() + count += 1 + if count > max_pixels: + return None + if x > 0 and interior[y, x - 1] and not visited[y, x - 1]: + visited[y, x - 1] = True + q.append((x - 1, y)) + if x + 1 < w and interior[y, x + 1] and not visited[y, x + 1]: + visited[y, x + 1] = True + q.append((x + 1, y)) + if y > 0 and interior[y - 1, x] and not visited[y - 1, x]: + visited[y - 1, x] = True + q.append((x, y - 1)) + if y + 1 < h and interior[y + 1, x] and not visited[y + 1, x]: + visited[y + 1, x] = True + q.append((x, y + 1)) + + return visited + + def _build_extrema_highlight_layer( size: tuple[int, int], highest_idx: int | None, @@ -608,6 +655,7 @@ def _build_extrema_highlight_layer( flat: np.ndarray | None, ids: np.ndarray | None, borders: Image.Image | None, + base_map: Image.Image | None = None, high_rgb: tuple[int, int, int] = _RESERVED_HIGHLIGHT_COLORS[0], low_rgb: tuple[int, int, int] = _RESERVED_HIGHLIGHT_COLORS[1], ) -> Image.Image | None: @@ -632,8 +680,16 @@ def _build_extrema_highlight_layer( inner_size = 37 if w >= 3000 else 21 outer_size = 25 if w >= 3000 else 15 - border_work = borders.copy() if (map_type == "world_countries" and borders is not None) else None - border_orig_alpha = np.asarray(borders)[..., 3] if border_work is not None else None + wc_interior_crisp: np.ndarray | None = None + wc_base_alpha: np.ndarray | None = None + wc_border_alpha: np.ndarray | None = None + if map_type == "world_countries" and base_map is not None: + base_arr = np.asarray(base_map) + wc_base_alpha = base_arr[..., 3] + # Crisp dark country borders on world_countries_map.png cleanly separate adjacent nations. + wc_interior_crisp = (wc_base_alpha >= 128) & (base_arr[..., :3].max(axis=2) > 12) + if borders is not None: + wc_border_alpha = np.asarray(borders)[..., 3] for region_idx, rgb in targets: mask: Image.Image | None = None @@ -642,13 +698,16 @@ def _build_extrema_highlight_layer( pix_mask[flat[ids == region_idx]] = 255 if pix_mask.any(): mask = Image.fromarray(pix_mask.reshape((h, w)), mode="L") - elif border_work is not None and 1 <= region_idx <= len(coords_list): - work = border_work.copy() - for coord in coords_list[region_idx - 1]: - ImageDraw.floodfill(work, xy=tuple(coord), value=(255, 255, 255, 255), thresh=60) - work_arr = np.asarray(work) - filled = (work_arr[..., 3] == 255) & (border_orig_alpha < 60) - if filled.any(): + elif wc_interior_crisp is not None and 1 <= region_idx <= len(coords_list): + max_px = int(0.08 * w * h) + filled = _floodfill_bool_mask(wc_interior_crisp, coords_list[region_idx - 1], max_px) + if (filled is None or not filled.any()) and wc_base_alpha is not None and wc_border_alpha is not None: + for thr in (45, 65): + interior = (wc_base_alpha >= 128) & (wc_border_alpha < thr) + filled = _floodfill_bool_mask(interior, coords_list[region_idx - 1], max_px) + if filled is not None and filled.any(): + break + if filled is not None and filled.any(): mask = Image.fromarray((filled.astype(np.uint8) * 255), mode="L") if mask is None: @@ -665,7 +724,7 @@ def _build_extrema_highlight_layer( outer_halo = ImageChops.subtract(small_outer, small_mask).filter(ImageFilter.GaussianBlur(2.5)) glow_small = ImageChops.lighter(inner_ring, outer_halo.point(lambda p: min(255, int(p * 0.95)))) glow_alpha = glow_small.resize((w, h), Image.Resampling.BILINEAR) - tint_alpha = mask.point(lambda p: 75 if p else 0) + tint_alpha = mask.point(lambda p: 95 if p else 0) combined_alpha = ImageChops.lighter(tint_alpha, glow_alpha) overlay = Image.new("RGBA", size, (*rgb, 255)) @@ -1159,7 +1218,7 @@ def _report(stage: int, label: str) -> None: low_rgb = _hex_to_rgba(highlight_low_color, (*_RESERVED_HIGHLIGHT_COLORS[1], 255))[:3] hl_layer = _build_extrema_highlight_layer( img.size, highest_idx, lowest_idx, map_type, dict_, flat, ids, borders, - high_rgb=high_rgb, low_rgb=low_rgb, + base_map=img, high_rgb=high_rgb, low_rgb=low_rgb, ) if hl_layer is not None: result = Image.alpha_composite(result, hl_layer) From 925b335c5bc124d5fbc8239d05b2c9d9c8c196b2 Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 17:45:58 +0200 Subject: [PATCH 05/14] Optimize Rust render/map engine and add logged MoviePy fallback --- automap_rs/.cargo/config.toml | 11 ++ automap_rs/src/lib.rs | 274 +++++++++++++++++++++++++++------- map/auto_map.py | 83 ++++++++-- yt-dlp_serv.py | 71 +++++++-- 4 files changed, 365 insertions(+), 74 deletions(-) create mode 100644 automap_rs/.cargo/config.toml diff --git a/automap_rs/.cargo/config.toml b/automap_rs/.cargo/config.toml new file mode 100644 index 0000000..7cb83a1 --- /dev/null +++ b/automap_rs/.cargo/config.toml @@ -0,0 +1,11 @@ +[target.aarch64-apple-darwin] +rustflags = [ + "-C", "link-arg=-undefined", + "-C", "link-arg=dynamic_lookup", +] + +[target.x86_64-apple-darwin] +rustflags = [ + "-C", "link-arg=-undefined", + "-C", "link-arg=dynamic_lookup", +] diff --git a/automap_rs/src/lib.rs b/automap_rs/src/lib.rs index a0ee964..f9b3875 100644 --- a/automap_rs/src/lib.rs +++ b/automap_rs/src/lib.rs @@ -12,22 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. +use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +use pyo3::types::PyBytes; use std::io::{Read, Write}; use std::process::{Command, Stdio}; /// Describes a single dynamic overlay layer passed from Python as a tuple: /// `(rgba_bytes, x, y, width, height, start_sec, fade_in_sec)`. #[derive(FromPyObject)] -struct DynamicLayer { - rgba: Vec, - x: i32, - y: i32, - width: usize, - height: usize, - start_sec: f32, - fade_in_sec: f32, -} +struct DynamicLayer(Vec, i32, i32, usize, usize, f32, f32); /// Composites the background video, static foreground, dynamic overlays, and intro veil /// frame-by-frame in a single reusable RGBA buffer, streaming directly to/from `ffmpeg`. @@ -63,15 +57,19 @@ fn render_video_rs( // Release Python's GIL so other Flask/worker threads are not blocked during rendering. py.allow_threads(|| { + let ffmpeg_bin = std::env::var("FFMPEG_BINARY").unwrap_or_else(|_| "ffmpeg".to_string()); let total_frames = (duration * fps as f32).round().max(1.0) as u32; let dur_str = format!("{duration:.3}"); + let fps_str = fps.to_string(); - // 1. Spawn ffmpeg decoder: reads the prepared background MP4 and outputs raw RGBA frames. - let mut decoder = Command::new("ffmpeg") + // 1. Spawn ffmpeg decoder: reads the prepared background MP4 and outputs raw RGBA frames at `fps`. + let mut decoder = Command::new(&ffmpeg_bin) .args([ "-y", "-i", bg_video_path, + "-r", + &fps_str, "-t", &dur_str, "-f", @@ -92,7 +90,6 @@ fn render_video_rs( // 2. Build ffmpeg encoder args: reads raw RGBA frames from stdin and encodes with the chosen codec. let size_str = format!("{width}x{height}"); - let fps_str = fps.to_string(); let mut enc_args: Vec = vec![ "-y".into(), "-f".into(), @@ -120,7 +117,7 @@ fn render_video_rs( } enc_args.extend(["-pix_fmt".into(), "yuv420p".into(), output_path.into()]); - let mut encoder = Command::new("ffmpeg") + let mut encoder = Command::new(&ffmpeg_bin) .args(&enc_args) .stdin(Stdio::piped()) .stderr(Stdio::null()) @@ -132,50 +129,66 @@ fn render_video_rs( .take() .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("missing encoder stdin"))?; - // 3. Single reusable frame buffer (~8.3 MB for 1080x1920 RGBA) to avoid per-frame allocations. + // 3. Precompute non-transparent byte spans in static_rgba so alpha==0 regions are skipped per frame. + let static_spans = build_non_transparent_spans(static_rgba); + + // 4. Reusable background and compositing frame buffers (~8.3 MB each for 1080x1920 RGBA). + let mut bg_buf = vec![0u8; expected_len]; let mut frame_buf = vec![0u8; expected_len]; for frame_idx in 0..total_frames { - if dec_out.read_exact(&mut frame_buf).is_err() { - break; + if dec_out.read_exact(&mut bg_buf).is_err() { + if frame_idx == 0 { + break; + } + // Hold the last decoded background frame if the source ended slightly early. } + frame_buf.copy_from_slice(&bg_buf); let t = frame_idx as f32 / fps as f32; // Layer 1: flattened static foreground (map, title, watermark). - blend_full_in_place(&mut frame_buf, static_rgba, 1.0); + blend_spans_in_place(&mut frame_buf, static_rgba, &static_spans); // Layer 2: dynamic overlays (subscribe badge, stars) with optional fade-in. for layer in &dynamic_layers { - if t < layer.start_sec { + let start_sec = layer.5; + let fade_in_sec = layer.6; + if t < start_sec { continue; } - let opacity = if layer.fade_in_sec > 0.0 { - ((t - layer.start_sec) / layer.fade_in_sec).clamp(0.0, 1.0) + let opacity = if fade_in_sec > 0.0 { + ((t - start_sec) / fade_in_sec).clamp(0.0, 1.0) } else { 1.0 }; + let op_u8 = (opacity * 255.0).round().clamp(0.0, 255.0) as u32; + if op_u8 == 0 { + continue; + } blend_rect_in_place( &mut frame_buf, width, height, - &layer.rgba, - layer.x, - layer.y, - layer.width, - layer.height, - opacity, + &layer.0, + layer.1, + layer.2, + layer.3, + layer.4, + op_u8, ); } // Layer 3: intro fade-in veil (darkens RGB channels linearly at the start). if veil_duration > 0.0 && t < veil_duration { let veil_alpha = (0.88 * (1.0 - (t / veil_duration))).clamp(0.0, 1.0); - let brightness = 1.0 - veil_alpha; - for px in frame_buf.chunks_exact_mut(4) { - px[0] = (px[0] as f32 * brightness) as u8; - px[1] = (px[1] as f32 * brightness) as u8; - px[2] = (px[2] as f32 * brightness) as u8; + let brightness_q8 = ((1.0 - veil_alpha) * 256.0).round().clamp(0.0, 256.0) as u32; + if brightness_q8 < 256 { + for px in frame_buf.chunks_exact_mut(4) { + px[0] = ((px[0] as u32 * brightness_q8) >> 8) as u8; + px[1] = ((px[1] as u32 * brightness_q8) >> 8) as u8; + px[2] = ((px[2] as u32 * brightness_q8) >> 8) as u8; + } } } @@ -201,13 +214,33 @@ fn render_video_rs( }) } -/// Alpha-blends a full-canvas RGBA overlay onto `base` in place. -fn blend_full_in_place(base: &mut [u8], overlay: &[u8], opacity: f32) { - if opacity <= 0.0 { - return; +/// Collects contiguous byte ranges `[start, end)` in `rgba` where `alpha > 0`. +fn build_non_transparent_spans(rgba: &[u8]) -> Vec<(usize, usize)> { + let mut spans = Vec::new(); + let mut in_span = false; + let mut start = 0usize; + for (idx, px) in rgba.chunks_exact(4).enumerate() { + let non_zero = px[3] > 0; + if non_zero && !in_span { + start = idx * 4; + in_span = true; + } else if !non_zero && in_span { + spans.push((start, idx * 4)); + in_span = false; + } + } + if in_span { + spans.push((start, rgba.len() - (rgba.len() % 4))); } - for (bg, fg) in base.chunks_exact_mut(4).zip(overlay.chunks_exact(4)) { - blend_pixel(bg, fg, opacity); + spans +} + +/// Alpha-blends precomputed non-transparent byte spans of `overlay` onto `base` in place. +fn blend_spans_in_place(base: &mut [u8], overlay: &[u8], spans: &[(usize, usize)]) { + for &(start, end) in spans { + for (bg, fg) in base[start..end].chunks_exact_mut(4).zip(overlay[start..end].chunks_exact(4)) { + blend_pixel_u8(bg, fg); + } } } @@ -222,47 +255,182 @@ fn blend_rect_in_place( y: i32, ov_w: usize, ov_h: usize, - opacity: f32, + op_u8: u32, ) { - if opacity <= 0.0 || ov_w == 0 || ov_h == 0 { + if op_u8 == 0 || ov_w == 0 || ov_h == 0 { return; } let start_y = y.max(0) as usize; let end_y = (y + ov_h as i32).min(canvas_h as i32).max(0) as usize; let start_x = x.max(0) as usize; let end_x = (x + ov_w as i32).min(canvas_w as i32).max(0) as usize; + if start_x >= end_x || start_y >= end_y { + return; + } + let row_bytes = (end_x - start_x) * 4; + let ox_start = (start_x as i32 - x) as usize; for cy in start_y..end_y { let oy = (cy as i32 - y) as usize; - for cx in start_x..end_x { - let ox = (cx as i32 - x) as usize; - let bg_idx = (cy * canvas_w + cx) * 4; - let fg_idx = (oy * ov_w + ox) * 4; - if fg_idx + 4 <= overlay.len() && bg_idx + 4 <= base.len() { - blend_pixel(&mut base[bg_idx..bg_idx + 4], &overlay[fg_idx..fg_idx + 4], opacity); + let bg_start = (cy * canvas_w + start_x) * 4; + let fg_start = (oy * ov_w + ox_start) * 4; + if fg_start + row_bytes > overlay.len() || bg_start + row_bytes > base.len() { + continue; + } + let bg_row = &mut base[bg_start..bg_start + row_bytes]; + let fg_row = &overlay[fg_start..fg_start + row_bytes]; + if op_u8 == 255 { + for (bg, fg) in bg_row.chunks_exact_mut(4).zip(fg_row.chunks_exact(4)) { + blend_pixel_u8(bg, fg); + } + } else { + for (bg, fg) in bg_row.chunks_exact_mut(4).zip(fg_row.chunks_exact(4)) { + blend_pixel_scaled(bg, fg, op_u8); } } } } #[inline(always)] -fn blend_pixel(bg: &mut [u8], fg: &[u8], opacity: f32) { - let fg_a = (fg[3] as f32 / 255.0) * opacity; - if fg_a <= 0.0 { +fn blend_pixel_u8(bg: &mut [u8], fg: &[u8]) { + let a = fg[3] as u32; + if a == 0 { return; } - if fg_a >= 1.0 { + if a == 255 { bg.copy_from_slice(fg); return; } - let inv_a = 1.0 - fg_a; - bg[0] = (fg[0] as f32 * fg_a + bg[0] as f32 * inv_a) as u8; - bg[1] = (fg[1] as f32 * fg_a + bg[1] as f32 * inv_a) as u8; - bg[2] = (fg[2] as f32 * fg_a + bg[2] as f32 * inv_a) as u8; + let inv_a = 255 - a; + bg[0] = (((fg[0] as u32 * a + bg[0] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[1] = (((fg[1] as u32 * a + bg[1] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[2] = (((fg[2] as u32 * a + bg[2] as u32 * inv_a + 128) * 257) >> 16) as u8; +} + +#[inline(always)] +fn blend_pixel_scaled(bg: &mut [u8], fg: &[u8], op_u8: u32) { + let raw_a = fg[3] as u32; + if raw_a == 0 { + return; + } + let a = ((raw_a * op_u8 + 128) * 257) >> 16; + if a == 0 { + return; + } + let inv_a = 255 - a; + bg[0] = (((fg[0] as u32 * a + bg[0] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[1] = (((fg[1] as u32 * a + bg[1] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[2] = (((fg[2] as u32 * a + bg[2] as u32 * inv_a + 128) * 257) >> 16) as u8; +} + +/// Copies `base_rgba` and paints pixels at `flat_indices` (native-endian `u32` bytes) +/// using `region_ids` (native-endian `u16` bytes) into `lut_rgba` where `use_mask[rid] != 0`. +#[pyfunction] +fn paint_regions_rs( + py: Python<'_>, + base_rgba: &[u8], + flat_indices: &[u8], + region_ids: &[u8], + lut_rgba: &[u8], + use_mask: &[u8], +) -> PyResult> { + if base_rgba.len() % 4 != 0 { + return Err(PyValueError::new_err("base_rgba length must be a multiple of 4")); + } + if flat_indices.len() % 4 != 0 { + return Err(PyValueError::new_err("flat_indices byte length must be a multiple of 4 (u32)")); + } + if region_ids.len() % 2 != 0 { + return Err(PyValueError::new_err("region_ids byte length must be a multiple of 2 (u16)")); + } + let count = flat_indices.len() / 4; + if region_ids.len() / 2 != count { + return Err(PyValueError::new_err(format!( + "flat_indices count ({count}) != region_ids count ({})", + region_ids.len() / 2 + ))); + } + let num_regions = use_mask.len(); + if lut_rgba.len() < num_regions * 4 { + return Err(PyValueError::new_err(format!( + "lut_rgba length ({}) is smaller than use_mask.len() * 4 ({})", + lut_rgba.len(), + num_regions * 4 + ))); + } + let num_pixels = base_rgba.len() / 4; + + let bytes = PyBytes::new_with(py, base_rgba.len(), |out| { + out.copy_from_slice(base_rgba); + for (idx_b, id_b) in flat_indices.chunks_exact(4).zip(region_ids.chunks_exact(2)) { + let rid = u16::from_ne_bytes([id_b[0], id_b[1]]) as usize; + if rid < num_regions && use_mask[rid] != 0 { + let pix_idx = u32::from_ne_bytes([idx_b[0], idx_b[1], idx_b[2], idx_b[3]]) as usize; + if pix_idx < num_pixels { + let dst = pix_idx * 4; + let src = rid * 4; + out[dst..dst + 4].copy_from_slice(&lut_rgba[src..src + 4]); + } + } + } + Ok(()) + })?; + Ok(bytes.unbind()) +} + +/// Fast integer Porter-Duff "over" compositing for straight RGBA buffers of equal length. +#[pyfunction] +fn alpha_composite_rs( + py: Python<'_>, + base_rgba: &[u8], + overlay_rgba: &[u8], +) -> PyResult> { + if base_rgba.len() != overlay_rgba.len() || base_rgba.len() % 4 != 0 { + return Err(PyValueError::new_err(format!( + "base_rgba ({}) and overlay_rgba ({}) must have equal length divisible by 4", + base_rgba.len(), + overlay_rgba.len() + ))); + } + + let bytes = PyBytes::new_with(py, base_rgba.len(), |out| { + out.copy_from_slice(base_rgba); + for (dst, src) in out.chunks_exact_mut(4).zip(overlay_rgba.chunks_exact(4)) { + let sa = src[3] as u32; + if sa == 0 { + continue; + } + if sa == 255 || dst[3] == 0 { + dst.copy_from_slice(src); + continue; + } + let da = dst[3] as u32; + if da == 255 { + let inv_sa = 255 - sa; + dst[0] = (((src[0] as u32 * sa + dst[0] as u32 * inv_sa + 128) * 257) >> 16) as u8; + dst[1] = (((src[1] as u32 * sa + dst[1] as u32 * inv_sa + 128) * 257) >> 16) as u8; + dst[2] = (((src[2] as u32 * sa + dst[2] as u32 * inv_sa + 128) * 257) >> 16) as u8; + // dst[3] remains 255 + } else { + let sa_255 = sa * 255; + let da_inv = da * (255 - sa); + let out_a_255 = sa_255 + da_inv; + let half = out_a_255 >> 1; + dst[0] = ((src[0] as u32 * sa_255 + dst[0] as u32 * da_inv + half) / out_a_255) as u8; + dst[1] = ((src[1] as u32 * sa_255 + dst[1] as u32 * da_inv + half) / out_a_255) as u8; + dst[2] = ((src[2] as u32 * sa_255 + dst[2] as u32 * da_inv + half) / out_a_255) as u8; + dst[3] = (((out_a_255 + 128) * 257) >> 16) as u8; + } + } + Ok(()) + })?; + Ok(bytes.unbind()) } #[pymodule] fn automap_rs(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(render_video_rs, m)?)?; + m.add_function(wrap_pyfunction!(paint_regions_rs, m)?)?; + m.add_function(wrap_pyfunction!(alpha_composite_rs, m)?)?; Ok(()) } diff --git a/map/auto_map.py b/map/auto_map.py index ae49edf..85f3e61 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -14,6 +14,7 @@ import ast import hashlib +import logging import os import random import io @@ -210,22 +211,80 @@ def _region_index(map_path: Path, base: Image.Image, coords: dict) -> tuple[np.n return result +_RUST_WARNED = False + + +def _get_automap_rs(): + """Return the native ``automap_rs`` module when available, else ``None``.""" + global _RUST_WARNED + try: + import automap_rs + if hasattr(automap_rs, "paint_regions_rs") and hasattr(automap_rs, "alpha_composite_rs"): + return automap_rs + raise ImportError("automap_rs map functions not built") + except Exception as exc: + if not _RUST_WARNED: + _RUST_WARNED = True + msg = f"Rust map acceleration unavailable ({type(exc).__name__}: {exc}); falling back to Python/PIL." + log.warning(msg) + logging.warning(msg) + return None + + +def _alpha_composite(base: Image.Image, overlay: Image.Image) -> Image.Image: + """Alpha-composite ``overlay`` over ``base`` using Rust when available.""" + global _RUST_WARNED + rs = _get_automap_rs() + if rs is not None and base.size == overlay.size: + try: + base_rgba = base if base.mode == "RGBA" else base.convert("RGBA") + overlay_rgba = overlay if overlay.mode == "RGBA" else overlay.convert("RGBA") + out_bytes = rs.alpha_composite_rs(base_rgba.tobytes(), overlay_rgba.tobytes()) + return Image.frombytes("RGBA", base.size, out_bytes) + except Exception as exc: + if not _RUST_WARNED: + _RUST_WARNED = True + msg = f"Rust alpha_composite_rs failed ({type(exc).__name__}: {exc}); falling back to PIL." + log.warning(msg) + logging.warning(msg) + return Image.alpha_composite(base, overlay) + + def _paint_regions(img: Image.Image, flat: np.ndarray, ids: np.ndarray, colors: dict[int, tuple[int, int, int, int]]) -> Image.Image: """Return a copy of ``img`` with region ``i`` painted ``colors[i]``.""" + global _RUST_WARNED if not colors: return img.copy() n = int(max(colors)) + 1 if ids.size: n = max(n, int(ids.max()) + 1) lut = np.zeros((n, 4), dtype=np.uint8) - use = np.zeros(n, dtype=bool) + use = np.zeros(n, dtype=np.uint8) for i, c in colors.items(): lut[i] = c - use[i] = True + use[i] = 1 + rs = _get_automap_rs() + if rs is not None: + try: + base_rgba = img if img.mode == "RGBA" else img.convert("RGBA") + out_bytes = rs.paint_regions_rs( + base_rgba.tobytes(), + np.ascontiguousarray(flat, dtype=np.uint32).tobytes(), + np.ascontiguousarray(ids, dtype=np.uint16).tobytes(), + lut.tobytes(), + use.tobytes(), + ) + return Image.frombytes("RGBA", img.size, out_bytes) + except Exception as exc: + if not _RUST_WARNED: + _RUST_WARNED = True + msg = f"Rust paint_regions_rs failed ({type(exc).__name__}: {exc}); falling back to NumPy." + log.warning(msg) + logging.warning(msg) arr = np.array(img, dtype=np.uint8) pix = arr.reshape(-1, 4) - sel = use[ids] + sel = use.astype(bool, copy=False)[ids] pix[flat[sel]] = lut[ids[sel]] return Image.fromarray(arr) @@ -1209,7 +1268,7 @@ def _report(stage: int, label: str) -> None: # Relief is resized and its opacity reduced once per process. maps_dir = Path(__file__).parent.parent / "resources" / "maps" relief = _prepared_relief(maps_dir / relief_name, img.size) - result = Image.alpha_composite(img, relief) + result = _alpha_composite(img, relief) # Restore borders above the relief, then put readable labels on top. borders = _load_rgba(maps_dir / borders_name) @@ -1221,14 +1280,14 @@ def _report(stage: int, label: str) -> None: base_map=img, high_rgb=high_rgb, low_rgb=low_rgb, ) if hl_layer is not None: - result = Image.alpha_composite(result, hl_layer) - result = Image.alpha_composite(result, borders) - result = Image.alpha_composite(result, text_layer) + result = _alpha_composite(result, hl_layer) + result = _alpha_composite(result, borders) + result = _alpha_composite(result, text_layer) if has_most_least and map_type != "world" and most_least is not None: - result = Image.alpha_composite(result, most_least) + result = _alpha_composite(result, most_least) else: - result = Image.alpha_composite(img, text_layer) + result = _alpha_composite(img, text_layer) if show_legend: if mode == "number": @@ -1256,7 +1315,7 @@ def _report(stage: int, label: str) -> None: has_ml, ) if legend_layer is not None: - result = Image.alpha_composite(result, legend_layer) + result = _alpha_composite(result, legend_layer) _report(4, "Encoding final PNG...") @@ -1264,7 +1323,7 @@ def _report(stage: int, label: str) -> None: # Return an in-memory PNG for the web API instead of writing result.png. buffer = io.BytesIO() - result.save(buffer, format='PNG') + result.save(buffer, format='PNG', compress_level=1) # Consumers should be able to read the PNG from its first byte. buffer.seek(0) buffer.map_meta = render_meta @@ -1274,7 +1333,7 @@ def _report(stage: int, label: str) -> None: out_path = Path(__file__).parent.parent / "result.png" log.step(f"Saving result to {out_path}") - result.save(out_path) + result.save(out_path, compress_level=1) if show_result: result.show("Map") diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index 4495807..f03ad5e 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -13,11 +13,14 @@ # limitations under the License. import base64 +import importlib import io +import logging import os import re import shutil import subprocess +import sys import tempfile import time import uuid @@ -451,6 +454,34 @@ def cut_audio() -> tuple[object, int]: ) +def _load_automap_rs(): + """Import ``automap_rs``, bypassing any local source directory shadowing.""" + if "automap_rs" in sys.modules and sys.modules["automap_rs"] is None: + raise ImportError("automap_rs is disabled") + + mod = sys.modules.get("automap_rs") + if mod is None: + mod = importlib.import_module("automap_rs") + if hasattr(mod, "render_video_rs"): + return mod + + # When CWD is the repo root, ./automap_rs/ can shadow site-packages/automap_rs.abi3.so. + repo_root = os.path.dirname(os.path.abspath(__file__)) + orig_path = list(sys.path) + try: + sys.path = [p for p in orig_path if os.path.abspath(p or os.getcwd()) != repo_root] + if "automap_rs" in sys.modules and sys.modules["automap_rs"] is not None: + if not hasattr(sys.modules["automap_rs"], "render_video_rs"): + sys.modules.pop("automap_rs", None) + mod = importlib.import_module("automap_rs") + finally: + sys.path = orig_path + + if not hasattr(mod, "render_video_rs"): + raise ImportError("automap_rs native extension not built") + return mod + + @app.route('/api/video_title_preview', methods=['POST']) def video_title_preview(): from PIL import Image @@ -648,6 +679,7 @@ def _decode_optional_image(field: str, label: str): media_resources.append(background_video) background_video = background_video.with_duration(bg_duration) dynamic_layers = {id(background_video)} + dynamic_fade_timing = {} # Darken the edges and the area behind the title for readable white text. import numpy as np @@ -733,6 +765,7 @@ def _decode_optional_image(field: str, label: str): subscribe_clip = _apply_clip_fade_in(subscribe_clip, bg_duration, fade_start=fade_start, fade_duration=fade_dur) subscribe_clip = subscribe_clip.with_position(('center', accent_top)) dynamic_layers.add(id(subscribe_clip)) + dynamic_fade_timing[id(subscribe_clip)] = (float(fade_start), float(fade_dur)) accent_height = max(accent_height, subscribe_clip.h) map_top = accent_top + accent_height + gap if accent_height else accent_top @@ -785,13 +818,17 @@ def _decode_optional_image(field: str, label: str): else: stars_arr = _stars_row_image(watermark_color or '#ffffff', effects) stars_clip = ImageClip(stars_arr).with_duration(bg_duration) + stars_start = 0.0 + stars_fade_dur = 0.0 if bg_duration > 1.8: stars_start = min(1.8, bg_duration * 0.25) - stars_clip = _apply_clip_fade_in(stars_clip, bg_duration, fade_start=stars_start, fade_duration=0.5) + stars_fade_dur = 0.5 + stars_clip = _apply_clip_fade_in(stars_clip, bg_duration, fade_start=stars_start, fade_duration=stars_fade_dur) stars_y = 1805 if watermark_text else 1785 stars_clip = stars_clip.with_position(('center', stars_y)) if bg_duration > 1.8: dynamic_layers.add(id(stars_clip)) + dynamic_fade_timing[id(stars_clip)] = (float(stars_start), float(stars_fade_dur)) clips.append(stars_clip) if intro_fade: from moviepy import VideoClip @@ -825,10 +862,7 @@ def _veil_mask(t: float) -> np.ndarray: used_rust = False # ======== RUST ENGINE INJECTION ============= try: # pragma: no cover - import automap_rs - - if not hasattr(automap_rs, "render_video_rs"): - raise ImportError("automap_rs native extension not built") + automap_rs = _load_automap_rs() def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: # MoviePy splits RGBA inputs into 3-channel clip.img + float clip.mask. @@ -857,7 +891,15 @@ def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: is_full_canvas = clip.img.shape[:2] == (canvas_h, canvas_w) if not is_dynamic and is_full_canvas: - static_rgba = _clip_to_rgba_bytes(clip, 0.0) + layer_rgba = _clip_to_rgba_bytes(clip, 0.0) + if static_rgba is None: + static_rgba = layer_rgba + elif hasattr(automap_rs, "alpha_composite_rs"): + static_rgba = automap_rs.alpha_composite_rs(static_rgba, layer_rgba) + else: + base_img = Image.frombytes("RGBA", (canvas_w, canvas_h), static_rgba) + over_img = Image.frombytes("RGBA", (canvas_w, canvas_h), layer_rgba) + static_rgba = Image.alpha_composite(base_img, over_img).tobytes() elif is_dynamic and is_full_canvas and clip.img.shape[2] == 3: # Full-canvas 3-channel black clip represents the intro fade veil. veil_duration = float(clip.duration or 0.0) @@ -867,9 +909,16 @@ def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: h, w = clip.img.shape[:2] x = (canvas_w - w) // 2 if pos[0] == "center" else int(pos[0]) y = (canvas_h - h) // 2 if pos[1] == "center" else int(pos[1]) - dynamic_overlays.append((_clip_to_rgba_bytes(clip, float(bg_duration)), x, y, int(w), int(h), 0.0, 0.0)) + start_sec, fade_in_sec = dynamic_fade_timing.get(id(clip), (0.0, 0.0)) + dynamic_overlays.append((_clip_to_rgba_bytes(clip, float(bg_duration)), x, y, int(w), int(h), start_sec, fade_in_sec)) if static_rgba is not None and prepared_bg_path: + try: + from moviepy.config import FFMPEG_BINARY + if FFMPEG_BINARY: + os.environ.setdefault("FFMPEG_BINARY", FFMPEG_BINARY) + except ImportError: + pass automap_rs.render_video_rs( prepared_bg_path, static_rgba, @@ -886,8 +935,12 @@ def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: data.get('draft') is True, ) used_rust = True - except ImportError: - pass + except Exception as exc: + logging.warning( + "Rust video render unavailable or failed (%s: %s); falling back to MoviePy.", + type(exc).__name__, + exc, + ) if not used_rust: # pragma: no branch final_clip = CompositeVideoClip(clips, size=(canvas_w, canvas_h)) From e204d534d0711fad3437d674f5134436ab931e23 Mon Sep 17 00:00:00 2001 From: bibed234 Date: Tue, 17 Nov 2026 18:03:40 +0200 Subject: [PATCH 06/14] Add country reveal animation, impact glitch/shake, zoom-out, and auto-sync title # Conflicts: # yt-dlp_serv.py --- main.py | 323 +++++++++++++++++++++++++++++++++ templates/index.html | 93 ++++++++-- templates/video.html | 282 ++++++++++++++++++++++++++++- yt-dlp_serv.py | 420 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 1098 insertions(+), 20 deletions(-) diff --git a/main.py b/main.py index a52f126..df0d82e 100644 --- a/main.py +++ b/main.py @@ -22,6 +22,7 @@ import base64 import io +import math import os import re import threading @@ -1309,6 +1310,293 @@ def _render_video_request_data(): return data +_ZOOM_REF_DIMENSIONS: dict[str, tuple[float, float]] = { + "europe": (3900.0, 4104.0), + "world": (3424.0, 2027.0), +} +_ZOOM_OUTLINE_CACHE: dict[tuple[str, str], bytes] = {} +_REVEAL_MASK_CACHE: dict[tuple[str, str, int, int], str] = {} +_ZOOM_CACHE_LOCK = threading.Lock() + + +def _zoom_country_entries( + coords: dict[str, list[tuple[int, int]]], + ref_w: float, + ref_h: float, +) -> list[dict[str, object]]: + """Build normalized (0..1) center coordinate entries for a country map.""" + return [ + { + "key": k, + "name": k.replace("_", " ").title(), + "x": round(pts[0][0] / ref_w, 4), + "y": round(pts[0][1] / ref_h, 4), + } + for k, pts in coords.items() + if pts + ] + + +def _region_mask_from_index( + map_path: Path, + coords: dict[str, list[tuple[int, int]]], + key: str, +) -> Image.Image | None: + """Extract a full-resolution L-mode binary mask using ``_region_index``.""" + import numpy as np + from map.auto_map import _load_rgba, _region_index + + if key not in coords: + return None + region_idx = list(coords.keys()).index(key) + 1 + base = _load_rgba(map_path) + w, h = base.size + flat, ids = _region_index(map_path, base, coords) + pix_mask = np.zeros(w * h, dtype=np.uint8) + pix_mask[flat[ids == region_idx]] = 255 + if not pix_mask.any(): + return None + return Image.fromarray(pix_mask.reshape((h, w)), mode="L") + + +def _world_country_floodfill_mask(seeds: list[tuple[int, int]]) -> Image.Image | None: + """Extract a full-resolution L-mode binary mask on ``world_countries_map.png``.""" + import numpy as np + from map.auto_map import _floodfill_bool_mask, _load_rgba + + if not seeds: + return None + maps_dir = BASE_DIR / "resources" / "maps" + map_path = maps_dir / "world_countries_map.png" + base = _load_rgba(map_path) + w, h = base.size + base_arr = np.asarray(base) + wc_base_alpha = base_arr[..., 3] + wc_dark = (wc_base_alpha >= 128) & (base_arr[..., :3].max(axis=2) <= 12) + wc_interior_crisp = (wc_base_alpha >= 128) & ~wc_dark + wc_interior = wc_interior_crisp + + wc_border_alpha = None + borders_path = maps_dir / "world_countries_map_blured.png" + if borders_path.is_file(): + borders = _load_rgba(borders_path) + if borders.size == (w, h): + wc_border_alpha = np.asarray(borders)[..., 3] + # Only trust blurred border alpha to bridge inland black flag bands + # when the border asset actually covers the crisp borders. + if not wc_dark.any() or float(np.mean(wc_border_alpha[wc_dark] >= 20)) >= 0.8: + wc_interior = wc_interior_crisp | ((wc_base_alpha >= 128) & (wc_border_alpha < 44)) + + max_px = int(0.08 * w * h) + filled = _floodfill_bool_mask(wc_interior, seeds, max_px) + if (filled is None or not filled.any()) and wc_border_alpha is not None: + for thr in (45, 65): + interior = (wc_base_alpha >= 128) & (wc_border_alpha < thr) + filled = _floodfill_bool_mask(interior, seeds, max_px) + if filled is not None and filled.any(): + break + if filled is None or not filled.any(): + return None + return Image.fromarray((filled.astype(np.uint8) * 255), mode="L") + + +def _extract_country_mask_image( + map_kind: str, + key: str, + *, + allow_world_continent_fallback: bool = False, +) -> Image.Image | None: + """Return a full-resolution L-mode binary mask for ``key`` on ``europe`` or ``world``.""" + from map.constants import europe_coords, world_coords + from map.world_countries_coords import world_countries_coords + + maps_dir = BASE_DIR / "resources" / "maps" + if map_kind == "europe": + return _region_mask_from_index(maps_dir / "default_map.png", europe_coords, key) + if map_kind == "world": + if key in world_countries_coords: + return _world_country_floodfill_mask(world_countries_coords[key]) + if allow_world_continent_fallback and key in world_coords: + return _region_mask_from_index(maps_dir / "world_map.png", world_coords, key) + return None + + +def _resolve_reveal_country_key( + coords: dict[str, list[tuple[int, int]]], + ref_w: float, + ref_h: float, + zoom_country_key: str, + zoom_x: float, + zoom_y: float, +) -> str: + """Resolve target country key by exact match or nearest seed within 0.18 distance.""" + candidate = str(zoom_country_key or "").strip().lower() + if candidate and candidate in coords and coords[candidate]: + return candidate + if isinstance(zoom_x, bool) or isinstance(zoom_y, bool): + return "" + try: + zx = float(zoom_x) + zy = float(zoom_y) + except (TypeError, ValueError): + return "" + if not (math.isfinite(zx) and math.isfinite(zy)): + return "" + best_key = "" + best_dist_sq = 0.18 * 0.18 + for k, pts in coords.items(): + if not pts: + continue + dx = (pts[0][0] / ref_w) - zx + dy = (pts[0][1] / ref_h) - zy + dist_sq = dx * dx + dy * dy + if dist_sq <= best_dist_sq: + best_dist_sq = dist_sq + best_key = k + return best_key + + +def _extract_country_reveal_mask( + map_w: int, + map_h: int, + zoom_country_key: str, + zoom_x: float, + zoom_y: float, +) -> str: + """Extract a country reveal mask as a base64 L-mode PNG resized to ``(map_w, map_h)``.""" + map_w = int(map_w) + map_h = int(map_h) + if map_w <= 0 or map_h <= 0: + return "" + + from map.constants import europe_coords + from map.world_countries_coords import world_countries_coords + + map_kind = "europe" if (map_w / max(1, map_h)) < 1.25 else "world" + coords = europe_coords if map_kind == "europe" else world_countries_coords + ref_w, ref_h = _ZOOM_REF_DIMENSIONS[map_kind] + + key = _resolve_reveal_country_key( + coords, ref_w, ref_h, zoom_country_key, zoom_x, zoom_y + ) + if not key: + return "" + + cache_key = (map_kind, key, map_w, map_h) + with _ZOOM_CACHE_LOCK: + cached = _REVEAL_MASK_CACHE.get(cache_key) + if cached is not None: + return cached + + mask = _extract_country_mask_image(map_kind, key, allow_world_continent_fallback=False) + if mask is None: + return "" + if mask.size != (map_w, map_h): + mask = mask.resize((map_w, map_h), Image.Resampling.BILINEAR) + if mask.mode != "L": + mask = mask.convert("L") + if mask.getbbox() is None: + return "" + + buf = io.BytesIO() + mask.save(buf, format="PNG") + b64_mask = base64.b64encode(buf.getvalue()).decode("ascii") + with _ZOOM_CACHE_LOCK: + _REVEAL_MASK_CACHE[cache_key] = b64_mask + return b64_mask + + +def _parse_finite_coord(value: object, default: float) -> float: + """Parse a finite float coordinate, falling back to ``default`` when invalid.""" + if value is None or isinstance(value, bool) or value == "": + return default + try: + parsed = float(value) + except (TypeError, ValueError): + return default + return parsed if math.isfinite(parsed) else default + + +def _decode_image_size(image_data: object) -> tuple[int, int] | None: + """Decode a base64 or data-URL image payload and return its ``(width, height)``.""" + if not isinstance(image_data, str) or not image_data.strip(): + return None + raw_b64 = image_data.strip() + if "," in raw_b64 and raw_b64.lower().startswith("data:"): + _, raw_b64 = raw_b64.split(",", 1) + b64_part = "".join(raw_b64.split()) + if not b64_part: + return None + try: + decoded = base64.b64decode(b64_part, validate=True) + except (ValueError, TypeError): + return None + if not decoded: + return None + try: + with Image.open(io.BytesIO(decoded)) as opened: + return opened.size + except (UnidentifiedImageError, OSError, Image.DecompressionBombError, ValueError): + return None + + +@app.get('/api/zoom_countries') +def api_zoom_countries(): + """Return normalized (0..1) country center coordinates for Europe and World maps.""" + from map.constants import europe_coords, world_coords + from map.world_countries_coords import world_countries_coords + + europe = _zoom_country_entries(europe_coords, *_ZOOM_REF_DIMENSIONS["europe"]) + world_source = world_countries_coords if world_countries_coords else world_coords + world = _zoom_country_entries(world_source, *_ZOOM_REF_DIMENSIONS["world"]) + return jsonify({"europe": europe, "world": world}) + + +@app.get('/api/zoom_country_outline') +def api_zoom_country_outline(): + """Return a small transparent PNG highlighting the hovered country's outline.""" + from PIL import ImageChops, ImageFilter + + map_kind = str(request.args.get('map') or 'europe').strip().lower() + key = str(request.args.get('key') or '').strip().lower() + if not key or map_kind not in ('europe', 'world'): + return ('', 404) + + cache_key = (map_kind, key) + with _ZOOM_CACHE_LOCK: + cached = _ZOOM_OUTLINE_CACHE.get(cache_key) + if cached is not None: + resp = Response(cached, mimetype='image/png') + resp.headers['Cache-Control'] = 'public, max-age=86400' + return resp + + mask = _extract_country_mask_image( + map_kind, key, allow_world_continent_fallback=True + ) + if mask is None: + return ('', 404) + + w, h = mask.size + pw = 360 + ph = max(1, int(round(h * (pw / w)))) + small_mask = mask.resize((pw, ph), Image.Resampling.BILINEAR) + edge = ImageChops.subtract(small_mask.filter(ImageFilter.MaxFilter(5)), small_mask.filter(ImageFilter.MinFilter(3))) + fill_alpha = small_mask.point(lambda p: 45 if p > 128 else 0) + alpha = ImageChops.lighter(fill_alpha, edge.point(lambda p: min(255, int(p * 1.2)))) + + out = Image.new('RGBA', (pw, ph), (252, 211, 77, 255)) + out.putalpha(alpha) + buf = io.BytesIO() + out.save(buf, format='PNG') + png_bytes = buf.getvalue() + with _ZOOM_CACHE_LOCK: + _ZOOM_OUTLINE_CACHE[cache_key] = png_bytes + + resp = Response(png_bytes, mimetype='image/png') + resp.headers['Cache-Control'] = 'public, max-age=86400' + return resp + + @app.route('/api/render_video', methods=['POST']) @app.route('/api/render_video/', methods=['POST']) def make_video() -> tuple[object, int]: @@ -1340,6 +1628,29 @@ def make_video() -> tuple[object, int]: codec = str(data.get('codec') or 'libx264').strip() duration = data.get('duration') + raw_country_key = data.get('zoom_country_key') + zoom_country_key = raw_country_key.strip() if isinstance(raw_country_key, str) else '' + raw_reveal = data.get('reveal_enabled', False) + reveal_enabled = ( + raw_reveal.strip().lower() in _TRUTHY + if isinstance(raw_reveal, str) + else bool(raw_reveal) + ) + reveal_time = data.get('reveal_time', None) + reveal_mask = '' + if reveal_enabled and map_b64: + map_size = _decode_image_size(map_b64) + if map_size is not None: + zoom_x = _parse_finite_coord(data.get('zoom_x'), 0.80) + zoom_y = _parse_finite_coord(data.get('zoom_y'), 0.35) + reveal_mask = _extract_country_reveal_mask( + map_size[0], + map_size[1], + zoom_country_key, + zoom_x, + zoom_y, + ) + try: response = requests.post( f"{WORKER_URL}/api/render_video/", @@ -1373,6 +1684,18 @@ def make_video() -> tuple[object, int]: "subscribe_text": data.get('subscribe_text', 'Subscribe!'), "subscribe_delay": data.get('subscribe_delay', 2.5), "intro_fade": data.get('intro_fade', False), + "zoom_enabled": data.get('zoom_enabled', False), + "zoom_x": data.get('zoom_x', 0.80), + "zoom_y": data.get('zoom_y', 0.35), + "zoom_scale": data.get('zoom_scale', 2.0), + "zoom_start": data.get('zoom_start', 1.5), + "zoom_duration": data.get('zoom_duration', 2.5), + "zoom_out_enabled": data.get('zoom_out_enabled', False), + "zoom_out_duration": data.get('zoom_out_duration', 2.0), + "zoom_country_key": zoom_country_key, + "reveal_enabled": reveal_enabled, + "reveal_time": reveal_time, + "reveal_mask": reveal_mask, **({'render_id': data['render_id']} if data.get('render_id') is not None else {}), }, # Video rendering (moviepy/ffmpeg) can take a while - allow more time. diff --git a/templates/index.html b/templates/index.html index 92e01a5..683b429 100644 --- a/templates/index.html +++ b/templates/index.html @@ -3194,6 +3194,33 @@

showToast("Run history cleared", "info"); } + function createHistoryThumbnail(dataUrl, size = 96) { + return new Promise(resolve => { + if (!dataUrl || !dataUrl.startsWith('data:image/')) { + resolve(null); + return; + } + const img = new Image(); + img.onload = () => { + try { + const canvas = document.createElement('canvas'); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext('2d'); + const scale = Math.max(size / img.naturalWidth, size / img.naturalHeight); + const drawW = img.naturalWidth * scale; + const drawH = img.naturalHeight * scale; + ctx.drawImage(img, (size - drawW) / 2, (size - drawH) / 2, drawW, drawH); + resolve(canvas.toDataURL('image/jpeg', 0.82)); + } catch { + resolve(null); + } + }; + img.onerror = () => resolve(null); + img.src = dataUrl; + }); + } + function addToHistory(state, cmd, extra = {}) { const {api_key, ...savedState} = state; const createdAt = Date.now(); @@ -3204,12 +3231,44 @@

state: savedState, cmd, image_url: extra.image_url || null, + thumb_url: null, analysis: extra.analysis || null, map_values: extra.map_values || null }; runHistory = [entry, ...runHistory.filter(item => createdAt - item.createdAt <= HISTORY_RETENTION_MS)]; renderRunHistory(); - queueHistoryWrite(() => StudioStorage.addHistory(entry)); + if (entry.image_url) { + createHistoryThumbnail(entry.image_url).then(thumb => { + if (!thumb) return; + entry.thumb_url = thumb; + const imgEl = document.querySelector(`[data-history-id="${entry.id}"] img`); + if (imgEl) imgEl.src = thumb; + queueHistoryWrite(() => StudioStorage.addHistory(entry)); + }); + } else { + queueHistoryWrite(() => StudioStorage.addHistory(entry)); + } + } + + let thumbBackfillRunning = false; + function backfillMissingThumbnails() { + if (thumbBackfillRunning) return; + const missing = runHistory.filter(item => item.image_url && !item.thumb_url); + if (!missing.length) return; + thumbBackfillRunning = true; + (async () => { + for (const item of missing) { + const thumb = await createHistoryThumbnail(item.image_url); + if (thumb) { + item.thumb_url = thumb; + const imgEl = document.querySelector(`[data-history-id="${item.id}"] img`); + if (imgEl) imgEl.src = thumb; + queueHistoryWrite(() => StudioStorage.addHistory(item)); + } + await new Promise(r => setTimeout(r, 20)); + } + thumbBackfillRunning = false; + })(); } function renderRunHistory() { @@ -3224,12 +3283,18 @@

} runHistory.forEach((item, idx) => { const row = document.createElement('div'); + row.dataset.historyId = item.id || ''; + row.style.contain = 'layout style paint'; row.className = 'p-2.5 rounded-xl bg-slate-900 border border-slate-800 hover:border-indigo-500/60 cursor-pointer transition flex items-center gap-2.5'; row.addEventListener('click', () => restoreHistoryItem(idx)); - if (item.image_url) { + if (item.image_url || item.thumb_url) { const preview = document.createElement('img'); - preview.src = item.image_url; + preview.decoding = 'async'; + preview.loading = 'lazy'; + preview.width = 44; + preview.height = 44; + preview.src = item.thumb_url || item.image_url; preview.alt = 'Map preview'; preview.className = 'w-11 h-11 rounded-lg object-cover border border-slate-700/80 shrink-0 bg-slate-950'; row.appendChild(preview); @@ -3238,22 +3303,24 @@

const details = document.createElement('div'); details.className = 'min-w-0 flex-1 flex flex-col justify-between gap-1'; const metadata = document.createElement('div'); - metadata.className = 'flex items-center justify-between text-[11px]'; - const mode = document.createElement('span'); - mode.className = 'font-mono text-indigo-400 font-semibold'; - mode.textContent = `${item.state.map_type} / ${item.state.mode}`; + metadata.className = 'flex items-center justify-between gap-2 text-[11px]'; + const topicEl = document.createElement('span'); + topicEl.className = 'text-indigo-300 font-semibold truncate'; + topicEl.textContent = (item.state?.topic || '').trim() || 'Untitled map'; const time = document.createElement('span'); - time.className = 'text-slate-500'; + time.className = 'text-slate-500 shrink-0'; time.textContent = item.time; - metadata.append(mode, time); + metadata.append(topicEl, time); - const command = document.createElement('div'); - command.className = 'text-[11px] font-mono text-slate-400 truncate'; - command.textContent = item.cmd; - details.append(metadata, command); + const modeLine = document.createElement('div'); + modeLine.className = 'text-[11px] font-mono text-slate-400 truncate'; + const mapLabel = String(item.state?.map_type || 'default').replace(/_/g, ' '); + modeLine.textContent = `${mapLabel} / ${item.state?.mode || 'text'}`; + details.append(metadata, modeLine); row.appendChild(details); list.appendChild(row); }); + backfillMissingThumbnails(); } function restoreHistoryItem(index) { diff --git a/templates/video.html b/templates/video.html index a4b5466..d42789a 100644 --- a/templates/video.html +++ b/templates/video.html @@ -870,6 +870,74 @@

Frame Com Smooth intro fade-in from black (0.0s → 0.8s) + +
@@ -1363,6 +1431,8 @@

const VIDEO_SETTING_IDS = ['musicUrlInput', 'musicCookiesInput', 'cutStartInput', 'cutDurationInput', 'videoTitleInput', 'titleFontSelect', 'titleFontSize', 'titleFirstLineColor', 'titleOtherLinesColor', 'titleUppercase', 'visualEffects', 'introFadeToggle', + 'mapZoomToggle', 'mapZoomX', 'mapZoomY', 'mapZoomCountry', 'mapZoomCountryKey', + 'mapZoomScale', 'mapZoomStart', 'mapZoomDuration', 'mapZoomOutToggle', 'mapZoomOutDuration', 'revealCountryToggle', 'revealTimeInput', 'topLeftStickerSelect', 'topRightStickerSelect', 'subscribeBadgeToggle', 'subscribeTextInput', 'subscribeDelayInput', 'watermarkTextInput', 'watermarkFontSelect', 'watermarkColor', 'watermarkStarsToggle', 'codecSelect']; @@ -1414,6 +1484,17 @@

input.value = input.maxLength > 0 ? normalized.slice(0, input.maxLength) : normalized; } }); + if (typeof saved.mapZoomCountryKey !== 'string') { + const savedCountry = (document.getElementById('mapZoomCountry')?.value || '').trim(); + const keyEl = document.getElementById('mapZoomCountryKey'); + if (keyEl) { + keyEl.value = (!savedCountry || savedCountry.toLowerCase() === 'custom point') + ? '' + : savedCountry.toLowerCase().replace(/\s+/g, '_'); + } + } + updateMapZoomUI(); + updateRevealUI(); } } catch (error) { // Invalid or unavailable saved settings should not prevent opening the studio. @@ -1444,13 +1525,15 @@

// A newer generated map wins. A manually selected or removed map // remains the user's choice until another map is generated. const map = latest && (!selected || latest.updatedAt > selected.updatedAt) ? latest : selected; + const isNewGeneratedMap = !!(map && map === latest); if (map?.file && materialVersions.mapFileInput === 0) { - const file = map === latest ? await prepareGeneratedMap(map.file) : map.file; + const file = isNewGeneratedMap ? await prepareGeneratedMap(map.file) : map.file; if (materialVersions.mapFileInput === 0) { - acceptFile('mapFileInput', file, map === latest, map.topic); - if (renderFiles.mapFileInput === file && !manualVideoTitle && typeof map.topic === 'string' && map.topic.trim()) { + acceptFile('mapFileInput', file, isNewGeneratedMap, map.topic); + if (renderFiles.mapFileInput === file && (isNewGeneratedMap || !manualVideoTitle) && typeof map.topic === 'string' && map.topic.trim()) { const title = document.getElementById('videoTitleInput'); title.value = map.topic.trim().slice(0, title.maxLength); + manualVideoTitle = false; updateStageTitlePreview(title.value); saveVideoSettings(); } @@ -2157,6 +2240,17 @@

title_uppercase: document.getElementById('titleUppercase').checked, visual_effects: document.getElementById('visualEffects').checked, intro_fade: document.getElementById('introFadeToggle').checked, + zoom_enabled: document.getElementById('mapZoomToggle').checked, + zoom_x: Number(document.getElementById('mapZoomX').value || 0.80), + zoom_y: Number(document.getElementById('mapZoomY').value || 0.35), + zoom_country_key: (document.getElementById('mapZoomCountryKey')?.value || '').trim(), + zoom_scale: Number(document.getElementById('mapZoomScale').value || 2.0), + zoom_start: Number(document.getElementById('mapZoomStart').value || 1.5), + zoom_duration: Number(document.getElementById('mapZoomDuration').value || 2.5), + zoom_out_enabled: !!document.getElementById('mapZoomOutToggle')?.checked, + zoom_out_duration: Number(document.getElementById('mapZoomOutDuration')?.value || 2.0), + reveal_enabled: !!document.getElementById('revealCountryToggle')?.checked, + reveal_time: Number(document.getElementById('revealTimeInput')?.value || 5.5), top_left_sticker: document.getElementById('topLeftStickerSelect').value, top_right_sticker: document.getElementById('topRightStickerSelect').value, subscribe_badge: document.getElementById('subscribeBadgeToggle').checked, @@ -2165,6 +2259,176 @@

}; } + let zoomCountriesCache = null; + + async function loadZoomCountries() { + if (zoomCountriesCache) return zoomCountriesCache; + try { + const resp = await fetch('/api/zoom_countries'); + if (resp.ok) zoomCountriesCache = await resp.json(); + } catch { + // Fall back to direct click coordinates if country index fails to load. + } + return zoomCountriesCache; + } + + function updateZoomOutUI() { + const enabled = !!document.getElementById('mapZoomOutToggle')?.checked; + const input = document.getElementById('mapZoomOutDuration'); + const wrap = document.getElementById('mapZoomOutDurationWrap'); + if (input) input.disabled = !enabled; + if (wrap) wrap.classList.toggle('opacity-50', !enabled); + } + + function updateRevealUI() { + const enabled = !!document.getElementById('revealCountryToggle')?.checked; + const panel = document.getElementById('revealControlsPanel'); + if (panel) panel.classList.toggle('hidden', !enabled); + } + + function updateMapZoomUI() { + const enabled = !!document.getElementById('mapZoomToggle')?.checked; + const panel = document.getElementById('mapZoomPanel'); + if (panel) panel.classList.toggle('hidden', !enabled); + if (enabled) loadZoomCountries(); + updateZoomOutUI(); + updateRevealUI(); + const pin = document.getElementById('zoomPickerPin'); + const rawX = parseFloat(document.getElementById('mapZoomX')?.value); + const rawY = parseFloat(document.getElementById('mapZoomY')?.value); + const zx = Math.max(0, Math.min(1, Number.isFinite(rawX) ? rawX : 0.807)); + const zy = Math.max(0, Math.min(1, Number.isFinite(rawY) ? rawY : 0.358)); + if (pin) { + pin.style.left = `${(zx * 100).toFixed(1)}%`; + pin.style.top = `${(zy * 100).toFixed(1)}%`; + } + const countryName = (document.getElementById('mapZoomCountry')?.value || '').trim(); + const labelEl = document.getElementById('zoomTargetCountry'); + if (labelEl) { + const coordsText = `(${Math.round(zx * 100)}%, ${Math.round(zy * 100)}%)`; + labelEl.textContent = countryName ? `${countryName} ${coordsText}` : coordsText; + } + } + + function setZoomTarget(x, y, countryName = '', countryKey = '') { + document.getElementById('mapZoomX').value = Number(x).toFixed(4); + document.getElementById('mapZoomY').value = Number(y).toFixed(4); + const countryEl = document.getElementById('mapZoomCountry'); + if (countryEl) countryEl.value = countryName; + const keyEl = document.getElementById('mapZoomCountryKey'); + if (keyEl) { + const normalizedName = (countryName || '').trim().toLowerCase(); + keyEl.value = countryKey || (normalizedName === 'russia' ? 'russia' : ''); + } + updateMapZoomUI(); + saveVideoSettings(); + } + + let lastZoomPointerPos = null; + + function resolveZoomTargetFromEvent(event) { + const img = document.getElementById('zoomPickerImg'); + if (!img || img.classList.contains('hidden')) return null; + const rect = img.getBoundingClientRect(); + if (!rect.width || !rect.height) return null; + const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)); + const y = Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)); + const aspect = (img.naturalWidth && img.naturalHeight) ? (img.naturalWidth / img.naturalHeight) : 1.0; + const mapKind = aspect < 1.25 ? 'europe' : 'world'; + + if (event.ctrlKey) { + return { x, y, name: 'Custom point', key: '', mapKind }; + } + + const data = zoomCountriesCache; + const list = data ? data[mapKind] : null; + if (Array.isArray(list) && list.length) { + let best = null; + let bestDist = Infinity; + for (const c of list) { + const dx = c.x - x; + const dy = c.y - y; + const dist = dx * dx + dy * dy; + if (dist < bestDist) { + bestDist = dist; + best = c; + } + } + if (best && bestDist <= 0.18 * 0.18) { + const resolvedKey = best.key || ((best.name || '').trim().toLowerCase() === 'russia' ? 'russia' : ''); + return { x: best.x, y: best.y, name: best.name, key: resolvedKey, mapKind }; + } + } + return { x, y, name: '', key: '', mapKind }; + } + + let lastHoverOutlineKey = ''; + function hoverZoomPoint(event) { + lastZoomPointerPos = { clientX: event.clientX, clientY: event.clientY }; + if (!zoomCountriesCache) { + loadZoomCountries().then(data => { + if (data && lastZoomPointerPos) hoverZoomPoint({ ...lastZoomPointerPos, ctrlKey: !!event.ctrlKey }); + }); + } + const target = resolveZoomTargetFromEvent(event); + const hoverPin = document.getElementById('zoomHoverPin'); + const hoverLabel = document.getElementById('zoomHoverLabel'); + const hoverOutline = document.getElementById('zoomHoverOutline'); + if (!target || !hoverPin || !hoverLabel) return; + const leftPct = `${(target.x * 100).toFixed(1)}%`; + const topPct = `${(target.y * 100).toFixed(1)}%`; + hoverPin.classList.toggle('transition-all', !event.ctrlKey); + hoverPin.classList.toggle('duration-75', !event.ctrlKey); + hoverPin.style.left = leftPct; + hoverPin.style.top = topPct; + hoverPin.classList.remove('hidden'); + + if (hoverOutline) { + if (target.key) { + const outlineKey = `${target.mapKind}:${target.key}`; + if (outlineKey !== lastHoverOutlineKey) { + lastHoverOutlineKey = outlineKey; + hoverOutline.src = `/api/zoom_country_outline?map=${encodeURIComponent(target.mapKind)}&key=${encodeURIComponent(target.key)}`; + } + hoverOutline.classList.remove('hidden'); + } else { + lastHoverOutlineKey = ''; + hoverOutline.classList.add('hidden'); + } + } + + if (target.name) { + hoverLabel.textContent = target.name; + hoverLabel.style.left = `${Math.max(14, Math.min(86, target.x * 100)).toFixed(1)}%`; + hoverLabel.style.top = `${Math.max(14, target.y * 100).toFixed(1)}%`; + hoverLabel.classList.remove('hidden'); + } else { + hoverLabel.classList.add('hidden'); + } + } + + function clearZoomHover() { + lastZoomPointerPos = null; + lastHoverOutlineKey = ''; + document.getElementById('zoomHoverPin')?.classList.add('hidden'); + document.getElementById('zoomHoverLabel')?.classList.add('hidden'); + document.getElementById('zoomHoverOutline')?.classList.add('hidden'); + } + + function pickZoomPoint(event) { + const target = resolveZoomTargetFromEvent(event); + if (!target) return; + setZoomTarget(target.x, target.y, target.name, target.key || ''); + } + + for (const evtName of ['keydown', 'keyup']) { + window.addEventListener(evtName, e => { + if (e.key === 'Control' && lastZoomPointerPos) { + hoverZoomPoint({ ...lastZoomPointerPos, ctrlKey: e.ctrlKey }); + } + }); + } + function fitStageMap() { const map = document.getElementById('stageMapPreview'); const area = document.getElementById('stageMapArea'); @@ -3367,8 +3631,15 @@

materialPreviewUrls[inputId] = file ? URL.createObjectURL(file) : null; if (inputId === 'mapFileInput') { + const zoomImg = document.getElementById('zoomPickerImg'); + const zoomPlaceholder = document.getElementById('zoomPickerPlaceholder'); if (file) { const url = materialPreviewUrls[inputId]; + if (zoomImg) { + zoomImg.src = url; + zoomImg.classList.remove('hidden'); + } + if (zoomPlaceholder) zoomPlaceholder.classList.add('hidden'); if (stageMap) { stageMap.onload = fitStageMap; stageMap.src = url; @@ -3380,6 +3651,11 @@

mapThumbIcon.classList.add('hidden'); } } else { + if (zoomImg) { + zoomImg.removeAttribute('src'); + zoomImg.classList.add('hidden'); + } + if (zoomPlaceholder) zoomPlaceholder.classList.remove('hidden'); if (stageMap) { stageMap.src = ''; stageMap.classList.add('hidden'); diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index f03ad5e..44df091 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -16,6 +16,7 @@ import importlib import io import logging +import math import os import re import shutil @@ -530,6 +531,309 @@ def video_title_preview(): return send_file(output, mimetype='image/png') +def _parse_finite_float(value: object, default: float) -> float: + """Parse a finite float from JSON input, returning ``default`` on missing or invalid values.""" + if value is None or value == '' or isinstance(value, bool): + return default + try: + parsed = float(value) # type: ignore[arg-type] + except (TypeError, ValueError): + return default + return parsed if math.isfinite(parsed) else default + + +def _decode_reveal_mask(raw_mask: object, box_w: int, box_h: int): + """Decode a base64 or data-URL L-mode PNG mask resized to ``(box_w, box_h)``, or return None.""" + if not isinstance(raw_mask, str) or not raw_mask.strip(): + return None + import numpy as np + from PIL import Image, UnidentifiedImageError + + value = raw_mask.strip() + if value.startswith('data:'): + header, sep, value = value.partition(',') + if not sep or ';base64' not in header.lower(): + return None + b64_part = ''.join(value.split()) + if not b64_part or len(b64_part) > 4 * ((MAX_MATERIAL_BYTES + 2) // 3): + return None + try: + raw_bytes = base64.b64decode(b64_part, validate=True) + except (ValueError, TypeError): + return None + if not raw_bytes or len(raw_bytes) > MAX_MATERIAL_BYTES: + return None + try: + with Image.open(io.BytesIO(raw_bytes)) as mask_img: + if mask_img.width * mask_img.height > 20_000_000: + return None + mask_resized = mask_img.convert('L').resize( + (box_w, box_h), + Image.Resampling.BILINEAR, + ) + mask_arr = np.array(mask_resized, dtype=np.float32) / 255.0 + except (UnidentifiedImageError, OSError, Image.DecompressionBombError, ValueError): + return None + if not np.any(mask_arr > 0.0): + return None + return mask_arr[..., None] + + +def _render_reveal_dot_overlays( + box_w: int, + box_h: int, + cx: float, + cy: float, +) -> dict[int, tuple[int, int, int, int, object]]: + """Pre-render 1-, 2-, and 3-dot RGBA overlays centered at ``(cx, cy)`` using 4x supersampling.""" + import numpy as np + from PIL import Image, ImageDraw + + base_dim = min(box_w, box_h) + dot_r = max(6.0, min(10.5, base_dim * 0.011)) + outline_w = max(2.0, dot_r * 0.34) + outer_r = dot_r + outline_w + spacing = dot_r * 3.0 + + pad = int(math.ceil(outer_r)) + 4 + x0 = max(0, int(math.floor(cx - spacing - pad))) + x1 = min(box_w, int(math.ceil(cx + spacing + pad))) + y0 = max(0, int(math.floor(cy - pad))) + y1 = min(box_h, int(math.ceil(cy + pad))) + patch_w = max(1, x1 - x0) + patch_h = max(1, y1 - y0) + + ss = 4 + overlays: dict[int, tuple[int, int, int, int, object]] = {} + for count in (1, 2, 3): + hi_img = Image.new('RGBA', (patch_w * ss, patch_h * ss), (0, 0, 0, 0)) + draw = ImageDraw.Draw(hi_img) + for idx in range(count): + dot_x = (cx + (idx - 1) * spacing - x0) * ss + dot_y = (cy - y0) * ss + ro = outer_r * ss + ri = dot_r * ss + draw.ellipse( + (dot_x - ro, dot_y - ro, dot_x + ro, dot_y + ro), + fill=(10, 12, 20, 255), + ) + draw.ellipse( + (dot_x - ri, dot_y - ri, dot_x + ri, dot_y + ri), + fill=(255, 255, 255, 255), + ) + patch = hi_img.resize((patch_w, patch_h), Image.Resampling.LANCZOS) + overlays[count] = (y0, y1, x0, x1, np.array(patch, dtype=np.uint8)) + return overlays + + +def _alpha_composite_patch(base_rgba, y0: int, y1: int, x0: int, x1: int, patch_rgba): + """Return a copy of ``base_rgba`` with ``patch_rgba`` alpha-composited into ``[y0:y1, x0:x1]``.""" + import numpy as np + + out = base_rgba.copy() + bg = out[y0:y1, x0:x1].astype(np.float32) + fg = patch_rgba.astype(np.float32) + fg_a = fg[:, :, 3:4] / 255.0 + bg_a = bg[:, :, 3:4] / 255.0 + out_a = fg_a + bg_a * (1.0 - fg_a) + safe_a = np.maximum(out_a, 1e-6) + out_rgb = (fg[:, :, :3] * fg_a + bg[:, :, :3] * bg_a * (1.0 - fg_a)) / safe_a + out[y0:y1, x0:x1, :3] = np.clip(np.rint(out_rgb), 0, 255).astype(np.uint8) + out[y0:y1, x0:x1, 3:4] = np.clip(np.rint(out_a * 255.0), 0, 255).astype(np.uint8) + return out + + +def _compute_reveal_time( + zoom_enabled: bool, + zoom_start: float, + zoom_duration: float, + reveal_time_raw: object, +) -> float: + """Resolve the effective reveal trigger timestamp (after zoom ends when zoom is enabled).""" + z_start = zoom_start if zoom_enabled else 1.5 + zoom_end = (z_start + zoom_duration) if zoom_enabled else 0.0 + default_reveal = (zoom_end + 0.8) if zoom_enabled else 2.5 + raw_r_time = _parse_finite_float(reveal_time_raw, default_reveal) + if zoom_enabled: + return max(zoom_end + 0.5, raw_r_time) + return max(0.2, raw_r_time) + + +def _apply_reveal_impact_fx(clip, reveal_time: float, canvas_w: int, canvas_h: int): + """Apply a brief camera-shake + RGB chromatic glitch + impact punch when dots vanish.""" + import numpy as np + from PIL import Image + + impact_dur = 0.60 + + def _impact_frame(get_frame, t: float) -> np.ndarray: + frame = get_frame(t) + dt = float(t) - reveal_time + if dt < 0.0 or dt >= impact_dur: + return frame + + env = math.exp(-dt * 5.8) * max(0.0, 1.0 - dt / impact_dur) + punch = 1.0 + 0.042 * env + inv_p = 1.0 / punch + cw = canvas_w * inv_p + ch = canvas_h * inv_p + margin_x = (canvas_w - cw) * 0.5 + margin_y = (canvas_h - ch) * 0.5 + shake_x = env * 22.0 * math.sin(dt * 85.0) + env * 8.0 * math.cos(dt * 145.0) + shake_y = env * 18.0 * math.cos(dt * 78.0) - env * 6.0 * math.sin(dt * 130.0) + x0 = max(0.0, min(canvas_w - cw, margin_x + shake_x)) + y0 = max(0.0, min(canvas_h - ch, margin_y + shake_y)) + + punched = Image.fromarray(frame).transform( + (canvas_w, canvas_h), + Image.Transform.AFFINE, + (inv_p, 0.0, x0, 0.0, inv_p, y0), + resample=Image.Resampling.BILINEAR, + ) + out = np.array(punched, dtype=np.uint8, copy=True) + + if dt < 0.38: + glitch_env = math.exp(-dt * 7.5) + ca_shift = int(round(10.0 * glitch_env * (1.0 if math.sin(dt * 105.0) >= 0 else -1.0))) + if ca_shift > 0 and ca_shift < canvas_w: + src = out.copy() + out[:, ca_shift:, 0] = src[:, :-ca_shift, 0] + out[:, :-ca_shift, 2] = src[:, ca_shift:, 2] + elif ca_shift < 0 and (-ca_shift) < canvas_w: + s = -ca_shift + src = out.copy() + out[:, :-s, 0] = src[:, s:, 0] + out[:, s:, 2] = src[:, :-s, 2] + + if glitch_env > 0.20: + step = int(dt * 50.0) + band_h = max(8, canvas_h // 65) + dx = max(4, int(round(18.0 * glitch_env))) + for b_idx, frac in enumerate((0.38, 0.56)): + by0 = min( + canvas_h - band_h, + max(0, int(canvas_h * frac) + ((step * 53 + b_idx * 97) % 140) - 70), + ) + by1 = min(canvas_h, by0 + band_h) + shift_px = dx if ((step + b_idx) % 2 == 0) else -dx + out[by0:by1] = np.roll(out[by0:by1], shift_px, axis=1) + + if dt < 0.14: + boost = int(round(18.0 * (1.0 - dt / 0.14))) + if boost > 0: + out = np.clip(out.astype(np.int16) + boost, 0, 255).astype(np.uint8) + return out + + return clip.transform(_impact_frame) + + +def _build_reveal_map_clip( + map_path: str, + mask_f, + box_w: int, + box_h: int, + bg_duration: float, + effects: bool, + zoom_enabled: bool, + zoom_x: float, + zoom_y: float, + zoom_start: float, + zoom_duration: float, + reveal_time_raw: object, +): + """Build a dynamic RGB + mask ``VideoClip`` for the country reveal animation.""" + import numpy as np + from moviepy import VideoClip + from PIL import Image, ImageFilter + + with Image.open(map_path) as raw_map: + base_pil = raw_map.convert('RGBA').resize((box_w, box_h), Image.Resampling.LANCZOS) + base_rgba = np.array(base_pil, dtype=np.uint8) + + map_visible = (base_rgba[:, :, 3:4] > 0).astype(np.float32) + eff_mask = mask_f * map_visible + black_pixel = np.array([14.0, 14.0, 22.0, 255.0], dtype=np.float32).reshape(1, 1, 4) + base_f = base_rgba.astype(np.float32) + black_f = base_f * (1.0 - eff_mask) + black_pixel * eff_mask + delta_f = black_f - base_f + black_rgba = np.clip(np.rint(black_f), 0, 255).astype(np.uint8) + + shadow_only = None + if effects: + alpha_chan = Image.new('L', (box_w + 48, box_h + 48)) + alpha_chan.paste(base_pil.getchannel('A'), (24, 32)) + shadow_only = Image.new('RGBA', (box_w + 48, box_h + 48), (0, 0, 0, 0)) + shadow_only.putalpha( + alpha_chan.filter(ImageFilter.GaussianBlur(10)).point(lambda p: round(p * 0.8)) + ) + + def _to_rgb_and_mask(frame_rgba) -> tuple[object, object]: + if shadow_only is not None: + canvas = shadow_only.copy() + canvas.alpha_composite(Image.fromarray(frame_rgba), (24, 24)) + composed = np.asarray(canvas, dtype=np.uint8) + else: + composed = frame_rgba + rgb = np.ascontiguousarray(composed[:, :, :3]) + mask = np.ascontiguousarray(composed[:, :, 3], dtype=np.float32) / 255.0 + return rgb, mask + + z_start = zoom_start if zoom_enabled else 1.5 + r_time = _compute_reveal_time(zoom_enabled, zoom_start, zoom_duration, reveal_time_raw) + fade_dur = 0.25 + phase_end = z_start if (zoom_enabled and z_start > 0.2) else min(1.5, r_time * 0.6) + + dot_cx = zoom_x * box_w + dot_cy = zoom_y * box_h + mask_2d = eff_mask[:, :, 0] > 0.5 + ys, xs = np.nonzero(mask_2d) + if ys.size > 0: + dot_cx = float(xs.mean()) + dot_cy = float(ys.mean()) + ix = max(0, min(box_w - 1, int(round(dot_cx)))) + iy = max(0, min(box_h - 1, int(round(dot_cy)))) + if not mask_2d[iy, ix]: + d2 = (xs.astype(np.float32) - dot_cx) ** 2 + (ys.astype(np.float32) - dot_cy) ** 2 + best = int(np.argmin(d2)) + dot_cx = float(xs[best]) + dot_cy = float(ys[best]) + + dot_overlays = _render_reveal_dot_overlays(box_w, box_h, dot_cx, dot_cy) + dot_frames = { + count: _to_rgb_and_mask(_alpha_composite_patch(black_rgba, *dot_overlays[count])) + for count in (1, 2, 3) + } + final_frame = _to_rgb_and_mask(base_rgba) + + frame_cache: list[tuple[float, object, object] | None] = [None] + + def _get_cached_frame(t: float) -> tuple[object, object]: + t_key = float(t) + cached = frame_cache[0] + if cached is not None and cached[0] == t_key: + return cached[1], cached[2] + if t_key < r_time: + if t_key < phase_end * 0.33: + count = 1 + elif t_key < phase_end * 0.66: + count = 2 + else: + count = 3 + rgb, mask = dot_frames[count] + elif t_key >= r_time + fade_dur: + rgb, mask = final_frame + else: + fade_alpha = max(0.0, min(1.0, 1.0 - (t_key - r_time) / fade_dur)) + blended_rgba = np.clip(np.rint(base_f + fade_alpha * delta_f), 0, 255).astype(np.uint8) + rgb, mask = _to_rgb_and_mask(blended_rgba) + frame_cache[0] = (t_key, rgb, mask) + return rgb, mask + + rgb_clip = VideoClip(lambda t: _get_cached_frame(t)[0], duration=bg_duration) + mask_clip = VideoClip(lambda t: _get_cached_frame(t)[1], is_mask=True, duration=bg_duration) + return rgb_clip.with_mask(mask_clip) + + @app.route('/api/render_video', methods=['POST']) @app.route('/api/render_video/', methods=['POST']) @render_progress.track @@ -777,13 +1081,68 @@ def _decode_optional_image(field: str, label: str): if map_clip.w >= map_clip.h: scale = max(canvas_w / map_clip.w, scale) map_clip = map_clip.resized(scale) - map_y = map_top + (map_area_height - map_clip.h) / 2 - if effects: - map_image = Image.open(map_path).convert('RGBA').resize((map_clip.w, map_clip.h)) + box_w, box_h = int(map_clip.w), int(map_clip.h) + map_y = map_top + (map_area_height - box_h) / 2 + map_x = (canvas_w - box_w) / 2.0 + + zoom_enabled = bool(data.get('zoom_enabled', False)) + zoom_x = max(0.0, min(1.0, _parse_finite_float(data.get('zoom_x'), 0.80))) + zoom_y = max(0.0, min(1.0, _parse_finite_float(data.get('zoom_y'), 0.35))) + zoom_scale = max(1.1, min(4.0, _parse_finite_float(data.get('zoom_scale'), 2.0))) + zoom_start = max(0.0, _parse_finite_float(data.get('zoom_start'), 1.5)) + zoom_duration = max(0.2, _parse_finite_float(data.get('zoom_duration'), 2.5)) + zoom_out_enabled = bool(data.get('zoom_out_enabled', False)) + zoom_out_duration = max(0.0, _parse_finite_float(data.get('zoom_out_duration'), 2.0)) + + reveal_enabled = bool(data.get('reveal_enabled', False)) + reveal_mask_f = ( + _decode_reveal_mask(data.get('reveal_mask'), box_w, box_h) + if reveal_enabled + else None + ) + reveal_active = reveal_enabled and reveal_mask_f is not None + + if reveal_active: + map_clip = _build_reveal_map_clip( + map_path, + reveal_mask_f, + box_w, + box_h, + bg_duration, + effects, + zoom_enabled, + zoom_x, + zoom_y, + zoom_start, + zoom_duration, + data.get('reveal_time'), + ) + if effects: + map_y -= 24 + elif effects: + with Image.open(map_path) as raw_map: + map_image = raw_map.convert('RGBA').resize((box_w, box_h)) map_clip = ImageClip(np.array(_with_shadow(map_image))).with_duration(bg_duration) map_y -= 24 + title_clip = title_clip.with_position(("center", title_top)) map_clip = map_clip.with_position(("center", map_y)) + if reveal_active: + dynamic_layers.add(id(map_clip)) + + zoom_params = None + if zoom_enabled: + target_cx = map_x + zoom_x * box_w + target_cy = (map_y + (24 if effects else 0)) + zoom_y * box_h + zoom_params = ( + target_cx, + target_cy, + zoom_scale, + zoom_start, + zoom_duration, + zoom_out_enabled, + zoom_out_duration, + ) clips = [background_video, scrim, map_clip, title_clip] if left_sticker_arr is not None: @@ -858,10 +1217,12 @@ def _veil_mask(t: float) -> np.ndarray: media_resources.append(audio_clip) render_duration = min(bg_duration, audio_clip.duration or bg_duration) - # Prefer the native Rust compositor when available; fall back to MoviePy locally. + # Prefer the native Rust compositor when available; fall back to MoviePy for dynamic map zoom or reveal. used_rust = False # ======== RUST ENGINE INJECTION ============= try: # pragma: no cover + if zoom_enabled or reveal_enabled: + raise ImportError("Camera zoom and country reveal use MoviePy compositor") automap_rs = _load_automap_rs() def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: @@ -945,6 +1306,57 @@ def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: if not used_rust: # pragma: no branch final_clip = CompositeVideoClip(clips, size=(canvas_w, canvas_h)) media_resources.append(final_clip) + if zoom_params is not None: + target_cx, target_cy, z_scale, z_start, z_dur, z_out_enabled, z_out_dur = zoom_params + final_cw = canvas_w / z_scale + final_ch = canvas_h / z_scale + final_x0 = max(0.0, min(canvas_w - final_cw, target_cx - final_cw / 2.0)) + final_y0 = max(0.0, min(canvas_h - final_ch, target_cy - final_ch / 2.0)) + zoom_total_dur = render_duration if has_audio else bg_duration + + def _zoom_full_frame(get_frame, t: float) -> np.ndarray: + frame = get_frame(t) + if t <= z_start: + return frame + if t < z_start + z_dur: + u = (t - z_start) / z_dur + # Quintic smootherstep for silky-smooth camera acceleration/deceleration. + ease = u * u * u * (u * (u * 6.0 - 15.0) + 10.0) + elif z_out_enabled and z_out_dur > 0.0 and zoom_total_dur > (z_start + z_dur + 0.05): + out_start = max(z_start + z_dur, zoom_total_dur - z_out_dur) + out_dur = max(0.05, zoom_total_dur - out_start) + if t >= zoom_total_dur: + ease = 0.0 + elif t > out_start: + u = (t - out_start) / out_dur + ease = 1.0 - (u * u * u * (u * (u * 6.0 - 15.0) + 10.0)) + else: + ease = 1.0 + else: + ease = 1.0 + if ease <= 0.0: + return frame + cw = canvas_w + (final_cw - canvas_w) * ease + ch = canvas_h + (final_ch - canvas_h) * ease + x0 = final_x0 * ease + y0 = final_y0 * ease + inv_z = cw / canvas_w + zoomed = Image.fromarray(frame).transform( + (canvas_w, canvas_h), + Image.Transform.AFFINE, + (inv_z, 0.0, x0, 0.0, inv_z, y0), + resample=Image.Resampling.BILINEAR, + ) + return np.asarray(zoomed, dtype=np.uint8) + + final_clip = final_clip.transform(_zoom_full_frame) + media_resources.append(final_clip) + if reveal_active: + r_trigger = _compute_reveal_time( + zoom_enabled, zoom_start, zoom_duration, data.get('reveal_time') + ) + final_clip = _apply_reveal_impact_fx(final_clip, r_trigger, canvas_w, canvas_h) + media_resources.append(final_clip) if has_audio: final_clip = final_clip.with_audio(audio_clip.subclipped(0, render_duration)) final_clip = final_clip.with_duration(render_duration) From 1a213f9e8797c7a64c67b80237182ebbf97d9af4 Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 18:03:17 +0200 Subject: [PATCH 07/14] Surface Rust fallback warnings in web API responses and UI --- main.py | 2 ++ map/auto_map.py | 41 +++++++++++++++++++++++------------------ templates/index.html | 4 ++++ templates/video.html | 7 ++++++- yt-dlp_serv.py | 17 +++++++++++------ 5 files changed, 46 insertions(+), 25 deletions(-) diff --git a/main.py b/main.py index df0d82e..e45947f 100644 --- a/main.py +++ b/main.py @@ -708,6 +708,8 @@ def generate(): "ai_cached": ai_cache_hit, } render_meta = getattr(buffer, "map_meta", None) + if isinstance(render_meta, dict) and render_meta.get("rust_warning"): + resp_payload["warning"] = render_meta["rust_warning"] ai_vals = render_meta.get("ai_answer") if isinstance(render_meta, dict) else None if isinstance(ai_vals, dict) and ai_vals: resp_payload["map_values"] = render_meta.get("raw_ai_answer", ai_vals) diff --git a/map/auto_map.py b/map/auto_map.py index 85f3e61..de2edf9 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -212,28 +212,36 @@ def _region_index(map_path: Path, base: Image.Image, coords: dict) -> tuple[np.n _RUST_WARNED = False +_LAST_RUST_WARNING: str | None = None + + +def _record_rust_warning(msg: str) -> None: + global _RUST_WARNED, _LAST_RUST_WARNING + _LAST_RUST_WARNING = msg + if not _RUST_WARNED: + _RUST_WARNED = True + log.warning(msg) + logging.warning(msg) def _get_automap_rs(): """Return the native ``automap_rs`` module when available, else ``None``.""" - global _RUST_WARNED + global _LAST_RUST_WARNING try: import automap_rs if hasattr(automap_rs, "paint_regions_rs") and hasattr(automap_rs, "alpha_composite_rs"): + _LAST_RUST_WARNING = None return automap_rs raise ImportError("automap_rs map functions not built") except Exception as exc: - if not _RUST_WARNED: - _RUST_WARNED = True - msg = f"Rust map acceleration unavailable ({type(exc).__name__}: {exc}); falling back to Python/PIL." - log.warning(msg) - logging.warning(msg) + _record_rust_warning( + f"Rust map acceleration unavailable ({type(exc).__name__}: {exc}); falling back to Python/PIL." + ) return None def _alpha_composite(base: Image.Image, overlay: Image.Image) -> Image.Image: """Alpha-composite ``overlay`` over ``base`` using Rust when available.""" - global _RUST_WARNED rs = _get_automap_rs() if rs is not None and base.size == overlay.size: try: @@ -242,18 +250,15 @@ def _alpha_composite(base: Image.Image, overlay: Image.Image) -> Image.Image: out_bytes = rs.alpha_composite_rs(base_rgba.tobytes(), overlay_rgba.tobytes()) return Image.frombytes("RGBA", base.size, out_bytes) except Exception as exc: - if not _RUST_WARNED: - _RUST_WARNED = True - msg = f"Rust alpha_composite_rs failed ({type(exc).__name__}: {exc}); falling back to PIL." - log.warning(msg) - logging.warning(msg) + _record_rust_warning( + f"Rust alpha_composite_rs failed ({type(exc).__name__}: {exc}); falling back to PIL." + ) return Image.alpha_composite(base, overlay) def _paint_regions(img: Image.Image, flat: np.ndarray, ids: np.ndarray, colors: dict[int, tuple[int, int, int, int]]) -> Image.Image: """Return a copy of ``img`` with region ``i`` painted ``colors[i]``.""" - global _RUST_WARNED if not colors: return img.copy() n = int(max(colors)) + 1 @@ -277,11 +282,9 @@ def _paint_regions(img: Image.Image, flat: np.ndarray, ids: np.ndarray, ) return Image.frombytes("RGBA", img.size, out_bytes) except Exception as exc: - if not _RUST_WARNED: - _RUST_WARNED = True - msg = f"Rust paint_regions_rs failed ({type(exc).__name__}: {exc}); falling back to NumPy." - log.warning(msg) - logging.warning(msg) + _record_rust_warning( + f"Rust paint_regions_rs failed ({type(exc).__name__}: {exc}); falling back to NumPy." + ) arr = np.array(img, dtype=np.uint8) pix = arr.reshape(-1, 4) sel = use.astype(bool, copy=False)[ids] @@ -1319,6 +1322,8 @@ def _report(stage: int, label: str) -> None: _report(4, "Encoding final PNG...") + if _LAST_RUST_WARNING: + render_meta["rust_warning"] = _LAST_RUST_WARNING if io_res: # Return an in-memory PNG for the web API instead of writing result.png. diff --git a/templates/index.html b/templates/index.html index 683b429..d500301 100644 --- a/templates/index.html +++ b/templates/index.html @@ -2477,6 +2477,10 @@

if (response.ok && result.status === 'success') { if (result.command) logToConsole(`[Server] ${result.command}`, 'info'); + if (result.warning) { + logToConsole(`[Warning] ${result.warning}`, 'warn'); + showToast(result.warning, 'warn'); + } logToConsole(`[Success] Map generated and loaded (${describeDataUrl(result.image_url)})`, 'success'); if (result.map_values) { diff --git a/templates/video.html b/templates/video.html index d42789a..a3c2c2f 100644 --- a/templates/video.html +++ b/templates/video.html @@ -3863,8 +3863,13 @@

} logToConsole(`[Success] Video rendered: ${filePath}`, 'success'); + if (result.warning) { + logToConsole(`[Warning] ${result.warning}`, 'warn'); + showToast(result.warning, 'warn'); + } else { + showToast(result.has_audio ? 'Video rendered with music! Click Download video.' : 'Video rendered without music.', 'success'); + } metaBadge.textContent = `Done (${new Date().toLocaleTimeString()})`; - showToast(result.has_audio ? 'Video rendered with music! Click Download video.' : 'Video rendered without music.', 'success'); } catch (error) { logToConsole(`[API Error] ${error.message}`, 'error'); showToast(error.message || "Video render failed. Check console logs.", 'error'); diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index 44df091..f13660f 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -1219,6 +1219,7 @@ def _veil_mask(t: float) -> np.ndarray: # Prefer the native Rust compositor when available; fall back to MoviePy for dynamic map zoom or reveal. used_rust = False + rust_warning: str | None = None # ======== RUST ENGINE INJECTION ============= try: # pragma: no cover if zoom_enabled or reveal_enabled: @@ -1297,11 +1298,11 @@ def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: ) used_rust = True except Exception as exc: - logging.warning( - "Rust video render unavailable or failed (%s: %s); falling back to MoviePy.", - type(exc).__name__, - exc, + rust_warning = ( + f"Rust video render unavailable or failed ({type(exc).__name__}: {exc}); " + "falling back to MoviePy." ) + logging.warning(rust_warning) if not used_rust: # pragma: no branch final_clip = CompositeVideoClip(clips, size=(canvas_w, canvas_h)) @@ -1379,12 +1380,16 @@ def _zoom_full_frame(get_frame, t: float) -> np.ndarray: **encode_options, ) - return jsonify({ + payload = { "status": "success", "file_path": output_path, "download_url": "/api/download_video?" + urlencode({'path': output_path}), "has_audio": has_audio, - }), 200 + "render_engine": "rust" if used_rust else "moviepy", + } + if rust_warning: + payload["warning"] = rust_warning + return jsonify(payload), 200 except Exception as e: return jsonify({"status": "error", "error": f"Error processing video: {str(e)}"}), 500 From 6a125ceaf6d98acf9a5c1f07cb488d3cf714f4e0 Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 19:28:43 +0200 Subject: [PATCH 08/14] Implement Rust zoom/reveal/impact FX and live preview animation --- automap_rs/src/lib.rs | 431 ++++++++++++++++++++++++++++++++++++++++-- templates/video.html | 352 +++++++++++++++++++++++++++++++++- yt-dlp_serv.py | 64 +++++-- 3 files changed, 816 insertions(+), 31 deletions(-) diff --git a/automap_rs/src/lib.rs b/automap_rs/src/lib.rs index f9b3875..59b7e69 100644 --- a/automap_rs/src/lib.rs +++ b/automap_rs/src/lib.rs @@ -14,7 +14,7 @@ use pyo3::exceptions::PyValueError; use pyo3::prelude::*; -use pyo3::types::PyBytes; +use pyo3::types::{PyBytes, PyTuple}; use std::io::{Read, Write}; use std::process::{Command, Stdio}; @@ -23,10 +23,60 @@ use std::process::{Command, Stdio}; #[derive(FromPyObject)] struct DynamicLayer(Vec, i32, i32, usize, usize, f32, f32); -/// Composites the background video, static foreground, dynamic overlays, and intro veil -/// frame-by-frame in a single reusable RGBA buffer, streaming directly to/from `ffmpeg`. +/// Optional camera zoom parameters: +/// `(target_cx, target_cy, z_scale, z_start, z_dur, z_out_enabled, z_out_dur)`. +type ZoomParams = (f32, f32, f32, f32, f32, bool, f32); + +/// Optional country reveal animation & impact FX specification: +/// `(x, y, w, h, frame1_rgba, frame2_rgba, frame3_rgba, black_rgba, base_rgba, r_time, phase_end, fade_dur, impact_fx)`. +struct RevealSpec( + i32, + i32, + usize, + usize, + Vec, + Vec, + Vec, + Vec, + Vec, + f32, + f32, + f32, + bool, +); + +impl<'py> FromPyObject<'py> for RevealSpec { + fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult { + let t = ob.downcast::()?; + if t.len() != 13 { + return Err(PyValueError::new_err(format!( + "reveal_spec must be a 13-tuple, got length {}", + t.len() + ))); + } + Ok(Self( + t.get_item(0)?.extract()?, + t.get_item(1)?.extract()?, + t.get_item(2)?.extract()?, + t.get_item(3)?.extract()?, + t.get_item(4)?.extract()?, + t.get_item(5)?.extract()?, + t.get_item(6)?.extract()?, + t.get_item(7)?.extract()?, + t.get_item(8)?.extract()?, + t.get_item(9)?.extract()?, + t.get_item(10)?.extract()?, + t.get_item(11)?.extract()?, + t.get_item(12)?.extract()?, + )) + } +} + +/// Composites the background video, static foreground, country reveal animation, +/// dynamic overlays, intro veil, camera zoom, and impact FX frame-by-frame in reusable +/// RGBA buffers, streaming directly to/from `ffmpeg`. #[pyfunction] -#[pyo3(signature = (bg_video_path, static_rgba, dynamic_layers, veil_duration, audio_path, output_path, width, height, fps, duration, codec, preset=None, draft=false))] +#[pyo3(signature = (bg_video_path, static_rgba, dynamic_layers, veil_duration, audio_path, output_path, width, height, fps, duration, codec, preset=None, draft=false, zoom_params=None, reveal_spec=None))] #[allow(clippy::too_many_arguments)] fn render_video_rs( py: Python<'_>, @@ -43,6 +93,8 @@ fn render_video_rs( codec: &str, preset: Option<&str>, draft: bool, + zoom_params: Option, + reveal_spec: Option, ) -> PyResult<()> { let expected_len = width * height * 4; if static_rgba.len() != expected_len { @@ -54,6 +106,26 @@ fn render_video_rs( expected_len ))); } + if let Some(RevealSpec(_, _, rw, rh, ref f1, ref f2, ref f3, ref black, ref base, _, _, _, _)) = reveal_spec { + let rev_len = rw * rh * 4; + for (name, buf) in [ + ("frame1_rgba", f1), + ("frame2_rgba", f2), + ("frame3_rgba", f3), + ("black_rgba", black), + ("base_rgba", base), + ] { + if buf.len() != rev_len { + return Err(PyValueError::new_err(format!( + "reveal_spec {name} length {} does not match {}x{}x4 ({})", + buf.len(), + rw, + rh, + rev_len + ))); + } + } + } // Release Python's GIL so other Flask/worker threads are not blocked during rendering. py.allow_threads(|| { @@ -132,9 +204,14 @@ fn render_video_rs( // 3. Precompute non-transparent byte spans in static_rgba so alpha==0 regions are skipped per frame. let static_spans = build_non_transparent_spans(static_rgba); - // 4. Reusable background and compositing frame buffers (~8.3 MB each for 1080x1920 RGBA). + // 4. Reusable background, compositing, and zoom/FX frame buffers (~8.3 MB each for 1080x1920 RGBA). + let impact_fx_enabled = reveal_spec.as_ref().is_some_and(|r| r.12); + let need_zoom_buf = zoom_params.is_some() || impact_fx_enabled; let mut bg_buf = vec![0u8; expected_len]; let mut frame_buf = vec![0u8; expected_len]; + let mut zoom_buf = if need_zoom_buf { vec![0u8; expected_len] } else { Vec::new() }; + let mut ca_row_buf = if impact_fx_enabled { vec![0u8; width * 4] } else { Vec::new() }; + let mut x_resample_lut = if need_zoom_buf { Vec::with_capacity(width) } else { Vec::new() }; for frame_idx in 0..total_frames { if dec_out.read_exact(&mut bg_buf).is_err() { @@ -150,6 +227,28 @@ fn render_video_rs( // Layer 1: flattened static foreground (map, title, watermark). blend_spans_in_place(&mut frame_buf, static_rgba, &static_spans); + // Layer 1b: country reveal animation (dots -> fade from black to base). + if let Some(RevealSpec(rx, ry, rw, rh, ref f1, ref f2, ref f3, ref black, ref base, r_time, phase_end, fade_dur, _)) = + reveal_spec + { + if t < r_time { + let dot_frame = if t < phase_end * 0.33 { + f1 + } else if t < phase_end * 0.66 { + f2 + } else { + f3 + }; + blend_rect_in_place(&mut frame_buf, width, height, dot_frame, rx, ry, rw, rh, 255); + } else if t >= r_time + fade_dur { + blend_rect_in_place(&mut frame_buf, width, height, base, rx, ry, rw, rh, 255); + } else { + let fade_alpha = (1.0 - (t - r_time) / fade_dur).clamp(0.0, 1.0); + let fade_q8 = (fade_alpha * 256.0).round().clamp(0.0, 256.0) as i32; + blend_lerp_rect_in_place(&mut frame_buf, width, height, base, black, rx, ry, rw, rh, fade_q8); + } + } + // Layer 2: dynamic overlays (subscribe badge, stars) with optional fade-in. for layer in &dynamic_layers { let start_sec = layer.5; @@ -192,9 +291,67 @@ fn render_video_rs( } } + // Layer 4: camera zoom + reveal impact FX (punch, shake, CA, glitch bands, flash). + let out_buf: &[u8] = if need_zoom_buf { + let (mut cw, mut ch, mut x0, mut y0) = if let Some(zp) = zoom_params { + compute_zoom_crop(zp, width as f32, height as f32, t, duration) + } else { + (width as f32, height as f32, 0.0, 0.0) + }; + + let impact_dt = if impact_fx_enabled { + reveal_spec.as_ref().map(|r| t - r.9).filter(|&dt| (0.0..0.60).contains(&dt)) + } else { + None + }; + + if let Some(dt) = impact_dt { + let env = (-dt * 5.8).exp() * (1.0 - dt / 0.60).max(0.0); + let punch = 1.0 + 0.042 * env; + let inv_p = 1.0 / punch; + let new_cw = cw * inv_p; + let new_ch = ch * inv_p; + let margin_x = (cw - new_cw) * 0.5; + let margin_y = (ch - new_ch) * 0.5; + let shake_x = env * 22.0 * (dt * 85.0).sin() + env * 8.0 * (dt * 145.0).cos(); + let shake_y = env * 18.0 * (dt * 78.0).cos() - env * 6.0 * (dt * 130.0).sin(); + cw = new_cw; + ch = new_ch; + x0 = (x0 + margin_x + shake_x).clamp(0.0, (width as f32 - cw).max(0.0)); + y0 = (y0 + margin_y + shake_y).clamp(0.0, (height as f32 - ch).max(0.0)); + } + + let do_resample = cw < width as f32 - 0.5 || x0.abs() > 0.1 || y0.abs() > 0.1; + let active_buf: &mut [u8] = if do_resample { + bilinear_resample_rgba( + &frame_buf, + &mut zoom_buf, + width, + height, + x0, + y0, + cw, + ch, + &mut x_resample_lut, + ); + &mut zoom_buf + } else { + &mut frame_buf + }; + + if let Some(dt) = impact_dt { + if dt < 0.38 { + apply_impact_fx_in_place(active_buf, width, height, dt, &mut ca_row_buf); + } + } + active_buf + } else { + &frame_buf + }; + // Stream the composited frame into ffmpeg's stdin. enc_in - .write_all(&frame_buf) + .write_all(out_buf) .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("encoder write failed: {e}")))?; } @@ -244,6 +401,32 @@ fn blend_spans_in_place(base: &mut [u8], overlay: &[u8], spans: &[(usize, usize) } } +/// Computes the clipped destination/source bounds for a positioned overlay rectangle. +/// Returns `(start_x, start_y, end_y, row_bytes, ox_start)` or `None` if completely off-screen. +#[inline] +fn clip_rect( + canvas_w: usize, + canvas_h: usize, + x: i32, + y: i32, + ov_w: usize, + ov_h: usize, +) -> Option<(usize, usize, usize, usize, usize)> { + if ov_w == 0 || ov_h == 0 { + return None; + } + let start_y = y.max(0) as usize; + let end_y = (y + ov_h as i32).min(canvas_h as i32).max(0) as usize; + let start_x = x.max(0) as usize; + let end_x = (x + ov_w as i32).min(canvas_w as i32).max(0) as usize; + if start_x >= end_x || start_y >= end_y { + return None; + } + let row_bytes = (end_x - start_x) * 4; + let ox_start = (start_x as i32 - x) as usize; + Some((start_x, start_y, end_y, row_bytes, ox_start)) +} + /// Alpha-blends a positioned rectangular RGBA overlay onto `base` in place, clipped to canvas bounds. #[allow(clippy::too_many_arguments)] fn blend_rect_in_place( @@ -257,18 +440,13 @@ fn blend_rect_in_place( ov_h: usize, op_u8: u32, ) { - if op_u8 == 0 || ov_w == 0 || ov_h == 0 { + if op_u8 == 0 { return; } - let start_y = y.max(0) as usize; - let end_y = (y + ov_h as i32).min(canvas_h as i32).max(0) as usize; - let start_x = x.max(0) as usize; - let end_x = (x + ov_w as i32).min(canvas_w as i32).max(0) as usize; - if start_x >= end_x || start_y >= end_y { + let Some((start_x, start_y, end_y, row_bytes, ox_start)) = clip_rect(canvas_w, canvas_h, x, y, ov_w, ov_h) + else { return; - } - let row_bytes = (end_x - start_x) * 4; - let ox_start = (start_x as i32 - x) as usize; + }; for cy in start_y..end_y { let oy = (cy as i32 - y) as usize; @@ -291,6 +469,229 @@ fn blend_rect_in_place( } } +/// Linearly interpolates `base_ov + (fade_q8 / 256) * (black_ov - base_ov)` and alpha-blends +/// the resulting RGBA pixels onto `canvas` at `(x, y)` in place. +#[allow(clippy::too_many_arguments)] +fn blend_lerp_rect_in_place( + canvas: &mut [u8], + canvas_w: usize, + canvas_h: usize, + base_ov: &[u8], + black_ov: &[u8], + x: i32, + y: i32, + ov_w: usize, + ov_h: usize, + fade_q8: i32, +) { + let Some((start_x, start_y, end_y, row_bytes, ox_start)) = clip_rect(canvas_w, canvas_h, x, y, ov_w, ov_h) + else { + return; + }; + + for cy in start_y..end_y { + let oy = (cy as i32 - y) as usize; + let dst_start = (cy * canvas_w + start_x) * 4; + let src_start = (oy * ov_w + ox_start) * 4; + if src_start + row_bytes > base_ov.len() + || src_start + row_bytes > black_ov.len() + || dst_start + row_bytes > canvas.len() + { + continue; + } + let dst_row = &mut canvas[dst_start..dst_start + row_bytes]; + let base_row = &base_ov[src_start..src_start + row_bytes]; + let black_row = &black_ov[src_start..src_start + row_bytes]; + for ((dst, b), k) in dst_row + .chunks_exact_mut(4) + .zip(base_row.chunks_exact(4)) + .zip(black_row.chunks_exact(4)) + { + let fg = [ + (b[0] as i32 + (((k[0] as i32 - b[0] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + (b[1] as i32 + (((k[1] as i32 - b[1] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + (b[2] as i32 + (((k[2] as i32 - b[2] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + (b[3] as i32 + (((k[3] as i32 - b[3] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + ]; + blend_pixel_u8(dst, &fg); + } + } +} + +#[inline] +fn smootherstep(u: f32) -> f32 { + u * u * u * (u * (u * 6.0 - 15.0) + 10.0) +} + +/// Computes the camera zoom crop `(cw, ch, x0, y0)` at time `t` using quintic smootherstep. +fn compute_zoom_crop(zp: ZoomParams, canvas_w: f32, canvas_h: f32, t: f32, total_dur: f32) -> (f32, f32, f32, f32) { + let (target_cx, target_cy, z_scale, z_start, z_dur, z_out_enabled, z_out_dur) = zp; + if z_scale <= 1.0 || t <= z_start { + return (canvas_w, canvas_h, 0.0, 0.0); + } + + let final_cw = canvas_w / z_scale; + let final_ch = canvas_h / z_scale; + let final_x0 = (target_cx - final_cw * 0.5).clamp(0.0, (canvas_w - final_cw).max(0.0)); + let final_y0 = (target_cy - final_ch * 0.5).clamp(0.0, (canvas_h - final_ch).max(0.0)); + + let ease = if z_dur > 0.0 && t < z_start + z_dur { + smootherstep((t - z_start) / z_dur) + } else if z_out_enabled && z_out_dur > 0.0 && total_dur > (z_start + z_dur + 0.05) { + let out_start = (z_start + z_dur).max(total_dur - z_out_dur); + let out_dur = (total_dur - out_start).max(0.05); + if t >= total_dur { + 0.0 + } else if t > out_start { + 1.0 - smootherstep((t - out_start) / out_dur) + } else { + 1.0 + } + } else { + 1.0 + }; + + if ease <= 0.0 { + return (canvas_w, canvas_h, 0.0, 0.0); + } + + let cw = canvas_w + (final_cw - canvas_w) * ease; + let ch = canvas_h + (final_ch - canvas_h) * ease; + let x0 = final_x0 * ease; + let y0 = final_y0 * ease; + (cw, ch, x0, y0) +} + +/// Fast 8-bit fixed-point bilinear resample of the crop `[x0, x0+cw] x [y0, y0+ch]` from `src` into `dst`. +#[allow(clippy::too_many_arguments)] +fn bilinear_resample_rgba( + src: &[u8], + dst: &mut [u8], + width: usize, + height: usize, + x0: f32, + y0: f32, + cw: f32, + ch: f32, + x_lut: &mut Vec<(usize, usize, u32, u32)>, +) { + if width == 0 || height == 0 { + return; + } + let scale_x = cw / width as f32; + let scale_y = ch / height as f32; + let max_x = (width - 1) as f32; + let max_y = (height - 1) as f32; + + x_lut.clear(); + for dx in 0..width { + let sx = (x0 + (dx as f32 + 0.5) * scale_x - 0.5).clamp(0.0, max_x); + let ix0 = (sx as usize).min(width - 1); + let ix1 = (ix0 + 1).min(width - 1); + let wx1 = ((sx - ix0 as f32) * 256.0).round().clamp(0.0, 256.0) as u32; + let wx0 = 256 - wx1; + x_lut.push((ix0 * 4, ix1 * 4, wx0, wx1)); + } + + let row_stride = width * 4; + for dy in 0..height { + let sy = (y0 + (dy as f32 + 0.5) * scale_y - 0.5).clamp(0.0, max_y); + let iy0 = (sy as usize).min(height - 1); + let iy1 = (iy0 + 1).min(height - 1); + let wy1 = ((sy - iy0 as f32) * 256.0).round().clamp(0.0, 256.0) as u32; + let wy0 = 256 - wy1; + + let row0 = &src[iy0 * row_stride..(iy0 + 1) * row_stride]; + let row1 = &src[iy1 * row_stride..(iy1 + 1) * row_stride]; + let dst_row = &mut dst[dy * row_stride..(dy + 1) * row_stride]; + + for (dst_px, &(ox0, ox1, wx0, wx1)) in dst_row.chunks_exact_mut(4).zip(x_lut.iter()) { + let p00 = &row0[ox0..ox0 + 4]; + let p10 = &row0[ox1..ox1 + 4]; + let p01 = &row1[ox0..ox0 + 4]; + let p11 = &row1[ox1..ox1 + 4]; + + for c in 0..3 { + let top = p00[c] as u32 * wx0 + p10[c] as u32 * wx1; + let bot = p01[c] as u32 * wx0 + p11[c] as u32 * wx1; + dst_px[c] = ((top * wy0 + bot * wy1 + 32768) >> 16) as u8; + } + dst_px[3] = 255; + } + } +} + +/// Applies RGB chromatic aberration, horizontal glitch band rolls, and flash brightness boost in place. +fn apply_impact_fx_in_place(buf: &mut [u8], width: usize, height: usize, dt: f32, row_buf: &mut [u8]) { + if width == 0 || height == 0 { + return; + } + let glitch_env = (-dt * 7.5).exp(); + let sign = if (dt * 105.0).sin() >= 0.0 { 1.0 } else { -1.0 }; + let ca_shift = (10.0 * glitch_env * sign).round() as i32; + let row_stride = width * 4; + + if ca_shift > 0 && (ca_shift as usize) < width { + let s = ca_shift as usize; + for row in buf.chunks_exact_mut(row_stride) { + row_buf.copy_from_slice(row); + for x in s..width { + row[x * 4] = row_buf[(x - s) * 4]; + } + for x in 0..(width - s) { + row[x * 4 + 2] = row_buf[(x + s) * 4 + 2]; + } + } + } else if ca_shift < 0 && ((-ca_shift) as usize) < width { + let s = (-ca_shift) as usize; + for row in buf.chunks_exact_mut(row_stride) { + row_buf.copy_from_slice(row); + for x in 0..(width - s) { + row[x * 4] = row_buf[(x + s) * 4]; + } + for x in s..width { + row[x * 4 + 2] = row_buf[(x - s) * 4 + 2]; + } + } + } + + if glitch_env > 0.20 { + let step = (dt * 50.0) as usize; + let band_h = (height / 65).max(8); + let dx = ((18.0 * glitch_env).round() as usize).max(4) % width; + if dx > 0 { + let byte_shift = dx * 4; + for (b_idx, frac) in [0.38_f32, 0.56_f32].iter().enumerate() { + let offset = ((step * 53 + b_idx * 97) % 140) as i32 - 70; + let by0 = (((height as f32 * frac) as i32 + offset).max(0) as usize) + .min(height.saturating_sub(band_h)); + let by1 = (by0 + band_h).min(height); + let roll_right = (step + b_idx) % 2 == 0; + for y in by0..by1 { + let row = &mut buf[y * row_stride..(y + 1) * row_stride]; + if roll_right { + row.rotate_right(byte_shift); + } else { + row.rotate_left(byte_shift); + } + } + } + } + } + + if dt < 0.14 { + let boost = (18.0 * (1.0 - dt / 0.14)).round() as i32; + if boost > 0 { + let b = boost.min(255) as u8; + for px in buf.chunks_exact_mut(4) { + px[0] = px[0].saturating_add(b); + px[1] = px[1].saturating_add(b); + px[2] = px[2].saturating_add(b); + } + } + } +} + #[inline(always)] fn blend_pixel_u8(bg: &mut [u8], fg: &[u8]) { let a = fg[3] as u32; diff --git a/templates/video.html b/templates/video.html index a3c2c2f..b44bd0d 100644 --- a/templates/video.html +++ b/templates/video.html @@ -253,6 +253,7 @@ } .codec-card:disabled { opacity: .4; cursor: not-allowed; } #stageMapArea { + position: relative; display: flex; flex: 1; min-height: 0; @@ -1340,6 +1341,7 @@

+
@@ -1353,10 +1355,30 @@

+ + +
+ + +
+
+ + +
+ 00:00.0 / 00:08.0 +
@@ -2284,6 +2306,7 @@

const enabled = !!document.getElementById('revealCountryToggle')?.checked; const panel = document.getElementById('revealControlsPanel'); if (panel) panel.classList.toggle('hidden', !enabled); + if (typeof renderPreviewFrame === 'function') renderPreviewFrame(previewAnimTime); } function updateMapZoomUI() { @@ -2441,11 +2464,14 @@

function updatePreviewPlayback() { const bg = document.getElementById('stageBgPreview'); const player = document.getElementById('renderedVideoPlayer'); - if (previewVisible && !document.hidden && player.classList.contains('hidden') && bg.getAttribute('src')) { - bg.play().catch(() => {}); + const liveActive = previewVisible && !document.hidden && player && player.classList.contains('hidden'); + if (liveActive && bg.getAttribute('src')) { + if (previewAnimPlaying) bg.play().catch(() => {}); + else bg.pause(); } else { bg.pause(); } + syncPreviewAnimationLoop(); } function showLiveComposite() { @@ -2456,6 +2482,319 @@

updatePreviewPlayback(); } + let previewAnimPlaying = true; + let previewAnimTime = 0; + let previewLastTs = null; + let previewRafId = null; + const revealMaskCache = { key: '', silhouette: null, cx: 0.5, cy: 0.5, loadingKey: '' }; + + function smootherstep(u) { + const c = Math.max(0, Math.min(1, u)); + return c * c * c * (c * (c * 6 - 15) + 10); + } + + function formatPreviewClock(sec) { + const s = Math.max(0, Number(sec) || 0); + const mins = Math.floor(s / 60); + const rem = (s % 60).toFixed(1).padStart(4, '0'); + return `${String(mins).padStart(2, '0')}:${rem}`; + } + + function ensureRevealMaskLoaded() { + const map = document.getElementById('stageMapPreview'); + if (!map || map.classList.contains('hidden') || !map.naturalWidth || !map.naturalHeight) return null; + + const customDataUrl = (typeof window.revealMaskDataUrl === 'string' && window.revealMaskDataUrl) ? window.revealMaskDataUrl : ''; + let maskKey = ''; + let maskSrc = ''; + if (customDataUrl) { + maskKey = `custom:${customDataUrl.slice(0, 64)}`; + maskSrc = customDataUrl; + } else { + const countryKey = (document.getElementById('mapZoomCountryKey')?.value || '').trim(); + if (!countryKey) return null; + const aspect = map.naturalWidth / map.naturalHeight; + const mapKind = aspect < 1.25 ? 'europe' : 'world'; + maskKey = `${mapKind}:${countryKey}`; + maskSrc = `/api/zoom_country_outline?map=${encodeURIComponent(mapKind)}&key=${encodeURIComponent(countryKey)}`; + } + + if (revealMaskCache.key === maskKey && revealMaskCache.silhouette) { + return revealMaskCache; + } + if (revealMaskCache.loadingKey === maskKey) { + return null; + } + + revealMaskCache.loadingKey = maskKey; + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.onload = () => { + if (revealMaskCache.loadingKey !== maskKey) return; + const w = img.naturalWidth || 1; + const h = img.naturalHeight || 1; + const off = document.createElement('canvas'); + off.width = w; + off.height = h; + const octx = off.getContext('2d'); + octx.drawImage(img, 0, 0, w, h); + const imgData = octx.getImageData(0, 0, w, h); + const data = imgData.data; + let sumX = 0; + let sumY = 0; + let count = 0; + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + const idx = (y * w + x) * 4; + const a = data[idx + 3]; + if (a > 20) { + data[idx] = 14; + data[idx + 1] = 14; + data[idx + 2] = 22; + data[idx + 3] = Math.round(a * 0.95); + sumX += x; + sumY += y; + count++; + } else { + data[idx + 3] = 0; + } + } + } + octx.putImageData(imgData, 0, 0); + revealMaskCache.key = maskKey; + revealMaskCache.silhouette = off; + revealMaskCache.cx = count > 0 ? (sumX / count) / w : 0.5; + revealMaskCache.cy = count > 0 ? (sumY / count) / h : 0.5; + revealMaskCache.loadingKey = ''; + renderPreviewFrame(previewAnimTime); + }; + img.onerror = () => { + if (revealMaskCache.loadingKey === maskKey) revealMaskCache.loadingKey = ''; + }; + img.src = maskSrc; + return null; + } + + function renderPreviewFrame(t) { + const stage = document.querySelector('.video-preview-stage'); + const composite = document.getElementById('stageCompositeBox'); + const player = document.getElementById('renderedVideoPlayer'); + const veil = document.getElementById('stageIntroVeil'); + const revealCanvas = document.getElementById('stageRevealCanvas'); + const subBox = document.getElementById('stageSubscribeBanner'); + const starsBox = document.getElementById('stageWatermarkStars'); + const timeEl = document.getElementById('previewTimeIndicator'); + const totalDur = getCutDuration(); + const baseScale = stage && stage.clientWidth ? (stage.clientWidth / 1080) : 1; + + if (timeEl) { + timeEl.textContent = `${formatPreviewClock(t)} / ${formatPreviewClock(totalDur)}`; + } + + if (!player || !player.classList.contains('hidden')) { + if (composite) composite.style.transform = `scale(${baseScale})`; + if (veil) veil.classList.add('hidden'); + if (revealCanvas) revealCanvas.classList.add('hidden'); + if (subBox) subBox.style.opacity = ''; + if (starsBox) starsBox.style.opacity = ''; + return; + } + + const introFade = !!document.getElementById('introFadeToggle')?.checked; + if (veil) { + if (introFade && t < 0.8) { + veil.classList.remove('hidden'); + veil.style.opacity = String(Math.max(0, 1 - t / 0.8)); + } else { + veil.classList.add('hidden'); + veil.style.opacity = '0'; + } + } + + const subEnabled = !!document.getElementById('subscribeBadgeToggle')?.checked; + const subDelay = Number(document.getElementById('subscribeDelayInput')?.value || 2.5); + if (subBox) { + if (subEnabled && !subBox.classList.contains('hidden')) { + subBox.style.opacity = String(t < subDelay ? 0 : Math.min(1, (t - subDelay) / 0.4)); + } else { + subBox.style.opacity = ''; + } + } + + const starsEnabled = !!document.getElementById('watermarkStarsToggle')?.checked; + if (starsBox) { + if (starsEnabled && !starsBox.classList.contains('hidden')) { + starsBox.style.opacity = String(Math.min(1, Math.max(0, (t - 0.3) / 0.5))); + } else { + starsBox.style.opacity = ''; + } + } + + const zoomEnabled = !!document.getElementById('mapZoomToggle')?.checked; + const revealEnabled = !!document.getElementById('revealCountryToggle')?.checked; + const rTime = Number(document.getElementById('revealTimeInput')?.value || 5.5); + const map = document.getElementById('stageMapPreview'); + const area = document.getElementById('stageMapArea'); + + let s = 1; + let tx = 0; + let ty = 0; + if (zoomEnabled) { + const rawX = parseFloat(document.getElementById('mapZoomX')?.value); + const rawY = parseFloat(document.getElementById('mapZoomY')?.value); + const zx = Math.max(0, Math.min(1, Number.isFinite(rawX) ? rawX : 0.80)); + const zy = Math.max(0, Math.min(1, Number.isFinite(rawY) ? rawY : 0.35)); + const targetScale = Math.max(1, Number(document.getElementById('mapZoomScale')?.value || 2.0)); + const zStart = Number(document.getElementById('mapZoomStart')?.value || 1.5); + const zDur = Math.max(0.1, Number(document.getElementById('mapZoomDuration')?.value || 2.5)); + const zEnd = zStart + zDur; + const zOutEnabled = !!document.getElementById('mapZoomOutToggle')?.checked; + const zOutDur = Math.max(0.1, Number(document.getElementById('mapZoomOutDuration')?.value || 2.0)); + const zOutStart = Math.max(zEnd, totalDur - zOutDur); + + let ease = 0; + if (t >= zStart && t < zEnd) { + ease = smootherstep((t - zStart) / zDur); + } else if (t >= zEnd) { + ease = (zOutEnabled && t >= zOutStart) ? (1 - smootherstep((t - zOutStart) / zOutDur)) : 1; + } + s = 1 + (targetScale - 1) * ease; + const targetX = (map && map.offsetWidth > 0 && area) + ? (area.offsetLeft + map.offsetLeft + zx * map.offsetWidth) + : (zx * 1080); + const targetY = (map && map.offsetHeight > 0 && area) + ? (area.offsetTop + map.offsetTop + zy * map.offsetHeight) + : (zy * 1920); + tx = Math.min(0, Math.max(1080 * (1 - s), 540 - targetX * s)); + ty = Math.min(0, Math.max(1920 * (1 - s), 960 - targetY * s)); + } + + let shakeX = 0; + let shakeY = 0; + if (revealEnabled && t >= rTime && t < rTime + 0.5) { + const dt = t - rTime; + const decay = Math.exp(-dt * 9.0) * (1 - dt / 0.5); + const amp = 18 * decay; + shakeX = Math.sin(dt * 55) * amp; + shakeY = Math.cos(dt * 47) * amp * 0.7; + } + + if (composite) { + composite.style.transform = `scale(${baseScale}) translate3d(${(tx + shakeX).toFixed(2)}px, ${(ty + shakeY).toFixed(2)}px, 0) scale(${s.toFixed(4)})`; + } + + const fadeDur = 0.25; + const mask = revealEnabled ? ensureRevealMaskLoaded() : null; + if (revealCanvas && revealEnabled && mask && mask.silhouette && map && !map.classList.contains('hidden') && map.offsetWidth > 0 && area && t < rTime + fadeDur) { + revealCanvas.classList.remove('hidden'); + const aw = Math.max(1, area.clientWidth); + const ah = Math.max(1, area.clientHeight); + if (revealCanvas.width !== aw) revealCanvas.width = aw; + if (revealCanvas.height !== ah) revealCanvas.height = ah; + const ctx = revealCanvas.getContext('2d'); + ctx.clearRect(0, 0, aw, ah); + const alpha = t < rTime ? 1.0 : Math.max(0, 1 - (t - rTime) / fadeDur); + const mx = map.offsetLeft; + const my = map.offsetTop; + const mw = map.offsetWidth; + const mh = map.offsetHeight; + ctx.save(); + ctx.globalAlpha = alpha; + ctx.drawImage(mask.silhouette, mx, my, mw, mh); + if (t < rTime) { + const dotCount = t < rTime * 0.30 ? 1 : (t < rTime * 0.60 ? 2 : 3); + const cx = mx + mask.cx * mw; + const cy = my + mask.cy * mh; + const r = Math.max(5, Math.min(11, mw * 0.011)); + const gap = r * 2.8; + const startX = cx - ((dotCount - 1) * gap) / 2; + for (let i = 0; i < dotCount; i++) { + const dx = startX + i * gap; + ctx.beginPath(); + ctx.arc(dx, cy, r, 0, Math.PI * 2); + ctx.fillStyle = '#ffffff'; + ctx.shadowColor = 'rgba(0,0,0,0.75)'; + ctx.shadowBlur = 8; + ctx.fill(); + ctx.shadowBlur = 0; + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(15,23,42,0.85)'; + ctx.stroke(); + } + } + ctx.restore(); + } else if (revealCanvas) { + revealCanvas.classList.add('hidden'); + } + } + + function syncPreviewTransportUI() { + const icon = document.getElementById('previewPlayPauseIcon'); + const label = document.getElementById('previewPlayPauseLabel'); + const bar = document.getElementById('previewPlaybackBar'); + const player = document.getElementById('renderedVideoPlayer'); + const mp4Active = player && !player.classList.contains('hidden'); + if (icon) icon.className = previewAnimPlaying ? 'fa-solid fa-pause text-[10px]' : 'fa-solid fa-play text-[10px]'; + if (label) label.textContent = previewAnimPlaying ? 'Pause' : 'Play'; + if (bar) bar.classList.toggle('opacity-40', !!mp4Active); + } + + function stepPreviewAnimation(ts) { + const player = document.getElementById('renderedVideoPlayer'); + if (!previewAnimPlaying || !previewVisible || document.hidden || !player || !player.classList.contains('hidden')) { + previewRafId = null; + previewLastTs = null; + renderPreviewFrame(previewAnimTime); + return; + } + if (previewLastTs !== null) { + const dt = Math.min(0.1, Math.max(0, (ts - previewLastTs) / 1000)); + const dur = getCutDuration(); + previewAnimTime = (previewAnimTime + dt) % Math.max(0.5, dur); + } + previewLastTs = ts; + renderPreviewFrame(previewAnimTime); + previewRafId = requestAnimationFrame(stepPreviewAnimation); + } + + function syncPreviewAnimationLoop() { + syncPreviewTransportUI(); + const player = document.getElementById('renderedVideoPlayer'); + const shouldRun = previewAnimPlaying && previewVisible && !document.hidden && player && player.classList.contains('hidden'); + if (shouldRun && previewRafId === null) { + previewLastTs = null; + previewRafId = requestAnimationFrame(stepPreviewAnimation); + } else if (!shouldRun) { + if (previewRafId !== null) { + cancelAnimationFrame(previewRafId); + previewRafId = null; + } + previewLastTs = null; + renderPreviewFrame(previewAnimTime); + } + } + + function togglePreviewAnimation() { + const player = document.getElementById('renderedVideoPlayer'); + if (player && !player.classList.contains('hidden')) return; + previewAnimPlaying = !previewAnimPlaying; + updatePreviewPlayback(); + } + + function restartPreviewAnimation() { + const player = document.getElementById('renderedVideoPlayer'); + if (player && !player.classList.contains('hidden')) return; + previewAnimTime = 0; + previewLastTs = null; + const bg = document.getElementById('stageBgPreview'); + if (bg && bg.getAttribute('src')) { + try { bg.currentTime = 0; } catch {} + } + previewAnimPlaying = true; + updatePreviewPlayback(); + renderPreviewFrame(0); + } + function updateTitleStyle() { document.getElementById('titleFontSizeValue').textContent = `${titleSettings().title_font_size} px`; updateStageTitlePreview(document.getElementById('videoTitleInput').value); @@ -3916,16 +4255,19 @@

if (VIDEO_SETTING_IDS.includes(event.target.id)) saveVideoSettings(); })); const stage = document.querySelector('.video-preview-stage'); - const composite = document.getElementById('stageCompositeBox'); new ResizeObserver(() => { - composite.style.transform = `scale(${stage.clientWidth / 1080})`; + renderPreviewFrame(previewAnimTime); }).observe(stage); - new ResizeObserver(fitStageMap).observe(document.getElementById('stageMapArea')); + new ResizeObserver(() => { + fitStageMap(); + renderPreviewFrame(previewAnimTime); + }).observe(document.getElementById('stageMapArea')); new IntersectionObserver(([entry]) => { previewVisible = entry.isIntersecting; updatePreviewPlayback(); }).observe(stage); document.addEventListener('visibilitychange', updatePreviewPlayback); + syncPreviewAnimationLoop(); window.addEventListener('pagehide', (event) => { // Keep blob URLs alive when the browser caches this page for Back. if (event.persisted) return; diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index f13660f..2ff9aef 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -767,13 +767,14 @@ def _build_reveal_map_clip( alpha_chan.filter(ImageFilter.GaussianBlur(10)).point(lambda p: round(p * 0.8)) ) - def _to_rgb_and_mask(frame_rgba) -> tuple[object, object]: + def _compose_rgba(frame_rgba) -> np.ndarray: if shadow_only is not None: canvas = shadow_only.copy() canvas.alpha_composite(Image.fromarray(frame_rgba), (24, 24)) - composed = np.asarray(canvas, dtype=np.uint8) - else: - composed = frame_rgba + return np.asarray(canvas, dtype=np.uint8) + return np.ascontiguousarray(frame_rgba, dtype=np.uint8) + + def _to_rgb_and_mask(composed: np.ndarray) -> tuple[object, object]: rgb = np.ascontiguousarray(composed[:, :, :3]) mask = np.ascontiguousarray(composed[:, :, 3], dtype=np.float32) / 255.0 return rgb, mask @@ -799,11 +800,17 @@ def _to_rgb_and_mask(frame_rgba) -> tuple[object, object]: dot_cy = float(ys[best]) dot_overlays = _render_reveal_dot_overlays(box_w, box_h, dot_cx, dot_cy) + dot_rgba_frames = { + count: _compose_rgba(_alpha_composite_patch(black_rgba, *dot_overlays[count])) + for count in (1, 2, 3) + } dot_frames = { - count: _to_rgb_and_mask(_alpha_composite_patch(black_rgba, *dot_overlays[count])) + count: _to_rgb_and_mask(dot_rgba_frames[count]) for count in (1, 2, 3) } - final_frame = _to_rgb_and_mask(base_rgba) + black_composed_rgba = _compose_rgba(black_rgba) + base_composed_rgba = _compose_rgba(base_rgba) + final_frame = _to_rgb_and_mask(base_composed_rgba) frame_cache: list[tuple[float, object, object] | None] = [None] @@ -825,13 +832,27 @@ def _get_cached_frame(t: float) -> tuple[object, object]: else: fade_alpha = max(0.0, min(1.0, 1.0 - (t_key - r_time) / fade_dur)) blended_rgba = np.clip(np.rint(base_f + fade_alpha * delta_f), 0, 255).astype(np.uint8) - rgb, mask = _to_rgb_and_mask(blended_rgba) + rgb, mask = _to_rgb_and_mask(_compose_rgba(blended_rgba)) frame_cache[0] = (t_key, rgb, mask) return rgb, mask rgb_clip = VideoClip(lambda t: _get_cached_frame(t)[0], duration=bg_duration) mask_clip = VideoClip(lambda t: _get_cached_frame(t)[1], is_mask=True, duration=bg_duration) - return rgb_clip.with_mask(mask_clip) + reveal_clip = rgb_clip.with_mask(mask_clip) + spec_h, spec_w = base_composed_rgba.shape[:2] + reveal_clip.rust_reveal_spec = ( + int(spec_w), + int(spec_h), + dot_rgba_frames[1].tobytes(), + dot_rgba_frames[2].tobytes(), + dot_rgba_frames[3].tobytes(), + black_composed_rgba.tobytes(), + base_composed_rgba.tobytes(), + float(r_time), + float(phase_end), + float(fade_dur), + ) + return reveal_clip @app.route('/api/render_video', methods=['POST']) @@ -1102,6 +1123,7 @@ def _decode_optional_image(field: str, label: str): ) reveal_active = reveal_enabled and reveal_mask_f is not None + rust_reveal_spec = None if reveal_active: map_clip = _build_reveal_map_clip( map_path, @@ -1119,6 +1141,24 @@ def _decode_optional_image(field: str, label: str): ) if effects: map_y -= 24 + raw_reveal = getattr(map_clip, "rust_reveal_spec", None) + if raw_reveal is not None: + spec_w, spec_h, f1, f2, f3, blk, base, rt, pe, fd = raw_reveal + rust_reveal_spec = ( + (canvas_w - spec_w) // 2, + int(map_y), + spec_w, + spec_h, + f1, + f2, + f3, + blk, + base, + rt, + pe, + fd, + True, + ) elif effects: with Image.open(map_path) as raw_map: map_image = raw_map.convert('RGBA').resize((box_w, box_h)) @@ -1217,13 +1257,11 @@ def _veil_mask(t: float) -> np.ndarray: media_resources.append(audio_clip) render_duration = min(bg_duration, audio_clip.duration or bg_duration) - # Prefer the native Rust compositor when available; fall back to MoviePy for dynamic map zoom or reveal. + # Prefer the native Rust compositor when available; fall back to MoviePy on failure. used_rust = False rust_warning: str | None = None # ======== RUST ENGINE INJECTION ============= try: # pragma: no cover - if zoom_enabled or reveal_enabled: - raise ImportError("Camera zoom and country reveal use MoviePy compositor") automap_rs = _load_automap_rs() def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: @@ -1246,6 +1284,8 @@ def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: # Skip clips[0] (background_video); Rust decodes it directly from prepared_bg_path. for clip in clips[1:]: + if rust_reveal_spec is not None and clip is map_clip: + continue if not hasattr(clip, "img"): continue @@ -1295,6 +1335,8 @@ def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes: codec, _x264_preset() if codec == 'libx264' else None, data.get('draft') is True, + zoom_params=zoom_params, + reveal_spec=rust_reveal_spec, ) used_rust = True except Exception as exc: From c70d5a7ca73b7c24ee6b8c827bc8344c25a4c8db Mon Sep 17 00:00:00 2001 From: bibed234 Date: Tue, 17 Nov 2026 19:39:04 +0200 Subject: [PATCH 09/14] Fit map to full 1080px frame width without clipping or right gap --- templates/video.html | 5 +++-- yt-dlp_serv.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/templates/video.html b/templates/video.html index b44bd0d..b417190 100644 --- a/templates/video.html +++ b/templates/video.html @@ -257,7 +257,8 @@ display: flex; flex: 1; min-height: 0; - width: 100%; + width: 1080px; + margin-inline: -20px; align-items: center; justify-content: center; } @@ -2456,7 +2457,7 @@

const map = document.getElementById('stageMapPreview'); const area = document.getElementById('stageMapArea'); if (!map.naturalWidth || !map.naturalHeight) return; - const scale = Math.min(area.clientWidth / map.naturalWidth, area.clientHeight / map.naturalHeight) * 1.14; + const scale = Math.min(area.clientWidth / map.naturalWidth, area.clientHeight / map.naturalHeight); map.style.width = `${map.naturalWidth * scale}px`; map.style.height = `${map.naturalHeight * scale}px`; } diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index 2ff9aef..c6b2256 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -1098,7 +1098,7 @@ def _decode_optional_image(field: str, label: str): map_bottom = 1450 if watermark_image is not None else (1664 if branded else 1760) map_area_height = max(240, map_bottom - map_top) # Fit inside the map area while ensuring non-portrait maps span the full Shorts width. - scale = min(1040 / map_clip.w, map_area_height / map_clip.h) * 1.14 + scale = min(canvas_w / map_clip.w, map_area_height / map_clip.h) if map_clip.w >= map_clip.h: scale = max(canvas_w / map_clip.w, scale) map_clip = map_clip.resized(scale) From 6734d64cf12dfd40ef3d2dadde9eb1749785942f Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 19:48:12 +0200 Subject: [PATCH 10/14] Add Generate idea button with two modes and remove Russia label example --- main.py | 48 ++++++++++- map/functions.py | 189 +++++++++++++++++++++++++++++++++++++++++++ templates/index.html | 92 ++++++++++++++++++++- templates/video.html | 2 +- 4 files changed, 325 insertions(+), 6 deletions(-) diff --git a/main.py b/main.py index e45947f..5212f3c 100644 --- a/main.py +++ b/main.py @@ -55,12 +55,12 @@ _resolve_theme_name, _to_rgba_tuple, ) -from map.constants import europe_coords, world_coords +from map.constants import europe_coords, world_coords, _PALETTE_THEMES from cli import AVAILABLE_MODELS from map.functions import ( - _ALLOWED_MAP_TYPES, AIServiceError, configured_api_key, list_deepseek_models, - parse_ideas_content, provider_for_model, provider_key_name, slugify_prompt, - validate_temperature, + _ALLOWED_MAP_TYPES, AIServiceError, configured_api_key, generate_map_idea, + list_deepseek_models, parse_ideas_content, provider_for_model, + provider_key_name, slugify_prompt, validate_temperature, ) from flask import Flask, request, jsonify, send_file, render_template, Response, session @@ -724,6 +724,46 @@ def generate(): return jsonify(resp_payload) +@app.route('/api/generate_idea', methods=['POST']) +def api_generate_idea(): + """Generate a map topic idea (and optionally matching parameters) using the selected AI model.""" + data = request.get_json(silent=True) or {} + try: + provider = _request_provider(data) + api_key = _request_api_key(data, provider) + except ValueError as error: + return jsonify(status='error', error=str(error)), 400 + + model = str(data.get("model") or ('deepseek-flash' if provider == 'deepseek' else AVAILABLE_MODELS[0])).strip() + if provider_for_model(model) != provider: + return jsonify(status='error', error=f"Model '{model}' does not match provider '{provider}'."), 400 + + with_params = str(data.get("with_params") or "").strip().lower() in ("1", "true", "yes", "on") or data.get("with_params") is True + + temperature = None + if "temperature" in data and str(data["temperature"]).strip() != "": + try: + temperature = validate_temperature(data["temperature"]) + except ValueError as err: + return jsonify(status='error', error=str(err)), 400 + + try: + result = generate_map_idea( + model, + api_key=api_key, + with_params=with_params, + available_themes=list(_PALETTE_THEMES.keys()), + available_fonts=_available_fonts(), + temperature=temperature, + ) + except AIServiceError as error: + return jsonify(status='error', error=str(error)), error.status_code + except Exception as exc: # noqa: BLE001 + return jsonify(status='error', error=str(exc)), 500 + + return jsonify({"status": "success", **result}), 200 + + @app.route('/api/models', methods=['POST']) def list_available_models(): """Return models available for the selected provider's API key.""" diff --git a/map/functions.py b/map/functions.py index f765f77..642717e 100644 --- a/map/functions.py +++ b/map/functions.py @@ -387,6 +387,195 @@ def ai_request(prompt: str, mode: str, ai_model: str, api_key: str | None = None return country_dict +IDEA_EXAMPLES = ( + "How many bears are there in your country?", + "How many school years children must study in your country?", + "What is the most popular drink in your country?", + "What is the biggest city in your country?", +) + + +def _call_model_text( + system_msg: str, + user_prompt: str, + ai_model: str, + api_key: str | None = None, + *, + temperature: float | None = None, + json_mode: bool = False, +) -> str: + """Send a lightweight prompt to the selected Gemini or DeepSeek model and return raw text.""" + if provider_for_model(ai_model) == 'deepseek': + payload: dict[str, object] = { + 'model': ai_model, + 'messages': [ + {'role': 'system', 'content': system_msg}, + {'role': 'user', 'content': user_prompt}, + ], + 'thinking': {'type': 'disabled'}, + 'max_tokens': 512, + 'stream': False, + } + if json_mode: + payload['response_format'] = {'type': 'json_object'} + if temperature is not None: + payload['temperature'] = validate_temperature(temperature) + key = api_key or configured_api_key('deepseek') + result = _deepseek_json('chat/completions', key, payload=payload) + try: + content = result['choices'][0]['message']['content'] + except (KeyError, IndexError, TypeError) as error: + raise AIServiceError('DeepSeek returned no idea. Please try again.', 502) from error + if not isinstance(content, str) or not content.strip(): + raise AIServiceError('DeepSeek returned an empty idea. Please try again.', 502) + return content.strip() + + try: + options: dict[str, object] = { + 'http_options': types.HttpOptions( + timeout=AI_TIMEOUT_MS, + retry_options=types.HttpRetryOptions(attempts=1), + ), + } + if api_key: + options['api_key'] = api_key + client = genai.Client(**options) + cfg_kwargs: dict[str, object] = {} + if temperature is not None: + cfg_kwargs['temperature'] = validate_temperature(temperature) + if json_mode: + cfg_kwargs['response_mime_type'] = 'application/json' + config = {'config': types.GenerateContentConfig(**cfg_kwargs)} if cfg_kwargs else {} + response = client.models.generate_content( + model=ai_model, + contents=f"{system_msg}\n\n{user_prompt}", + **config, + ) + except genai_errors.APIError as error: + if error.code in (500, 502, 503, 504): + raise AIServiceError( + f'The selected model ({ai_model}) is overloaded or temporarily unavailable. ' + 'Please try again shortly or select another model.', 503, + ) from error + if error.code == 429: + raise AIServiceError( + 'The AI request limit or quota has been reached. Please try again later ' + 'or check the quota for your API key.', 429, + ) from error + if error.code in (400, 401, 403, 404): + raise AIServiceError( + f'The selected model ({ai_model}) could not be used. ' + 'Refresh the model list and check your API key and model access.', 400, + ) from error + raise AIServiceError('The AI service could not complete this request. Please try again.') from error + except (httpx.TimeoutException, TimeoutError) as error: + raise AIServiceError( + 'The AI model did not respond within 45 seconds. ' + 'Please try again or select a faster model.', 504, + ) from error + + text = getattr(response, 'text', None) + if not isinstance(text, str) or not text.strip(): + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + return text.strip() + + +def generate_map_idea( + ai_model: str, + api_key: str | None = None, + *, + with_params: bool = False, + available_themes: list[str] | tuple[str, ...] | None = None, + available_fonts: list[str] | tuple[str, ...] | None = None, + temperature: float | None = None, +) -> dict[str, object]: + """Generate a single map idea (and optionally matching map parameters) via the selected AI model.""" + examples_block = "\n".join(f'- "{ex}"' for ex in IDEA_EXAMPLES) + + if not with_params: + system_msg = ( + "You generate short, engaging, curiosity-sparking map topic questions in English. " + "Return ONLY the idea itself as a single plain-text sentence/question, with no quotes, " + "no numbering, no markdown, and no explanation." + ) + user_prompt = ( + "Generate 1 new creative map topic idea in the exact same style and format as these examples:\n" + f"{examples_block}\n\n" + "Return only the idea text." + ) + raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=temperature, json_mode=False) + idea = raw.strip().splitlines()[0].strip().strip('"\'` ') + if not idea: + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + return {"idea": idea} + + themes = [str(t) for t in (available_themes or list(constants._PALETTE_THEMES.keys()))] + fonts = [str(f) for f in (available_fonts or ["Bips.ttf", "DIN Condensed.ttf", "kodchasan.ttf", "arialroundedmtbold.ttf"])] + allowed_map_types = ("default", "flag", "world", "world_countries") + allowed_modes = ("text", "number") + allowed_extras = ("none", "show_most_least", "show_short_form") + + system_msg = ( + "You generate short, engaging map topic questions in English along with the best map rendering parameters. " + "Return ONLY a valid JSON object (no markdown fences, no commentary)." + ) + user_prompt = ( + "Generate 1 new creative map topic idea in the same style as these examples:\n" + f"{examples_block}\n\n" + "Return a JSON object with these exact keys:\n" + '- "idea": string (the single map question/topic, no surrounding quotes)\n' + f'- "mode": one of {list(allowed_modes)} ("number" for numeric counts/amounts/years, "text" for names/words/categories)\n' + f'- "map_type": one of {list(allowed_map_types)} ("default" = Europe painted, "flag" = Europe flags, "world" = continents, "world_countries" = all world countries)\n' + f'- "palette_theme": one of {themes}\n' + f'- "font": one of {fonts}\n' + f'- "extra_option": one of {list(allowed_extras)} ("show_most_least" or "show_short_form" only when mode is "number" and map_type is not "world", otherwise "none")\n' + '- "show_legend": boolean (true if a legend helps explain the map, false otherwise)' + ) + raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=temperature, json_mode=True) + cleaned = raw.strip() + if cleaned.startswith("```"): + cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.IGNORECASE | re.DOTALL).strip() + try: + parsed = json.loads(cleaned) + except json.JSONDecodeError as error: + raise AIServiceError('AI returned invalid JSON for the map idea. Please try again.', 502) from error + if not isinstance(parsed, dict): + raise AIServiceError('AI returned an unexpected format for the map idea.', 502) + + idea = str(parsed.get("idea") or "").strip().strip('"\'` ') + if not idea: + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + + mode = str(parsed.get("mode") or "text").strip().lower() + if mode not in allowed_modes: + mode = "text" + map_type = str(parsed.get("map_type") or "default").strip().lower() + if map_type not in allowed_map_types: + map_type = "default" + palette_theme = str(parsed.get("palette_theme") or "auto").strip() + if palette_theme not in themes: + palette_theme = "auto" if "auto" in themes else themes[0] + font = str(parsed.get("font") or fonts[0]).strip() + if font not in fonts: + font = fonts[0] + extra_option = str(parsed.get("extra_option") or "none").strip().lower() + if extra_option not in allowed_extras or mode != "number" or map_type == "world": + extra_option = "none" + show_legend = bool(parsed.get("show_legend", False)) + + return { + "idea": idea, + "params": { + "mode": mode, + "map_type": map_type, + "palette_theme": palette_theme, + "font": font, + "extra_option": extra_option, + "show_legend": show_legend, + }, + } + + diff --git a/templates/index.html b/templates/index.html index d500301..761e2b0 100644 --- a/templates/index.html +++ b/templates/index.html @@ -397,11 +397,23 @@

+
+
+ + +
updateCommandPreview(); } + async function generateIdea() { + const btn = document.getElementById('generateIdeaBtn'); + const icon = document.getElementById('generateIdeaIcon'); + const textEl = document.getElementById('generateIdeaText'); + const withParams = document.getElementById('ideaModeSelect')?.value === 'idea_and_params'; + const state = collectCurrentState(); + + if (btn) btn.disabled = true; + if (icon) icon.className = 'fa-solid fa-spinner fa-spin text-[10px]'; + if (textEl) textEl.textContent = 'Thinking...'; + + try { + const response = await fetch('/api/generate_idea', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + provider: state.provider, + model: state.model, + api_key: state.api_key, + with_params: withParams, + temperature: state.temperature, + }), + }); + let result; + try { + result = await response.json(); + } catch { + throw new Error(`Server returned ${response.status} ${response.statusText}`); + } + if (!response.ok || result.status !== 'success' || !result.idea) { + throw new Error(result.error || 'Failed to generate idea'); + } + + const topicInput = document.getElementById('topicInput'); + if (topicInput) { + topicInput.value = result.idea; + scheduleTopicPreview(); + flushTopicPreview(); + } + + if (withParams && result.params) { + const p = result.params; + const modeRadio = document.querySelector(`input[name="mode"][value="${p.mode}"]`); + if (modeRadio) modeRadio.checked = true; + const mapRadio = document.querySelector(`input[name="map_type"][value="${p.map_type}"]`); + if (mapRadio) mapRadio.checked = true; + const paletteEl = document.getElementById('fillingPaletteTheme'); + if (paletteEl && p.palette_theme && Array.from(paletteEl.options).some(o => o.value === p.palette_theme)) { + paletteEl.value = p.palette_theme; + } + const fontEl = document.getElementById('fontSelect'); + if (fontEl && p.font && Array.from(fontEl.options).some(o => o.value === p.font)) { + fontEl.value = p.font; + } + if (typeof setSelectedExtraOption === 'function') { + setSelectedExtraOption(p.extra_option || 'none'); + } + const legendEl = document.getElementById('showLegendToggle'); + if (legendEl) legendEl.checked = !!p.show_legend; + + updateCommandPreview(); + logToConsole(`[Idea] "${result.idea}" (${p.mode}, ${p.map_type}, theme=${p.palette_theme}, font=${p.font})`, 'info'); + showToast(`Generated idea + params (${p.palette_theme}, ${p.map_type})`, 'success'); + } else { + updateCommandPreview(); + logToConsole(`[Idea] "${result.idea}"`, 'info'); + showToast('Generated new map idea!', 'success'); + } + } catch (error) { + logToConsole(`[Idea Error] ${error.message}`, 'error'); + showToast(error.message || 'Failed to generate idea', 'error'); + } finally { + if (btn) btn.disabled = false; + if (icon) icon.className = 'fa-solid fa-lightbulb text-[10px]'; + if (textEl) textEl.textContent = 'Generate idea'; + } + } + let loadedIdeasFile = { filename: '', text: '' }; let lastBatchResults = []; diff --git a/templates/video.html b/templates/video.html index b417190..66cdccc 100644 --- a/templates/video.html +++ b/templates/video.html @@ -874,7 +874,7 @@

Frame Com @@ -1646,7 +1646,7 @@

const icon = document.getElementById('generateIdeaIcon'); const textEl = document.getElementById('generateIdeaText'); const withParams = document.getElementById('ideaModeSelect')?.value === 'idea_and_params'; - const state = collectCurrentState(); + const state = getFormState(); if (btn) btn.disabled = true; if (icon) icon.className = 'fa-solid fa-spinner fa-spin text-[10px]'; @@ -1690,6 +1690,9 @@

const paletteEl = document.getElementById('fillingPaletteTheme'); if (paletteEl && p.palette_theme && Array.from(paletteEl.options).some(o => o.value === p.palette_theme)) { paletteEl.value = p.palette_theme; + if (typeof onPaletteThemeChange === 'function') { + onPaletteThemeChange(); + } } const fontEl = document.getElementById('fontSelect'); if (fontEl && p.font && Array.from(fontEl.options).some(o => o.value === p.font)) { @@ -2281,7 +2284,7 @@

let topicPreviewTimer; function scheduleTopicPreview(event) { clearTimeout(topicPreviewTimer); - if (event.isComposing) return; + if (event && event.isComposing) return; topicPreviewTimer = setTimeout(flushTopicPreview, 250); } From de1d85a10306dbc3656921a659b723b52aeddefa Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 20:32:00 +0200 Subject: [PATCH 12/14] Fix preview reveal mask opacity and add customizable cover color --- main.py | 21 ++++--- templates/video.html | 134 +++++++++++++++++++++++++++++++++++-------- yt-dlp_serv.py | 28 +++++++-- 3 files changed, 147 insertions(+), 36 deletions(-) diff --git a/main.py b/main.py index 5212f3c..ab1f889 100644 --- a/main.py +++ b/main.py @@ -1537,6 +1537,8 @@ def _extract_country_reveal_mask( mask = mask.resize((map_w, map_h), Image.Resampling.BILINEAR) if mask.mode != "L": mask = mask.convert("L") + from PIL import ImageFilter + mask = mask.filter(ImageFilter.MaxFilter(5)).point(lambda p: 255 if p > 64 else 0) if mask.getbbox() is None: return "" @@ -1601,10 +1603,11 @@ def api_zoom_country_outline(): map_kind = str(request.args.get('map') or 'europe').strip().lower() key = str(request.args.get('key') or '').strip().lower() + solid = str(request.args.get('solid') or '').strip() in ('1', 'true', 'yes') if not key or map_kind not in ('europe', 'world'): return ('', 404) - cache_key = (map_kind, key) + cache_key = (map_kind, key, solid) with _ZOOM_CACHE_LOCK: cached = _ZOOM_OUTLINE_CACHE.get(cache_key) if cached is not None: @@ -1619,14 +1622,17 @@ def api_zoom_country_outline(): return ('', 404) w, h = mask.size - pw = 360 + pw = 720 if solid else 360 ph = max(1, int(round(h * (pw / w)))) small_mask = mask.resize((pw, ph), Image.Resampling.BILINEAR) - edge = ImageChops.subtract(small_mask.filter(ImageFilter.MaxFilter(5)), small_mask.filter(ImageFilter.MinFilter(3))) - fill_alpha = small_mask.point(lambda p: 45 if p > 128 else 0) - alpha = ImageChops.lighter(fill_alpha, edge.point(lambda p: min(255, int(p * 1.2)))) - - out = Image.new('RGBA', (pw, ph), (252, 211, 77, 255)) + if solid: + alpha = small_mask.filter(ImageFilter.MaxFilter(5)).point(lambda p: 255 if p > 64 else 0) + out = Image.new('RGBA', (pw, ph), (0, 0, 0, 255)) + else: + edge = ImageChops.subtract(small_mask.filter(ImageFilter.MaxFilter(5)), small_mask.filter(ImageFilter.MinFilter(3))) + fill_alpha = small_mask.point(lambda p: 45 if p > 128 else 0) + alpha = ImageChops.lighter(fill_alpha, edge.point(lambda p: min(255, int(p * 1.2)))) + out = Image.new('RGBA', (pw, ph), (252, 211, 77, 255)) out.putalpha(alpha) buf = io.BytesIO() out.save(buf, format='PNG') @@ -1737,6 +1743,7 @@ def make_video() -> tuple[object, int]: "zoom_country_key": zoom_country_key, "reveal_enabled": reveal_enabled, "reveal_time": reveal_time, + "reveal_color": str(data.get('reveal_color') or '#000000').strip(), "reveal_mask": reveal_mask, **({'render_id': data['render_id']} if data.get('render_id') is not None else {}), }, diff --git a/templates/video.html b/templates/video.html index 66cdccc..336efd5 100644 --- a/templates/video.html +++ b/templates/video.html @@ -927,15 +927,25 @@

Frame Com

@@ -1455,7 +1465,7 @@

'videoTitleInput', 'titleFontSelect', 'titleFontSize', 'titleFirstLineColor', 'titleOtherLinesColor', 'titleUppercase', 'visualEffects', 'introFadeToggle', 'mapZoomToggle', 'mapZoomX', 'mapZoomY', 'mapZoomCountry', 'mapZoomCountryKey', - 'mapZoomScale', 'mapZoomStart', 'mapZoomDuration', 'mapZoomOutToggle', 'mapZoomOutDuration', 'revealCountryToggle', 'revealTimeInput', + 'mapZoomScale', 'mapZoomStart', 'mapZoomDuration', 'mapZoomOutToggle', 'mapZoomOutDuration', 'revealCountryToggle', 'revealTimeInput', 'revealColorInput', 'topLeftStickerSelect', 'topRightStickerSelect', 'subscribeBadgeToggle', 'subscribeTextInput', 'subscribeDelayInput', 'watermarkTextInput', 'watermarkFontSelect', 'watermarkColor', 'watermarkStarsToggle', 'codecSelect']; @@ -2274,6 +2284,7 @@

zoom_out_duration: Number(document.getElementById('mapZoomOutDuration')?.value || 2.0), reveal_enabled: !!document.getElementById('revealCountryToggle')?.checked, reveal_time: Number(document.getElementById('revealTimeInput')?.value || 5.5), + reveal_color: document.getElementById('revealColorInput')?.value || '#000000', top_left_sticker: document.getElementById('topLeftStickerSelect').value, top_right_sticker: document.getElementById('topRightStickerSelect').value, subscribe_badge: document.getElementById('subscribeBadgeToggle').checked, @@ -2304,10 +2315,15 @@

} function updateRevealUI() { - const enabled = !!document.getElementById('revealCountryToggle')?.checked; + const zoomEnabled = !!document.getElementById('mapZoomToggle')?.checked; + const enabled = zoomEnabled && !!document.getElementById('revealCountryToggle')?.checked; const panel = document.getElementById('revealControlsPanel'); if (panel) panel.classList.toggle('hidden', !enabled); - if (typeof renderPreviewFrame === 'function') renderPreviewFrame(previewAnimTime); + if (typeof syncPreviewAnimationLoop === 'function') { + syncPreviewAnimationLoop(); + } else if (typeof renderPreviewFrame === 'function') { + renderPreviewFrame(previewAnimTime); + } } function updateMapZoomUI() { @@ -2501,23 +2517,73 @@

return `${String(mins).padStart(2, '0')}:${rem}`; } + function parseHexRgb(hexStr) { + const s = String(hexStr || '#000000').trim().replace(/^#/, ''); + if (/^[0-9a-fA-F]{6}$/.test(s)) { + return [parseInt(s.slice(0, 2), 16), parseInt(s.slice(2, 4), 16), parseInt(s.slice(4, 6), 16)]; + } + if (/^[0-9a-fA-F]{3}$/.test(s)) { + return [parseInt(s[0] + s[0], 16), parseInt(s[1] + s[1], 16), parseInt(s[2] + s[2], 16)]; + } + return [0, 0, 0]; + } + + function onRevealColorChange() { + const colorVal = document.getElementById('revealColorInput')?.value || '#000000'; + const hexLabel = document.getElementById('revealColorHex'); + if (hexLabel) hexLabel.textContent = colorVal.toLowerCase(); + revealMaskCache.key = ''; + revealMaskCache.loadingKey = ''; + updateRevealUI(); + saveVideoSettings(); + } + function ensureRevealMaskLoaded() { const map = document.getElementById('stageMapPreview'); if (!map || map.classList.contains('hidden') || !map.naturalWidth || !map.naturalHeight) return null; + const colorHex = (document.getElementById('revealColorInput')?.value || '#000000').toLowerCase(); + const hexLabel = document.getElementById('revealColorHex'); + if (hexLabel && hexLabel.textContent !== colorHex) hexLabel.textContent = colorHex; + const customDataUrl = (typeof window.revealMaskDataUrl === 'string' && window.revealMaskDataUrl) ? window.revealMaskDataUrl : ''; let maskKey = ''; let maskSrc = ''; if (customDataUrl) { - maskKey = `custom:${customDataUrl.slice(0, 64)}`; + maskKey = `custom:${customDataUrl.slice(0, 64)}:${colorHex}`; maskSrc = customDataUrl; } else { - const countryKey = (document.getElementById('mapZoomCountryKey')?.value || '').trim(); - if (!countryKey) return null; const aspect = map.naturalWidth / map.naturalHeight; const mapKind = aspect < 1.25 ? 'europe' : 'world'; - maskKey = `${mapKind}:${countryKey}`; - maskSrc = `/api/zoom_country_outline?map=${encodeURIComponent(mapKind)}&key=${encodeURIComponent(countryKey)}`; + let countryKey = (document.getElementById('mapZoomCountryKey')?.value || '').trim(); + if (!countryKey) { + if (!zoomCountriesCache) { + loadZoomCountries().then(() => renderPreviewFrame(previewAnimTime)); + return null; + } + const list = zoomCountriesCache[mapKind]; + const zx = parseFloat(document.getElementById('mapZoomX')?.value || '0.807'); + const zy = parseFloat(document.getElementById('mapZoomY')?.value || '0.358'); + if (Array.isArray(list) && list.length) { + let best = null; + let bestDist = Infinity; + for (const c of list) { + const d = (c.x - zx) ** 2 + (c.y - zy) ** 2; + if (d < bestDist) { + bestDist = d; + best = c; + } + } + if (best && bestDist <= 0.18 * 0.18) { + countryKey = best.key || ''; + const keyEl = document.getElementById('mapZoomCountryKey'); + if (keyEl && countryKey) keyEl.value = countryKey; + } + } + } + if (!countryKey) return null; + maskKey = `${mapKind}:${countryKey}:${colorHex}`; + maskSrc = `/api/zoom_country_outline?map=${encodeURIComponent(mapKind)}&key=${encodeURIComponent(countryKey)}&solid=1`; } if (revealMaskCache.key === maskKey && revealMaskCache.silhouette) { @@ -2527,6 +2593,7 @@

return null; } + const [cr, cg, cb] = parseHexRgb(colorHex); revealMaskCache.loadingKey = maskKey; const img = new Image(); img.crossOrigin = 'anonymous'; @@ -2549,10 +2616,10 @@

const idx = (y * w + x) * 4; const a = data[idx + 3]; if (a > 20) { - data[idx] = 14; - data[idx + 1] = 14; - data[idx + 2] = 22; - data[idx + 3] = Math.round(a * 0.95); + data[idx] = cr; + data[idx + 1] = cg; + data[idx + 2] = cb; + data[idx + 3] = 255; sumX += x; sumY += y; count++; @@ -2632,8 +2699,11 @@

} const zoomEnabled = !!document.getElementById('mapZoomToggle')?.checked; - const revealEnabled = !!document.getElementById('revealCountryToggle')?.checked; - const rTime = Number(document.getElementById('revealTimeInput')?.value || 5.5); + const revealEnabled = zoomEnabled && !!document.getElementById('revealCountryToggle')?.checked; + const zStartVal = Number(document.getElementById('mapZoomStart')?.value || 1.5); + const zDurVal = Math.max(0.1, Number(document.getElementById('mapZoomDuration')?.value || 2.5)); + const rawRTime = Number(document.getElementById('revealTimeInput')?.value || 5.5); + const rTime = zoomEnabled ? Math.max(zStartVal + zDurVal + 0.5, rawRTime) : Math.max(0.2, rawRTime); const map = document.getElementById('stageMapPreview'); const area = document.getElementById('stageMapArea'); @@ -2709,17 +2779,19 @@

const r = Math.max(5, Math.min(11, mw * 0.011)); const gap = r * 2.8; const startX = cx - ((dotCount - 1) * gap) / 2; + const [cr, cg, cb] = parseHexRgb(document.getElementById('revealColorInput')?.value || '#000000'); + const isLightCover = (0.299 * cr + 0.587 * cg + 0.114 * cb) > 175; for (let i = 0; i < dotCount; i++) { const dx = startX + i * gap; ctx.beginPath(); ctx.arc(dx, cy, r, 0, Math.PI * 2); - ctx.fillStyle = '#ffffff'; - ctx.shadowColor = 'rgba(0,0,0,0.75)'; + ctx.fillStyle = isLightCover ? '#0f172a' : '#ffffff'; + ctx.shadowColor = isLightCover ? 'rgba(255,255,255,0.75)' : 'rgba(0,0,0,0.75)'; ctx.shadowBlur = 8; ctx.fill(); ctx.shadowBlur = 0; ctx.lineWidth = 2; - ctx.strokeStyle = 'rgba(15,23,42,0.85)'; + ctx.strokeStyle = isLightCover ? 'rgba(255,255,255,0.85)' : 'rgba(15,23,42,0.85)'; ctx.stroke(); } } @@ -2758,10 +2830,21 @@

previewRafId = requestAnimationFrame(stepPreviewAnimation); } + function hasActivePreviewAnimations() { + const zoomEnabled = !!document.getElementById('mapZoomToggle')?.checked; + return !!( + document.getElementById('introFadeToggle')?.checked + || document.getElementById('subscribeBadgeToggle')?.checked + || document.getElementById('watermarkStarsToggle')?.checked + || zoomEnabled + ); + } + function syncPreviewAnimationLoop() { syncPreviewTransportUI(); const player = document.getElementById('renderedVideoPlayer'); - const shouldRun = previewAnimPlaying && previewVisible && !document.hidden && player && player.classList.contains('hidden'); + const hasAnims = hasActivePreviewAnimations(); + const shouldRun = hasAnims && previewAnimPlaying && previewVisible && !document.hidden && player && player.classList.contains('hidden'); if (shouldRun && previewRafId === null) { previewLastTs = null; previewRafId = requestAnimationFrame(stepPreviewAnimation); @@ -2771,6 +2854,7 @@

previewRafId = null; } previewLastTs = null; + if (!hasAnims) previewAnimTime = 0; renderPreviewFrame(previewAnimTime); } } diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index c6b2256..4d68332 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -579,11 +579,24 @@ def _decode_reveal_mask(raw_mask: object, box_w: int, box_h: int): return mask_arr[..., None] +def _parse_reveal_color(raw_color: object) -> tuple[int, int, int]: + """Parse a hex color string (e.g. ``#000000``) into an RGB tuple, defaulting to black.""" + if not isinstance(raw_color, str): + return (0, 0, 0) + s = raw_color.strip().lstrip('#') + if len(s) == 3 and all(c in '0123456789abcdefABCDEF' for c in s): + s = ''.join(c * 2 for c in s) + if len(s) == 6 and all(c in '0123456789abcdefABCDEF' for c in s): + return (int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16)) + return (0, 0, 0) + + def _render_reveal_dot_overlays( box_w: int, box_h: int, cx: float, cy: float, + cover_rgb: tuple[int, int, int] = (0, 0, 0), ) -> dict[int, tuple[int, int, int, int, object]]: """Pre-render 1-, 2-, and 3-dot RGBA overlays centered at ``(cx, cy)`` using 4x supersampling.""" import numpy as np @@ -603,6 +616,10 @@ def _render_reveal_dot_overlays( patch_w = max(1, x1 - x0) patch_h = max(1, y1 - y0) + lum = 0.299 * cover_rgb[0] + 0.587 * cover_rgb[1] + 0.114 * cover_rgb[2] + dot_fill = (15, 23, 42, 255) if lum > 175 else (255, 255, 255, 255) + ring_fill = (255, 255, 255, 255) if lum > 175 else (10, 12, 20, 255) + ss = 4 overlays: dict[int, tuple[int, int, int, int, object]] = {} for count in (1, 2, 3): @@ -615,11 +632,11 @@ def _render_reveal_dot_overlays( ri = dot_r * ss draw.ellipse( (dot_x - ro, dot_y - ro, dot_x + ro, dot_y + ro), - fill=(10, 12, 20, 255), + fill=ring_fill, ) draw.ellipse( (dot_x - ri, dot_y - ri, dot_x + ri, dot_y + ri), - fill=(255, 255, 255, 255), + fill=dot_fill, ) patch = hi_img.resize((patch_w, patch_h), Image.Resampling.LANCZOS) overlays[count] = (y0, y1, x0, x1, np.array(patch, dtype=np.uint8)) @@ -740,6 +757,7 @@ def _build_reveal_map_clip( zoom_start: float, zoom_duration: float, reveal_time_raw: object, + reveal_color: object = "#000000", ): """Build a dynamic RGB + mask ``VideoClip`` for the country reveal animation.""" import numpy as np @@ -750,9 +768,10 @@ def _build_reveal_map_clip( base_pil = raw_map.convert('RGBA').resize((box_w, box_h), Image.Resampling.LANCZOS) base_rgba = np.array(base_pil, dtype=np.uint8) + cover_r, cover_g, cover_b = _parse_reveal_color(reveal_color) map_visible = (base_rgba[:, :, 3:4] > 0).astype(np.float32) eff_mask = mask_f * map_visible - black_pixel = np.array([14.0, 14.0, 22.0, 255.0], dtype=np.float32).reshape(1, 1, 4) + black_pixel = np.array([float(cover_r), float(cover_g), float(cover_b), 255.0], dtype=np.float32).reshape(1, 1, 4) base_f = base_rgba.astype(np.float32) black_f = base_f * (1.0 - eff_mask) + black_pixel * eff_mask delta_f = black_f - base_f @@ -799,7 +818,7 @@ def _to_rgb_and_mask(composed: np.ndarray) -> tuple[object, object]: dot_cx = float(xs[best]) dot_cy = float(ys[best]) - dot_overlays = _render_reveal_dot_overlays(box_w, box_h, dot_cx, dot_cy) + dot_overlays = _render_reveal_dot_overlays(box_w, box_h, dot_cx, dot_cy, (cover_r, cover_g, cover_b)) dot_rgba_frames = { count: _compose_rgba(_alpha_composite_patch(black_rgba, *dot_overlays[count])) for count in (1, 2, 3) @@ -1138,6 +1157,7 @@ def _decode_optional_image(field: str, label: str): zoom_start, zoom_duration, data.get('reveal_time'), + data.get('reveal_color', '#000000'), ) if effects: map_y -= 24 From 7c89b35cbd0c5db0e093e3c65ed502dfdb96076a Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 20:46:05 +0200 Subject: [PATCH 13/14] Update video studio reveal/zoom preview and tests --- main.py | 5 +++- templates/video.html | 21 ++++++++++------- tests/browser/test_video_studio.py | 38 ++++++++++++++++++++++++++++++ tests/test_web.py | 20 ++++++++++++++++ yt-dlp_serv.py | 2 +- 5 files changed, 76 insertions(+), 10 deletions(-) diff --git a/main.py b/main.py index ab1f889..8f6db57 100644 --- a/main.py +++ b/main.py @@ -1684,6 +1684,9 @@ def make_video() -> tuple[object, int]: if isinstance(raw_reveal, str) else bool(raw_reveal) ) + raw_zoom = data.get('zoom_enabled', False) + zoom_enabled = raw_zoom.strip().lower() in _TRUTHY if isinstance(raw_zoom, str) else bool(raw_zoom) + reveal_enabled = zoom_enabled and reveal_enabled reveal_time = data.get('reveal_time', None) reveal_mask = '' if reveal_enabled and map_b64: @@ -1732,7 +1735,7 @@ def make_video() -> tuple[object, int]: "subscribe_text": data.get('subscribe_text', 'Subscribe!'), "subscribe_delay": data.get('subscribe_delay', 2.5), "intro_fade": data.get('intro_fade', False), - "zoom_enabled": data.get('zoom_enabled', False), + "zoom_enabled": zoom_enabled, "zoom_x": data.get('zoom_x', 0.80), "zoom_y": data.get('zoom_y', 0.35), "zoom_scale": data.get('zoom_scale', 2.0), diff --git a/templates/video.html b/templates/video.html index 336efd5..def3683 100644 --- a/templates/video.html +++ b/templates/video.html @@ -873,7 +873,7 @@

Frame Com Smooth intro fade-in from black (0.0s → 0.8s)
+
+ YouTube upload +
+

Connect your channel once, then upload automatically after rendering. Credentials stay on the server.

+ +

Web application redirect URI: Loading…. Desktop app files work on localhost.

+
+ + +
+

Checking connection…

+ + + + + + + +

+ +
+
+