From 215447b8c295fd3846fe538a707679726a4dd5b6 Mon Sep 17 00:00:00 2001 From: bibed234 Date: Sat, 14 Nov 2026 15:31:49 +0200 Subject: [PATCH 1/4] feat: add Shorts auto-montage overlays, auto-themed stickers, and AI map auto-coloring --- main.py | 153 ++++- map/auto_map.py | 121 ++++ templates/index.html | 543 +++++++++++++++--- templates/video.html | 1116 +++++++++++++++++++++++++++++++++++- tests/test_auto_map.py | 30 + tests/test_video_render.py | 160 ++++++ tests/test_web.py | 16 + yt-dlp_serv.py | 1000 +++++++++++++++++++++++++++++++- 8 files changed, 3017 insertions(+), 122 deletions(-) diff --git a/main.py b/main.py index 4e1bd9f..c95398e 100644 --- a/main.py +++ b/main.py @@ -41,7 +41,11 @@ os.makedirs(CUT_DIR, exist_ok=True) from dotenv import dotenv_values -from map.auto_map import auto_map +from map.auto_map import ( + auto_map, + _auto_fill_from_ai, + LAST_GENERATED_MAP_STATE, +) from flask import Flask, request, jsonify, send_file, render_template, Response @@ -86,14 +90,28 @@ def video_title_preview(): import requests data = request.get_json(silent=True) or {} + allowed_keys = ( + 'video_title', + 'title_font', + 'title_font_size', + 'title_first_line_color', + 'title_other_lines_color', + 'title_uppercase', + 'visual_effects', + 'preview_kind', + 'watermark_text', + 'watermark_color', + 'watermark_font', + 'subscribe_text', + 'sticker_kind', + 'sticker_side', + 'allow_remote_stickers', + ) try: # Preview and final rendering share the worker's title styling options. response = requests.post( 'http://yt-dlp-worker:8080/api/video_title_preview', - json={key: data[key] for key in ('video_title', 'title_font', 'title_font_size', - 'title_first_line_color', 'title_other_lines_color', - 'visual_effects', 'preview_kind', 'watermark_text', - 'watermark_color', 'watermark_font') if key in data}, + json={key: data[key] for key in allowed_keys if key in data}, timeout=15, ) except requests.RequestException: @@ -136,6 +154,60 @@ def api_status(): return jsonify({"needs_api_key": needs_api_key}) +def _build_analysis_from_ai( + ai_answer: dict[str, object], + mode: str = "auto", +) -> dict[str, object]: + """Build UI-friendly color rules and stats directly from AI map values.""" + vals = [v for v in ai_answer.values() if v is not None and str(v).strip() != ""] + num_vals: list[int] = [] + for v in vals: + if isinstance(v, bool): + continue + try: + num_vals.append(int(float(str(v).replace(",", "").strip()))) + except (ValueError, TypeError): + pass + + resolved_mode = mode if mode in ("number", "text") else ( + "number" if vals and len(num_vals) >= max(1, int(len(vals) * 0.6)) else "text" + ) + auto_txt, auto_num = _auto_fill_from_ai(ai_answer, resolved_mode) + + ui_txt_rules = [ + {"key": str(k), "hex": f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}", "alpha": c[3]} + for k, c in auto_txt.items() + ] + ui_num_rules = [ + {"low": lo, "high": hi, "hex": f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}", "alpha": c[3]} + for (lo, hi), c in auto_num.items() + ] + return { + "detected_type": resolved_mode, + "resolved_mode": resolved_mode, + "resolved_theme": "auto", + "filling_txt": {str(k): list(c) for k, c in auto_txt.items()}, + "filling_num": {f"({lo}, {hi})": list(c) for (lo, hi), c in auto_num.items()}, + "ui_txt_rules": ui_txt_rules, + "ui_num_rules": ui_num_rules, + "label_style": { + "text_color": "#ffffff", + "stroke_color": "#090d16", + "stroke_width": 15, + "auto_fit": True, + "recommended_font": "Bips.ttf" if resolved_mode == "number" else "DIN Condensed.ttf", + "recommended_gsm": 15, + }, + "stats": { + "total_regions": len(vals), + "unique_values": len({str(v).strip().lower() for v in vals}), + "min_value": min(num_vals) if num_vals else None, + "max_value": max(num_vals) if num_vals else None, + "sample_values": [str(v) for v in vals[:8]], + }, + } + + @app.route('/api/generate/', methods=['POST']) @app.route('/api/generate', methods=['POST']) def generate(): @@ -207,10 +279,67 @@ def generate(): # Encode the PNG buffer as a data URL the browser can load directly. encoded = base64.b64encode(buffer.getvalue()).decode('ascii') - return jsonify({ + resp_payload: dict[str, object] = { "status": "success", "command": command, "image_url": f"data:image/png;base64,{encoded}", + } + ai_vals = LAST_GENERATED_MAP_STATE.get("ai_answer") + if isinstance(ai_vals, dict) and ai_vals: + resp_payload["map_values"] = ai_vals + resp_payload["analysis"] = _build_analysis_from_ai(ai_vals, str(data.get("mode") or "auto")) + + return jsonify(resp_payload) + + +@app.route('/api/analyze_map/', methods=['POST']) +@app.route('/api/analyze_map', methods=['POST']) +def api_analyze_map(): + """Inspect AI map values (or topic sample) and auto-determine colors for numbers or words.""" + data = request.get_json(silent=True) or {} + mode = str(data.get('mode') or 'auto') + topic = str(data.get('topic') or '').strip() + + map_values = data.get('map_values') + if not isinstance(map_values, dict) or not map_values: + cached = LAST_GENERATED_MAP_STATE.get("ai_answer") + if isinstance(cached, dict) and cached: + map_values = cached + + if isinstance(map_values, dict) and map_values: + analysis = _build_analysis_from_ai(map_values, mode=mode) + return jsonify({ + "status": "success", + "source": "ai_answer", + "topic": topic, + "map_values": map_values, + "analysis": analysis, + }) + + t_low = topic.lower() + if any(w in t_low for w in ("nicholas", "christmas", "santa", "holiday", "dec")): + sample_values: dict[str, object] = { + "ukraine": "6 Dec", "poland": "6 Dec", "germany": "6 Dec", "france": "6 Dec", + "netherlands": "5 Dec", "russia": "19 Dec", "serbia": "19 Dec", "spain": "6 Jan", + } + elif mode == "text": + sample_values = { + "ukraine": "Yes", "poland": "Yes", "germany": "Yes", "france": "No", + "spain": "Yes", "italy": "Partial", "united_kingdom": "No", + } + else: + sample_values = { + "germany": 84, "france": 68, "italy": 59, "spain": 48, "ukraine": 38, + "poland": 37, "romania": 19, "netherlands": 18, "sweden": 10, "estonia": 1, + } + + analysis = _build_analysis_from_ai(sample_values, mode=mode) + return jsonify({ + "status": "success", + "source": "topic_preview", + "topic": topic, + "map_values": sample_values, + "analysis": analysis, }) @@ -353,11 +482,23 @@ def make_video() -> tuple[object, int]: "title_font_size": data.get('title_font_size', 100), "title_first_line_color": data.get('title_first_line_color', '#ffffff'), "title_other_lines_color": data.get('title_other_lines_color', '#ffe735'), + "title_uppercase": data.get('title_uppercase', True), "visual_effects": data.get('visual_effects', True), "watermark_image": data.get('watermark_image', ''), "watermark_text": data.get('watermark_text', ''), "watermark_color": data.get('watermark_color', '#a4e9ee'), "watermark_font": data.get('watermark_font', 'DIN Condensed.ttf'), + "watermark_stars": data.get('watermark_stars', False), + "watermark_stars_image": data.get('watermark_stars_image', ''), + "top_left_sticker": data.get('top_left_sticker', 'none'), + "top_right_sticker": data.get('top_right_sticker', 'none'), + "top_left_sticker_image": data.get('top_left_sticker_image', ''), + "top_right_sticker_image": data.get('top_right_sticker_image', ''), + "subscribe_badge": data.get('subscribe_badge', False), + "subscribe_image": data.get('subscribe_image', ''), + "subscribe_text": data.get('subscribe_text', 'Subscribe!'), + "subscribe_delay": data.get('subscribe_delay', 2.5), + "intro_fade": data.get('intro_fade', False), }, # Video rendering (moviepy/ffmpeg) can take a while - allow more time. timeout=300, diff --git a/map/auto_map.py b/map/auto_map.py index 46b829c..34127e0 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -15,6 +15,7 @@ import random import io import math +from collections import Counter from pathlib import Path from PIL import Image, ImageDraw, ImageFont @@ -24,6 +25,111 @@ from . import log +LAST_GENERATED_MAP_STATE: dict[str, object] = {} + +_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 +) + +_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), +} + + +def _parse_short_number(val: object) -> float | None: + """Parse plain numbers or short-form numbers like '10k', '2.5M', '1B'.""" + if isinstance(val, bool) or val is None: + return None + s = str(val).replace(",", "").replace(" ", "").strip() + if not s: + return None + mult = 1.0 + low = s.lower() + if low.endswith("k"): + mult, s = 1_000.0, s[:-1] + elif low.endswith("m"): + mult, s = 1_000_000.0, s[:-1] + elif low.endswith("b"): + mult, s = 1_000_000_000.0, s[:-1] + try: + num = float(s) * mult + except ValueError: + return None + return num if math.isfinite(num) else None + + +def _auto_fill_from_ai( + ai_answer: dict[str, object], + mode: str, +) -> tuple[dict[str, tuple[int, int, int, int]], dict[tuple[int, int], tuple[int, int, int, int]]]: + """Inspect AI response values (numbers, short-form numbers, or words) and pick colors.""" + auto_txt: dict[str, tuple[int, int, int, int]] = {} + auto_num: dict[tuple[int, int], tuple[int, int, int, int]] = {} + + if mode == "number": + nums: list[int] = [] + for val in ai_answer.values(): + parsed = _parse_short_number(val) + if parsed is not None: + nums.append(int(round(parsed))) + if nums: + nums.sort() + low_start = min(0, nums[0] - 1) if nums[0] <= 10 else nums[0] - 1 + buckets = min(5, max(1, len(set(nums)))) + bounds = [low_start] + for i in range(1, buckets): + q = nums[int(round((len(nums) - 1) * (i / buckets)))] + bounds.append(max(bounds[-1] + 1, q)) + bounds.append(max(bounds[-1] + 1, nums[-1])) + for i in range(buckets): + auto_num[(bounds[i], bounds[i + 1])] = _AUTO_PALETTE[i % len(_AUTO_PALETTE)] + else: + labels = [str(v).strip() for v in ai_answer.values() if v is not None and str(v).strip()] + parsed_pairs = [(lbl, _parse_short_number(lbl)) for lbl in labels] + numeric_vals = sorted(num for _, num in parsed_pairs if num is not None) + + # In text mode with short_form (e.g. '10k', '2.5M'), group numeric labels into + # gradient buckets instead of giving every distinct number its own random color. + if numeric_vals and len(numeric_vals) >= max(2, int(len(labels) * 0.6)): + buckets = min(5, max(1, len(set(numeric_vals)))) + thresholds = [ + numeric_vals[int(round((len(numeric_vals) - 1) * (i / buckets)))] + for i in range(1, buckets) + ] + for lbl, num in parsed_pairs: + if num is not None: + b_idx = sum(1 for t in thresholds if num > t) + auto_txt[lbl] = _AUTO_PALETTE[b_idx % len(_AUTO_PALETTE)] + else: + auto_txt.setdefault(lbl, _SEMANTIC_COLORS.get(lbl.lower(), _AUTO_PALETTE[5])) + else: + canonical: dict[str, str] = {} + for lbl in labels: + canonical.setdefault(lbl.lower(), lbl) + idx = 0 + for low_lbl, _ in Counter(lbl.lower() for lbl in labels).most_common(): + orig = canonical[low_lbl] + if low_lbl in _SEMANTIC_COLORS: + auto_txt[orig] = _SEMANTIC_COLORS[low_lbl] + else: + auto_txt[orig] = _AUTO_PALETTE[idx % len(_AUTO_PALETTE)] + idx += 1 + + return auto_txt, auto_num + + def _numeric_extrema(values): """Return region names for finite numeric extrema, or None if absent.""" numeric = {} @@ -136,6 +242,21 @@ def get_font(size): log.success(f"Got information from AI ({len(ai_answer)} entries)") + # Auto-pick colors based on the numbers or words returned by AI when filling.json has no rules + auto_txt, auto_num = _auto_fill_from_ai(ai_answer, mode) + if not filling_txt and auto_txt: + filling_txt = auto_txt + filling_txt_ci = {str(k).strip().lower(): v for k, v in filling_txt.items()} + if not filling_num and auto_num: + filling_num = auto_num + + LAST_GENERATED_MAP_STATE.clear() + LAST_GENERATED_MAP_STATE.update({ + "ai_answer": dict(ai_answer), + "filling_txt": {str(k): list(v) for k, v in (filling_txt or auto_txt).items()}, + "filling_num": {f"({lo}, {hi})": list(v) for (lo, hi), v in (filling_num or auto_num).items()}, + }) + most_least = None extrema = _numeric_extrema(ai_answer) if optional_feature == "show_most_least" else None if optional_feature == "show_most_least" and extrema is None: diff --git a/templates/index.html b/templates/index.html index 7cba7f2..29e9b3e 100644 --- a/templates/index.html +++ b/templates/index.html @@ -540,14 +540,18 @@

-
- Color Filling Rules - 6 rules +
+ Color & Label Style + Auto-Detect ON
-

Configure filling_txt & filling_num swatches

+

Auto-detects map numbers/words, palette & text style

-
+
+ @@ -841,79 +845,174 @@

Color Filling Studio

-
- -
- -
-
+
+ +
+
+
-
- -
-
-
-

- - Numeric Range Rules (filling_num) -

-

Matches low < value <= high -> RGBA fill color

-
- +
+
+ + +
+
+ Click "Detect from Map / Topic" or generate a map to auto-populate rules.
-
- -
-
-
- - - Live filling.json Output - -
- -
+
+
+ + +
+
+
+

+ + Numeric Range Rules (filling_num) +

+

Matches low < value <= high -> RGBA fill color

+
+ +
+
+
+
+ + +
+ +
+
+ + + Map Label Style (Auto-Tuned) + +
+
+
+ Text Fill +
+ + #ffffff +
+
+
+ Outline +
+ + #090d16 +
+
+
+
+ Stroke Width + + 15px +
+
+ + Font: Bips.ttf +
+
+ + +
+
+ + + Live filling.json Output + +
+ + +
+
+

                         
-

                     
-
+
- +
+ + +
@@ -954,6 +1053,16 @@

let fillingTxtRules = JSON.parse(JSON.stringify(DEFAULT_FILLING_TXT)); let fillingNumRules = JSON.parse(JSON.stringify(DEFAULT_FILLING_NUM)); + let labelStyleConfig = { + recommended_font: "Bips.ttf", + recommended_gsm: 15, + text_color: "#ffffff", + stroke_color: "#090d16", + stroke_width: 15, + auto_fit: true + }; + let lastMapValues = null; + let lastMapAnalysis = null; // --- Initialize on Load --- window.addEventListener('DOMContentLoaded', () => { @@ -1122,6 +1231,20 @@

} // --- Get Current Form Values --- + function buildFillingDictionaries() { + const filling_txt = {}; + const filling_num = {}; + fillingTxtRules.forEach(r => { + if (r.key && r.key.trim()) { + filling_txt[r.key.trim()] = hexToRgbArray(r.hex, r.alpha); + } + }); + fillingNumRules.forEach(r => { + filling_num[`(${Number(r.low) || 0}, ${Number(r.high) || 0})`] = hexToRgbArray(r.hex, r.alpha); + }); + return { filling_txt, filling_num }; + } + function getFormState() { const mode = document.querySelector('input[name="mode"]:checked')?.value || 'text'; const mapType = document.querySelector('input[name="map_type"]:checked')?.value || 'default'; @@ -1131,8 +1254,26 @@

const font = document.getElementById('fontSelect').value; const topic = document.getElementById('topicInput').value.trim(); const apiKey = document.getElementById('apiKeyInput').value.trim(); - - return { mode, map_type: mapType, gsm, extra_option: extraOption, model, font, topic, api_key: apiKey }; + const autoStyleEl = document.getElementById('autoStyleFromMapToggle'); + const auto_style = autoStyleEl ? !!autoStyleEl.checked : true; + const palette_theme = document.getElementById('fillingPaletteTheme')?.value || 'auto'; + const { filling_txt, filling_num } = buildFillingDictionaries(); + + return { + mode, + map_type: mapType, + gsm, + extra_option: extraOption, + model, + font, + topic, + api_key: apiKey, + auto_style, + palette_theme, + filling_txt, + filling_num, + label_style: { ...labelStyleConfig } + }; } // --- Sync Global Size Modifier Slider & Number Input --- @@ -1359,6 +1500,16 @@

if (result.command) logToConsole(`[Server] ${result.command}`, 'info'); logToConsole(`[Success] Map generated and loaded (${describeDataUrl(result.image_url)})`, 'success'); + if (result.map_values) { + lastMapValues = result.map_values; + } + if (result.analysis) { + applyAnalysisToFillingStudio(result.analysis, result.map_values, false); + const st = result.analysis.stats || {}; + const ls = result.analysis.label_style || {}; + logToConsole(`[Auto-Style] Detected ${result.analysis.detected_type} map (${st.total_regions || 0} regions, ${st.unique_values || 0} unique values) -> theme "${result.analysis.resolved_theme}", recommended font "${ls.recommended_font || 'Bips.ttf'}"`, 'info'); + } + // Display actual image returned by Flask (data URL) const imgEl = document.getElementById('serverMapImage'); const emptyEl = document.getElementById('emptyState'); @@ -1372,7 +1523,7 @@

try { const blob = await (await fetch(result.image_url)).blob(); await StudioStorage.setAsset('latest-map', new File([blob], 'generated-map.png', {type: 'image/png'})); - showToast("Map generated! It is ready in Video Studio.", "success"); + showToast("Map generated & auto-styled! Ready in Video Studio.", "success"); } catch (error) { showToast("Map generated, but automatic transfer could not be saved. Download it to use in Video Studio.", "warn"); } @@ -1434,7 +1585,7 @@

showToast("Downloading PNG map...", "success"); } - // --- Color Filling Studio (`filling_txt` & `filling_num`) --- + // --- Color Filling Studio (`filling_txt`, `filling_num`, & Smart Map Inspector) --- function hexToRgbArray(hex, alpha = 255) { const clean = (hex || '#6366f1').replace('#', ''); const num = parseInt(clean, 16); @@ -1456,7 +1607,216 @@

modal.classList.add('hidden'); modal.classList.remove('flex'); if (notify) { - showToast("Color filling palette updated", "success"); + showToast("Color filling & label style saved", "success"); + } + } + + function onAutoStyleToggleChange() { + renderFillingStudio(); + const isAuto = !!document.getElementById('autoStyleFromMapToggle')?.checked; + showToast(isAuto ? "Smart Auto-Detect from Map enabled" : "Manual custom rules mode active", "info"); + } + + function onPaletteThemeChange() { + if (lastMapValues && Object.keys(lastMapValues).length > 0) { + autoDetectMapColorsAndStyle(true); + } else { + renderFillingStudio(); + } + } + + function updateLabelStyleField(field, val) { + if (field === 'stroke_width') { + labelStyleConfig.stroke_width = Math.max(2, Math.min(25, parseInt(val, 10) || 15)); + } else if (field === 'auto_fit') { + labelStyleConfig.auto_fit = !!val; + } else { + labelStyleConfig[field] = val; + } + renderFillingStudio(); + } + + function applyRecommendedFontAndSize() { + const recFont = labelStyleConfig.recommended_font || 'Bips.ttf'; + const recGsm = typeof labelStyleConfig.recommended_gsm === 'number' ? labelStyleConfig.recommended_gsm : 15; + const fontSelect = document.getElementById('fontSelect'); + if (fontSelect && Array.from(fontSelect.options).some(o => o.value === recFont)) { + fontSelect.value = recFont; + } + syncGsm(recGsm); + showToast(`Applied recommended style: ${recFont} (GSM ${recGsm})`, 'success'); + } + + function applyAnalysisToFillingStudio(analysis, mapValues = null, notifyToast = true) { + if (!analysis) return; + lastMapAnalysis = analysis; + if (mapValues && typeof mapValues === 'object') { + lastMapValues = mapValues; + } + if (Array.isArray(analysis.ui_txt_rules) && analysis.ui_txt_rules.length > 0) { + fillingTxtRules = analysis.ui_txt_rules.map(r => ({ + key: r.key, + hex: r.hex || '#6366f1', + alpha: typeof r.alpha === 'number' ? r.alpha : 255 + })); + } + if (Array.isArray(analysis.ui_num_rules) && analysis.ui_num_rules.length > 0) { + fillingNumRules = analysis.ui_num_rules.map(r => ({ + low: Number(r.low) || 0, + high: Number(r.high) || 0, + hex: r.hex || '#38bdf8', + alpha: typeof r.alpha === 'number' ? r.alpha : 255 + })); + } + if (analysis.label_style) { + labelStyleConfig = { + ...labelStyleConfig, + ...analysis.label_style + }; + } + + const statsBar = document.getElementById('detectedMapStatsBar'); + if (statsBar) { + const st = analysis.stats || {}; + const samples = Array.isArray(st.sample_values) ? st.sample_values.slice(0, 6).join(', ') : ''; + const rangeBadge = (st.min_value !== null && st.min_value !== undefined) + ? `Range: ${st.min_value} .. ${st.max_value}` + : ''; + statsBar.innerHTML = ` + Type: ${analysis.detected_type || 'auto'} + Theme: ${analysis.resolved_theme || 'auto'} + ${st.total_regions || 0} regions (${st.unique_values || 0} unique) + ${rangeBadge} + ${samples ? `On Map: ${samples}` : ''} + `; + } + + renderFillingStudio(); + if (notifyToast) { + showToast(`Detected ${analysis.detected_type} map values -> applied ${analysis.resolved_theme} palette & style!`, 'success'); + } + } + + async function autoDetectMapColorsAndStyle(insideModal = false) { + const state = getFormState(); + const btnIcon = document.getElementById('autoDetectMapIcon'); + if (btnIcon) btnIcon.className = 'fa-solid fa-circle-notch fa-spin text-[11px]'; + + try { + const serverImg = document.getElementById('serverMapImage'); + const hasMapImg = serverImg && !serverImg.classList.contains('hidden') && serverImg.src && serverImg.src.startsWith('data:image/'); + const payload = { + topic: state.topic, + mode: state.mode, + map_type: state.map_type, + palette_theme: document.getElementById('fillingPaletteTheme')?.value || 'auto', + api_key: state.api_key, + model: state.model, + prefer_cached: true, + map_values: lastMapValues, + image_data: (!lastMapValues && hasMapImg) ? serverImg.src : undefined + }; + + const res = await fetch('/api/analyze_map', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + const data = await res.json(); + if (!res.ok || data.status !== 'success') { + throw new Error(data.error || 'Could not analyze map'); + } + applyAnalysisToFillingStudio(data.analysis, data.map_values, true); + if (!insideModal) { + openFillingStudio(); + } + } catch (err) { + logToConsole(`[Auto-Style] ${err.message}`, 'warn'); + showToast(err.message || 'Auto-detect failed', 'warn'); + } finally { + if (btnIcon) btnIcon.className = 'fa-solid fa-magnifying-glass-chart text-[11px]'; + } + } + + async function handleInspectUploadedMapImage(event) { + const file = event.target?.files?.[0]; + if (!file) return; + const reader = new FileReader(); + reader.onload = async () => { + const dataUrl = reader.result; + // Show the inspected map on the stage as well + const imgEl = document.getElementById('serverMapImage'); + const emptyEl = document.getElementById('emptyState'); + if (imgEl) { + imgEl.src = dataUrl; + imgEl.classList.remove('hidden'); + } + if (emptyEl) emptyEl.classList.add('hidden'); + + showToast(`Inspecting "${file.name}" for numbers, words & colors...`, 'info'); + const state = getFormState(); + try { + const res = await fetch('/api/analyze_map', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + image_data: dataUrl, + topic: state.topic, + mode: 'auto', + map_type: state.map_type, + palette_theme: document.getElementById('fillingPaletteTheme')?.value || 'auto', + api_key: state.api_key, + model: state.model, + prefer_cached: false + }) + }); + const data = await res.json(); + if (!res.ok || data.status !== 'success') { + throw new Error(data.error || 'Map image inspection failed'); + } + applyAnalysisToFillingStudio(data.analysis, data.map_values, true); + logToConsole(`[Map Inspector] Analyzed uploaded map "${file.name}" -> detected ${data.analysis?.detected_type} values & "${data.analysis?.resolved_theme}" theme`, 'success'); + } catch (err) { + showToast(err.message || 'Could not inspect map image', 'error'); + } finally { + event.target.value = ''; + } + }; + reader.readAsDataURL(file); + } + + async function restyleCurrentMapFromStudio() { + const state = getFormState(); + const btn = document.getElementById('restyleCurrentMapBtn'); + if (btn) btn.disabled = true; + try { + const res = await fetch('/api/restyle_map', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ...state, + auto_style: false, + map_values: lastMapValues + }) + }); + const data = await res.json(); + if (!res.ok || data.status !== 'success') { + throw new Error(data.error || 'Generate a map first to re-paint it live.'); + } + const imgEl = document.getElementById('serverMapImage'); + const emptyEl = document.getElementById('emptyState'); + if (imgEl) { + imgEl.src = data.image_url; + imgEl.classList.remove('hidden'); + } + if (emptyEl) emptyEl.classList.add('hidden'); + logToConsole('[Auto-Style] Re-painted active map with updated Color Filling Studio rules & typography style.', 'success'); + showToast('Map re-painted with new colors & label style!', 'success'); + closeFillingStudio(false); + } catch (err) { + showToast(err.message || 'Could not re-paint map', 'warn'); + } finally { + if (btn) btn.disabled = false; } } @@ -1466,6 +1826,27 @@

const jsonPreview = document.getElementById('fillingJsonPreview'); const miniSwatches = document.getElementById('miniSwatchPreview'); const summaryBadge = document.getElementById('fillingSummaryBadge'); + const sidebarSub = document.getElementById('fillingSidebarSubtext'); + const isAuto = !!document.getElementById('autoStyleFromMapToggle')?.checked; + + // Sync Label Style UI controls + const txtColorEl = document.getElementById('labelStyleTextColor'); + const txtHexEl = document.getElementById('labelStyleTextHex'); + const strColorEl = document.getElementById('labelStyleStrokeColor'); + const strHexEl = document.getElementById('labelStyleStrokeHex'); + const strWidthEl = document.getElementById('labelStyleStrokeWidth'); + const strWidthValEl = document.getElementById('labelStyleStrokeWidthVal'); + const autoFitEl = document.getElementById('labelStyleAutoFit'); + const recFontBadge = document.getElementById('recommendedFontBadge'); + + if (txtColorEl) txtColorEl.value = labelStyleConfig.text_color || '#ffffff'; + if (txtHexEl) txtHexEl.textContent = labelStyleConfig.text_color || '#ffffff'; + if (strColorEl) strColorEl.value = labelStyleConfig.stroke_color || '#090d16'; + if (strHexEl) strHexEl.textContent = labelStyleConfig.stroke_color || '#090d16'; + if (strWidthEl) strWidthEl.value = labelStyleConfig.stroke_width || 15; + if (strWidthValEl) strWidthValEl.textContent = `${labelStyleConfig.stroke_width || 15}px`; + if (autoFitEl) autoFitEl.checked = labelStyleConfig.auto_fit !== false; + if (recFontBadge) recFontBadge.textContent = `Font: ${labelStyleConfig.recommended_font || 'Bips.ttf'}`; if (txtList) { txtList.innerHTML = fillingTxtRules.map((item, idx) => ` @@ -1489,10 +1870,10 @@

- to -

Size at 1080×1920. Long titles shrink automatically to fit.

Enter starts a new line. Colors also apply to automatically wrapped lines.

-

Headlines use uppercase lettering for the reference layout.

+ + + + +
+
+ + + Shorts Auto-Montage Overlays + Optional + +
+ + +
+
+

Optional overlays — leave as None / unchecked to render a standard map video without extra badges.

+ +
+ Top corner stickers + +
+ + + + +
+
+ + +
+ Preset or custom file +
+ + +
+
+
+
+ + +
+ Preset or custom file +
+ + +
+
+
+
+ + + + +
+ Built-in [ ❤️ Subscribe! ▶️ ] or upload file +
+ + +
+
+ +
+ + +
+
+

@@ -750,6 +1024,22 @@

+ + +
+ Built-in ★ ★ ★ or upload file +
+ + +
+

Your logo is center-cropped to a circle below the map. Watermark text uses its own font near the bottom.

@@ -829,7 +1119,10 @@

+ + +
@@ -842,6 +1135,7 @@

+
@@ -921,8 +1215,10 @@

const VIDEO_SETTINGS_KEY = 'automap_video_settings_v1'; const VIDEO_SETTING_IDS = ['musicUrlInput', 'cutStartInput', 'cutDurationInput', 'videoTitleInput', 'titleFontSelect', 'titleFontSize', 'titleFirstLineColor', - 'titleOtherLinesColor', 'visualEffects', 'watermarkTextInput', - 'watermarkFontSelect', 'watermarkColor', 'codecSelect']; + 'titleOtherLinesColor', 'titleUppercase', 'visualEffects', 'introFadeToggle', + 'topLeftStickerSelect', 'topRightStickerSelect', 'subscribeBadgeToggle', + 'subscribeTextInput', 'subscribeDelayInput', 'watermarkTextInput', + 'watermarkFontSelect', 'watermarkColor', 'watermarkStarsToggle', 'codecSelect']; let videoSettingsReady = false; const materialVersions = {mapFileInput: 0, bgFileInput: 0}; let pendingAssetSaves = Promise.resolve(); @@ -958,8 +1254,12 @@

if (input.type === 'checkbox') { if (typeof value === 'boolean') input.checked = value; } else if (typeof value === 'string') { - if (input.tagName === 'SELECT' && ![...input.options].some(option => option.value === value)) return; - input.value = input.maxLength > 0 ? value.slice(0, input.maxLength) : value; + let normalized = value; + if ((id === 'topLeftStickerSelect' || id === 'topRightStickerSelect') && value.startsWith('gen_')) { + normalized = normalizeDynamicStickerValue(value); + } + if (input.tagName === 'SELECT' && ![...input.options].some(option => option.value === normalized)) return; + input.value = input.maxLength > 0 ? normalized.slice(0, input.maxLength) : normalized; } }); } @@ -967,13 +1267,26 @@

// Invalid or unavailable saved settings should not prevent opening the studio. } videoSettingsReady = true; + if (isDynamicStickerValue(document.getElementById('topLeftStickerSelect').value) || + isDynamicStickerValue(document.getElementById('topRightStickerSelect').value)) { + document.getElementById('autoStickerVariantsBox').classList.remove('hidden'); + } setCutDuration(document.getElementById('cutDurationInput').value); updateVisualEffects(); try { - const [latest, selected, background, logo, cutAudio] = await Promise.all([ - StudioStorage.getAsset('latest-map'), StudioStorage.getAsset('video-map'), - StudioStorage.getAsset('video-background'), StudioStorage.getAsset('video-watermark'), + const [ + latest, selected, background, logo, cutAudio, + savedSubImg, savedStarsImg, savedLeftStickerImg, savedRightStickerImg, + ] = await Promise.all([ + StudioStorage.getAsset('latest-map'), + StudioStorage.getAsset('video-map'), + StudioStorage.getAsset('video-background'), + StudioStorage.getAsset('video-watermark'), StudioStorage.getAsset('video-cut-audio'), + StudioStorage.getAsset('video-subscribe-image'), + StudioStorage.getAsset('video-stars-image'), + StudioStorage.getAsset('video-left-sticker-image'), + StudioStorage.getAsset('video-right-sticker-image'), ]); // A newer generated map wins. A manually selected or removed map // remains the user's choice until another map is generated. @@ -988,6 +1301,10 @@

acceptFile('bgFileInput', background.file, false); } if (logo?.file && watermarkUploadVersion === 0) await selectWatermark(logo.file, false); + if (savedSubImg?.file && subscribeUploadVersion === 0) await selectSubscribeImage(savedSubImg.file, false); + if (savedStarsImg?.file && watermarkStarsUploadVersion === 0) await selectWatermarkStarsImage(savedStarsImg.file, false); + if (savedLeftStickerImg?.file && leftStickerUploadVersion === 0) await selectLeftStickerImage(savedLeftStickerImg.file, false); + if (savedRightStickerImg?.file && rightStickerUploadVersion === 0) await selectRightStickerImage(savedRightStickerImg.file, false); if (cutAudio?.file && audioSelectionVersion === 0) { const restoredAudio = await fileToDataUrl(cutAudio.file); if (audioSelectionVersion !== 0) return; @@ -1560,7 +1877,14 @@

title_font_size: Number(document.getElementById('titleFontSize').value), title_first_line_color: document.getElementById('titleFirstLineColor').value, title_other_lines_color: document.getElementById('titleOtherLinesColor').value, + title_uppercase: document.getElementById('titleUppercase').checked, visual_effects: document.getElementById('visualEffects').checked, + intro_fade: document.getElementById('introFadeToggle').checked, + top_left_sticker: document.getElementById('topLeftStickerSelect').value, + top_right_sticker: document.getElementById('topRightStickerSelect').value, + subscribe_badge: document.getElementById('subscribeBadgeToggle').checked, + subscribe_text: document.getElementById('subscribeTextInput').value.trim() || 'Subscribe!', + subscribe_delay: Number(document.getElementById('subscribeDelayInput').value || 2.5), }; } @@ -1594,6 +1918,7 @@

function updateTitleStyle() { document.getElementById('titleFontSizeValue').textContent = `${titleSettings().title_font_size} px`; updateStageTitlePreview(document.getElementById('videoTitleInput').value); + updateAutoMontagePreview(); updateWatermarkPreview(); saveVideoSettings(); } @@ -1603,9 +1928,691 @@

document.getElementById('titleFontSize').value = '100'; document.getElementById('titleFirstLineColor').value = '#ffffff'; document.getElementById('titleOtherLinesColor').value = '#ffe735'; + document.getElementById('titleUppercase').checked = true; + document.getElementById('subscribeTextInput').value = 'Subscribe!'; + document.getElementById('subscribeDelayInput').value = '2.5'; + clearAutoMontageOverlays(false); updateTitleStyle(); } + function clearAutoMontageOverlays(notify = true) { + document.getElementById('topLeftStickerSelect').value = 'none'; + document.getElementById('topRightStickerSelect').value = 'none'; + document.getElementById('subscribeBadgeToggle').checked = false; + document.getElementById('watermarkStarsToggle').checked = false; + document.getElementById('introFadeToggle').checked = false; + document.getElementById('autoStickerVariantsBox').classList.add('hidden'); + clearLeftStickerImage(true); + clearRightStickerImage(true); + clearSubscribeImage(true); + clearWatermarkStarsImage(true); + showLiveComposite(); + updateAutoMontagePreview(); + updateWatermarkPreview(); + saveVideoSettings(); + if (notify) { + showToast('Cleared optional auto-montage overlays.', 'info'); + } + } + + const STICKER_CATALOG = { + auto: '✨ Auto', + santa: '🎅 Santa', + gift: '🎁 Gift', + snowflake: '❄️ Snow', + pumpkin: '🎃 Pumpkin', + globe: '🌍 Globe', + compass: '🧭 Compass', + pin: '📍 Pin', + plane: '✈️ Plane', + money: '💰 Money', + chart: '📈 Chart', + diamond: '💎 Diamond', + crown: '👑 Crown', + shield: '🛡️ Shield', + swords: '⚔️ Swords', + rocket: '🚀 Rocket', + bolt: '⚡ Bolt', + trophy: '🏆 Trophy', + fire: '🔥 Fire', + star: '⭐ Star', + heart: '❤️ Heart', + skull: '💀 Skull', + bear: '🐻 Bear', + paw: '🐾 Paw', + tree: '🌲 Tree', + wolf: '🐺 Wolf', + beer: '🍺 Beer', + coffee: '☕ Coffee', + wine: '🍷 Wine', + pizza: '🍕 Pizza', + soccer: '⚽ Football', + car: '🚗 Car', + brain: '🧠 Brain', + book: '📚 Book', + sun: '☀️ Sun', + }; + + const AUTO_STICKER_THEME_VARIANTS = [ + { + name: 'Wildlife & Nature', + keywords: ['bear', 'bears', 'grizzly', 'panda', 'wolf', 'wolves', 'fox', 'deer', 'moose', 'boar', 'lion', 'tiger', 'dog', 'dogs', 'cat', 'cats', 'pet', 'pets', 'animal', 'animals', 'wildlife', 'wild', 'forest', 'tree', 'trees', 'woods', 'nature', 'park', 'hunt', 'bird', 'fish', 'shark', 'snake', 'horse', 'cow', 'ведмід', 'ведмед', 'вовк', 'тварин', 'ліс', 'природ', 'собак', 'кіт'], + left: ['auto', 'bear', 'paw', 'tree', 'wolf'], + right: ['auto', 'tree', 'paw', 'bear', 'wolf'], + }, + { + name: 'Food, Drinks & Lifestyle', + keywords: ['beer', 'beers', 'wine', 'alcohol', 'vodka', 'whiskey', 'drink', 'drinks', 'pub', 'bar', 'coffee', 'tea', 'cafe', 'pizza', 'burger', 'food', 'cuisine', 'cheese', 'meat', 'bread', 'milk', 'water', 'пиво', 'вино', 'алкогол', 'кава', 'чай', 'їжа', 'страв'], + left: ['auto', 'beer', 'coffee', 'wine', 'pizza'], + right: ['auto', 'coffee', 'beer', 'pizza', 'wine'], + }, + { + name: 'People, IQ & Education', + keywords: ['iq', 'smart', 'intelligent', 'brain', 'genius', 'education', 'school', 'university', 'student', 'literacy', 'book', 'books', 'read', 'language', 'languages', 'speak', 'word', 'words', 'alphabet', 'name', 'names', 'population', 'people', 'human', 'мова', 'освіта', 'розум', 'книг', 'населення', 'люд', 'імен'], + left: ['auto', 'brain', 'book', 'crown', 'star'], + right: ['auto', 'book', 'brain', 'trophy', 'globe'], + }, + { + name: 'Cars, Transport & Energy', + keywords: ['car', 'cars', 'auto', 'vehicle', 'drive', 'driving', 'highway', 'road', 'roads', 'train', 'rail', 'railway', 'metro', 'bus', 'traffic', 'fuel', 'gas', 'petrol', 'oil', 'tesla', 'bmw', 'авто', 'машин', 'дорог', 'поїзд', 'транспорт', 'бензин', 'нафт'], + left: ['auto', 'car', 'bolt', 'compass', 'fire'], + right: ['auto', 'bolt', 'car', 'pin', 'globe'], + }, + { + name: 'Sports, Football & Games', + keywords: ['sport', 'sports', 'football', 'soccer', 'fifa', 'uefa', 'world cup', 'basketball', 'hockey', 'tennis', 'olympic', 'olympics', 'medal', 'athlete', 'gym', 'game', 'games', 'chess', 'спорт', 'футбол', 'олімп', 'медал', 'гра', 'ігр'], + left: ['auto', 'soccer', 'trophy', 'fire', 'crown'], + right: ['auto', 'trophy', 'soccer', 'star', 'fire'], + }, + { + name: 'Cold, Ice & Winter Weather', + keywords: ['cold', 'coldest', 'freeze', 'freezing', 'frost', 'ice', 'icy', 'snow', 'snowy', 'blizzard', 'minus', 'subzero', 'arctic', 'glacier', 'chill', 'холод', 'найхолод', 'мороз', 'сніг', 'лід', 'арктик'], + left: ['auto', 'snowflake', 'compass', 'globe', 'star'], + right: ['auto', 'globe', 'snowflake', 'pin', 'compass'], + }, + { + name: 'Weather, Climate & Heat', + keywords: ['weather', 'temperature', 'climate', 'sun', 'sunny', 'hot', 'hottest', 'heat', 'warm', 'warmest', 'summer', 'rain', 'wind', 'celsius', 'desert', 'погод', 'клімат', 'температур', 'сонц', 'спека', 'літо', 'тепл'], + left: ['auto', 'sun', 'compass', 'fire', 'globe'], + right: ['auto', 'compass', 'sun', 'pin', 'fire'], + }, + { + name: 'Oceans, Rivers & Geography', + keywords: ['sea', 'ocean', 'river', 'lake', 'coast', 'island', 'water', 'mountain', 'mountains', 'море', 'океан', 'річк', 'озеро', 'острів', 'вода', 'гор'], + left: ['auto', 'compass', 'globe', 'pin', 'sun'], + right: ['auto', 'globe', 'pin', 'compass', 'star'], + }, + { + name: 'Religion & Culture', + keywords: ['religion', 'christian', 'catholic', 'orthodox', 'islam', 'muslim', 'church', 'mosque', 'god', 'faith', 'реліг', 'християн', 'церкв', 'іслам'], + left: ['auto', 'star', 'globe', 'crown', 'book'], + right: ['auto', 'globe', 'star', 'pin', 'book'], + }, + { + name: 'Holiday & Winter', + keywords: ['nicholas', 'santa', 'christmas', 'xmas', 'winter', 'holiday', 'new year', 'snow', 'миколая', 'різдв', 'санта', 'зима', 'свято', 'новий рік'], + left: ['auto', 'santa', 'snowflake', 'gift', 'star'], + right: ['auto', 'gift', 'snowflake', 'santa', 'crown'], + }, + { + name: 'Halloween & Spooky', + keywords: ['halloween', 'spooky', 'horror', 'ghost', 'scary', 'геловін', 'страш'], + left: ['auto', 'pumpkin', 'skull', 'fire', 'star'], + right: ['auto', 'skull', 'pumpkin', 'fire', 'crown'], + }, + { + name: 'Economy & Wealth', + keywords: ['gdp', 'rich', 'poor', 'money', 'salary', 'wage', 'economy', 'tax', 'price', 'cost', 'billion', 'wealth', 'ввп', 'багат', 'бідн', 'грош', 'зарплат', 'економік', 'цін', 'подат'], + left: ['auto', 'money', 'diamond', 'chart', 'crown'], + right: ['auto', 'chart', 'money', 'diamond', 'trophy'], + }, + { + name: 'History, Military & Empires', + keywords: ['war', 'army', 'military', 'empire', 'history', 'battle', 'nato', 'soldier', 'війн', 'армі', 'імпері', 'історі', 'битв'], + left: ['auto', 'shield', 'swords', 'crown', 'skull'], + right: ['auto', 'swords', 'shield', 'fire', 'trophy'], + }, + { + name: 'Royalty & Power', + keywords: ['queen', 'monarch', 'royal', 'king', 'president', 'power', 'ruler', 'монарх', 'корол', 'президент', 'влад'], + left: ['auto', 'crown', 'diamond', 'shield', 'star'], + right: ['auto', 'star', 'crown', 'trophy', 'globe'], + }, + { + name: 'Science, Space & Energy', + keywords: ['space', 'nasa', 'tech', 'ai', 'internet', 'speed', 'energy', 'nuclear', 'science', 'космос', 'технолог', 'інтернет', 'швидк', 'енерг', 'наук'], + left: ['auto', 'rocket', 'bolt', 'globe', 'star'], + right: ['auto', 'bolt', 'rocket', 'chart', 'fire'], + }, + { + name: 'Travel & Geography', + keywords: ['travel', 'tourist', 'visa', 'passport', 'flight', 'airport', 'visit', 'подорож', 'туризм', 'віза', 'паспорт', 'літак'], + left: ['auto', 'plane', 'globe', 'compass', 'pin'], + right: ['auto', 'compass', 'pin', 'plane', 'star'], + }, + { + name: 'Rankings & Top Charts', + keywords: ['top', 'best', 'most', 'highest', 'winner', 'champion', 'rank', 'топ', 'найкращ', 'найбільш', 'рейтинг', 'чемпіон'], + left: ['auto', 'trophy', 'crown', 'star', 'fire'], + right: ['auto', 'fire', 'trophy', 'chart', 'diamond'], + }, + { + name: 'Love, Health & Happiness', + keywords: ['happy', 'happiness', 'love', 'health', 'life', 'safe', 'щаст', 'любов', 'здоров', 'житт', 'безпек'], + left: ['auto', 'heart', 'star', 'globe', 'trophy'], + right: ['auto', 'star', 'heart', 'crown', 'globe'], + }, + { + name: 'Danger & Risk', + keywords: ['danger', 'crime', 'dead', 'worst', 'risk', 'небезпек', 'злочин', 'смерт', 'ризик'], + left: ['auto', 'skull', 'fire', 'shield', 'bolt'], + right: ['auto', 'fire', 'skull', 'chart', 'pin'], + }, + ]; + + const EXACT_STICKER_WORDS = new Set([ + 'ai', 'gdp', 'nato', 'top', 'iq', 'car', 'sun', 'pet', 'dog', 'cat', + 'bar', 'pub', 'tea', 'oil', 'gas', 'bus', 'gym', 'ice', 'hot', 'god', + 'sea', 'топ', 'ввп', + ]); + + function detectTitleStickerVariants(title) { + const lower = (title || '').toLowerCase(); + let best = null; + let bestScore = 0; + for (const theme of AUTO_STICKER_THEME_VARIANTS) { + let score = 0; + for (const kw of theme.keywords) { + const escaped = kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const pattern = EXACT_STICKER_WORDS.has(kw) + ? new RegExp(`(^|[^a-zа-яіїєґ0-9_])${escaped}($|[^a-zа-яіїєґ0-9_])`, 'i') + : new RegExp(`(^|[^a-zа-яіїєґ0-9_])${escaped}`, 'i'); + if (pattern.test(lower)) score += 1; + } + if (score > bestScore) { + bestScore = score; + best = theme; + } + } + return best || { + name: 'World & Maps', + left: ['auto', 'globe', 'compass', 'trophy', 'fire'], + right: ['auto', 'pin', 'star', 'chart', 'crown'], + }; + } + + function normalizeDynamicStickerValue(val) { + if (!val) return 'none'; + if (val.startsWith('gen_diecut:')) return 'gen_diecut:auto'; + if (val.startsWith('gen_neon:')) return 'gen_neon:auto'; + if (val.startsWith('gen_stamp:')) return 'gen_stamp:auto'; + return val; + } + + function isDynamicStickerValue(val) { + return val === 'auto' || (typeof val === 'string' && val.startsWith('gen_')); + } + + function pickStickerVariant(side, value) { + const selectId = side === 'left' ? 'topLeftStickerSelect' : 'topRightStickerSelect'; + const select = document.getElementById(selectId); + if (side === 'left' && leftStickerFile) clearLeftStickerImage(true); + if (side === 'right' && rightStickerFile) clearRightStickerImage(true); + if (![...select.options].some(opt => opt.value === value)) { + const opt = document.createElement('option'); + opt.value = value; + const [prefix, base] = value.split(':'); + const styleLabel = prefix === 'gen_diecut' ? 'Die-Cut' : prefix === 'gen_neon' ? 'Neon' : 'Stamp'; + opt.textContent = `✨ Generated ${styleLabel} (${base})`; + select.appendChild(opt); + } + select.value = value; + showLiveComposite(); + updateAutoMontagePreview(); + } + + let lastAutoStickerTheme = null; + + function renderAutoStickerVariants() { + const box = document.getElementById('autoStickerVariantsBox'); + if (!box || box.classList.contains('hidden')) return; + const title = document.getElementById('videoTitleInput').value.trim(); + const theme = detectTitleStickerVariants(title); + document.getElementById('autoStickerThemeLabel').textContent = `Theme: ${theme.name} — library & generated variants`; + + const leftSelect = document.getElementById('topLeftStickerSelect'); + const rightSelect = document.getElementById('topRightStickerSelect'); + if (lastAutoStickerTheme && lastAutoStickerTheme.name !== theme.name) { + if (lastAutoStickerTheme.left.includes(leftSelect.value) && leftSelect.value !== 'auto') { + leftSelect.value = 'auto'; + } + if (lastAutoStickerTheme.right.includes(rightSelect.value) && rightSelect.value !== 'auto') { + rightSelect.value = 'auto'; + } + } + lastAutoStickerTheme = theme; + if (leftSelect.value.startsWith('gen_') && !leftSelect.value.endsWith(':auto')) { + leftSelect.value = normalizeDynamicStickerValue(leftSelect.value); + } + if (rightSelect.value.startsWith('gen_') && !rightSelect.value.endsWith(':auto')) { + rightSelect.value = normalizeDynamicStickerValue(rightSelect.value); + } + const currentLeft = leftSelect.value; + const currentRight = rightSelect.value; + const bestLeftBase = theme.left[1] || 'globe'; + const bestRightBase = theme.right[1] || 'pin'; + + const buildChips = (containerId, side, libraryItems, baseKind, currentValue) => { + const container = document.getElementById(containerId); + container.replaceChildren(); + + const addGroup = (heading, entries) => { + const label = document.createElement('div'); + label.className = 'w-full text-[9px] font-mono uppercase tracking-wider text-slate-500 mt-0.5'; + label.textContent = heading; + container.appendChild(label); + + entries.forEach(({ val, text, prefixMatch }) => { + const btn = document.createElement('button'); + btn.type = 'button'; + const active = currentValue === val || (prefixMatch && currentValue.startsWith(prefixMatch)); + btn.className = active + ? 'px-2 py-0.5 rounded-md bg-indigo-500/30 text-white border border-indigo-400 text-[10px] font-medium transition' + : 'px-2 py-0.5 rounded-md bg-slate-900 hover:bg-slate-800 text-slate-300 border border-slate-700 text-[10px] transition'; + btn.textContent = text; + btn.onclick = () => pickStickerVariant(side, val); + container.appendChild(btn); + }); + }; + + addGroup('Library (Twemoji)', libraryItems.map(val => ({ + val, + text: STICKER_CATALOG[val] || val, + }))); + + const baseLabel = STICKER_CATALOG[baseKind] || baseKind; + addGroup('Generated (Custom Art)', [ + { val: 'gen_diecut:auto', prefixMatch: 'gen_diecut:', text: `✨ Die-Cut (${baseLabel})` }, + { val: 'gen_neon:auto', prefixMatch: 'gen_neon:', text: `💫 Neon Badge (${baseLabel})` }, + { val: 'gen_stamp:auto', prefixMatch: 'gen_stamp:', text: `🏷️ Stamp (${baseLabel})` }, + ]); + }; + + buildChips('autoLeftVariantsList', 'left', theme.left, bestLeftBase, currentLeft); + buildChips('autoRightVariantsList', 'right', theme.right, bestRightBase, currentRight); + } + + function setAutoStickers() { + const leftSelect = document.getElementById('topLeftStickerSelect'); + const rightSelect = document.getElementById('topRightStickerSelect'); + leftSelect.value = leftSelect.value.startsWith('gen_') + ? normalizeDynamicStickerValue(leftSelect.value) + : 'auto'; + rightSelect.value = rightSelect.value.startsWith('gen_') + ? normalizeDynamicStickerValue(rightSelect.value) + : 'auto'; + document.getElementById('autoStickerVariantsBox').classList.remove('hidden'); + renderAutoStickerVariants(); + showLiveComposite(); + updateAutoMontagePreview(); + showToast('Auto-matched stickers! Choose any left or right variant below.', 'info'); + } + + function applyShortsViralPreset() { + const titleEl = document.getElementById('videoTitleInput'); + if (!titleEl.value.trim()) { + titleEl.value = 'When is Saint Nicholas\nDay in your country?'; + } + const wmEl = document.getElementById('watermarkTextInput'); + if (!wmEl.value.trim()) { + wmEl.value = 'TERRAMAPPER'; + } + document.getElementById('titleUppercase').checked = false; + document.getElementById('titleFirstLineColor').value = '#ffffff'; + document.getElementById('titleOtherLinesColor').value = '#ffffff'; + document.getElementById('topLeftStickerSelect').value = 'santa'; + document.getElementById('topRightStickerSelect').value = 'gift'; + document.getElementById('subscribeBadgeToggle').checked = true; + document.getElementById('subscribeTextInput').value = 'Subscribe!'; + document.getElementById('subscribeDelayInput').value = '2.5'; + document.getElementById('watermarkColor').value = '#ffffff'; + document.getElementById('watermarkStarsToggle').checked = true; + document.getElementById('introFadeToggle').checked = true; + document.getElementById('visualEffects').checked = true; + updateVisualEffects(); + showToast('Applied Reference Video Auto-Montage Preset!', 'success'); + } + + let subscribePreviewUrl; + let leftStickerPreviewUrl; + let rightStickerPreviewUrl; + let starsPreviewUrl; + let autoMontageVersion = 0; + + let subscribeImageFile = null; + let subscribeCustomUrl = null; + let subscribeUploadVersion = 0; + + let watermarkStarsFile = null; + let watermarkStarsCustomUrl = null; + let watermarkStarsUploadVersion = 0; + + let leftStickerFile = null; + let leftStickerCustomUrl = null; + let leftStickerUploadVersion = 0; + + let rightStickerFile = null; + let rightStickerCustomUrl = null; + let rightStickerUploadVersion = 0; + + const OVERLAY_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif']; + + async function validateOverlayImageFile(file, inputEl, label) { + if (!file) return null; + if (!OVERLAY_IMAGE_TYPES.includes(file.type) || file.size > MAX_MATERIAL_BYTES) { + showToast(`Choose a PNG, JPEG, WebP or GIF ${label} up to 10 MB.`, 'error'); + if (inputEl) inputEl.value = ''; + return null; + } + const url = URL.createObjectURL(file); + const probe = new Image(); + probe.src = url; + try { + await probe.decode(); + if (probe.naturalWidth * probe.naturalHeight > 20000000) { + throw new Error('Image is too large.'); + } + return url; + } catch { + URL.revokeObjectURL(url); + if (inputEl) inputEl.value = ''; + showToast(`Choose a valid ${label} image up to 20 megapixels.`, 'error'); + return null; + } + } + + function clearSubscribeImage(persist = true) { + subscribeUploadVersion++; + subscribeImageFile = null; + const input = document.getElementById('subscribeImageInput'); + if (input) input.value = ''; + const nameEl = document.getElementById('subscribeFileName'); + if (nameEl) nameEl.textContent = 'Built-in [ ❤️ Subscribe! ▶️ ] or upload file'; + if (subscribeCustomUrl) { + URL.revokeObjectURL(subscribeCustomUrl); + subscribeCustomUrl = null; + } + showLiveComposite(); + updateAutoMontagePreview(); + if (persist) rememberVideoAsset('video-subscribe-image', null); + } + + async function selectSubscribeImage(file, persist = true) { + const input = document.getElementById('subscribeImageInput'); + const version = ++subscribeUploadVersion; + if (!file) return; + const url = await validateOverlayImageFile(file, input, 'subscribe badge'); + if (!url) return; + if (version !== subscribeUploadVersion) { + URL.revokeObjectURL(url); + return; + } + if (subscribeCustomUrl) URL.revokeObjectURL(subscribeCustomUrl); + subscribeImageFile = file; + subscribeCustomUrl = url; + document.getElementById('subscribeFileName').textContent = file.name; + if (persist) { + document.getElementById('subscribeBadgeToggle').checked = true; + } + showLiveComposite(); + updateAutoMontagePreview(); + if (persist) rememberVideoAsset('video-subscribe-image', file); + } + + function clearWatermarkStarsImage(persist = true) { + watermarkStarsUploadVersion++; + watermarkStarsFile = null; + const input = document.getElementById('watermarkStarsImageInput'); + if (input) input.value = ''; + const nameEl = document.getElementById('watermarkStarsFileName'); + if (nameEl) nameEl.textContent = 'Built-in ★ ★ ★ or upload file'; + if (watermarkStarsCustomUrl) { + URL.revokeObjectURL(watermarkStarsCustomUrl); + watermarkStarsCustomUrl = null; + } + showLiveComposite(); + updateWatermarkPreview(); + if (persist) rememberVideoAsset('video-stars-image', null); + } + + async function selectWatermarkStarsImage(file, persist = true) { + const input = document.getElementById('watermarkStarsImageInput'); + const version = ++watermarkStarsUploadVersion; + if (!file) return; + const url = await validateOverlayImageFile(file, input, 'stars / footer badge'); + if (!url) return; + if (version !== watermarkStarsUploadVersion) { + URL.revokeObjectURL(url); + return; + } + if (watermarkStarsCustomUrl) URL.revokeObjectURL(watermarkStarsCustomUrl); + watermarkStarsFile = file; + watermarkStarsCustomUrl = url; + document.getElementById('watermarkStarsFileName').textContent = file.name; + if (persist) { + document.getElementById('watermarkStarsToggle').checked = true; + } + showLiveComposite(); + updateWatermarkPreview(); + if (persist) rememberVideoAsset('video-stars-image', file); + } + + function clearLeftStickerImage(persist = true) { + leftStickerUploadVersion++; + leftStickerFile = null; + const input = document.getElementById('leftStickerImageInput'); + if (input) input.value = ''; + const nameEl = document.getElementById('leftStickerFileName'); + if (nameEl) nameEl.textContent = 'Preset or custom file'; + if (leftStickerCustomUrl) { + URL.revokeObjectURL(leftStickerCustomUrl); + leftStickerCustomUrl = null; + } + showLiveComposite(); + updateAutoMontagePreview(); + if (persist) rememberVideoAsset('video-left-sticker-image', null); + } + + async function selectLeftStickerImage(file, persist = true) { + const input = document.getElementById('leftStickerImageInput'); + const version = ++leftStickerUploadVersion; + if (!file) return; + const url = await validateOverlayImageFile(file, input, 'top-left sticker'); + if (!url) return; + if (version !== leftStickerUploadVersion) { + URL.revokeObjectURL(url); + return; + } + if (leftStickerCustomUrl) URL.revokeObjectURL(leftStickerCustomUrl); + leftStickerFile = file; + leftStickerCustomUrl = url; + document.getElementById('leftStickerFileName').textContent = file.name; + showLiveComposite(); + updateAutoMontagePreview(); + if (persist) rememberVideoAsset('video-left-sticker-image', file); + } + + function clearRightStickerImage(persist = true) { + rightStickerUploadVersion++; + rightStickerFile = null; + const input = document.getElementById('rightStickerImageInput'); + if (input) input.value = ''; + const nameEl = document.getElementById('rightStickerFileName'); + if (nameEl) nameEl.textContent = 'Preset or custom file'; + if (rightStickerCustomUrl) { + URL.revokeObjectURL(rightStickerCustomUrl); + rightStickerCustomUrl = null; + } + showLiveComposite(); + updateAutoMontagePreview(); + if (persist) rememberVideoAsset('video-right-sticker-image', null); + } + + async function selectRightStickerImage(file, persist = true) { + const input = document.getElementById('rightStickerImageInput'); + const version = ++rightStickerUploadVersion; + if (!file) return; + const url = await validateOverlayImageFile(file, input, 'top-right sticker'); + if (!url) return; + if (version !== rightStickerUploadVersion) { + URL.revokeObjectURL(url); + return; + } + if (rightStickerCustomUrl) URL.revokeObjectURL(rightStickerCustomUrl); + rightStickerFile = file; + rightStickerCustomUrl = url; + document.getElementById('rightStickerFileName').textContent = file.name; + showLiveComposite(); + updateAutoMontagePreview(); + if (persist) rememberVideoAsset('video-right-sticker-image', file); + } + + async function fetchPreviewBlobUrl(payload) { + const response = await fetch('/api/video_title_preview', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); + if (!response.ok) return null; + return URL.createObjectURL(await response.blob()); + } + + async function updateAutoMontagePreview() { + const version = ++autoMontageVersion; + const settings = titleSettings(); + const currentTitle = document.getElementById('videoTitleInput').value.trim(); + const compositeBox = document.getElementById('stageCompositeBox'); + const leftBox = document.getElementById('stageTopLeftSticker'); + const rightBox = document.getElementById('stageTopRightSticker'); + const subBox = document.getElementById('stageSubscribeBanner'); + + const hasLeftSticker = Boolean(leftStickerFile || (settings.top_left_sticker && settings.top_left_sticker !== 'none')); + const hasRightSticker = Boolean(rightStickerFile || (settings.top_right_sticker && settings.top_right_sticker !== 'none')); + const hasStickers = hasLeftSticker || hasRightSticker; + compositeBox.classList.toggle('has-top-stickers', hasStickers); + renderAutoStickerVariants(); + saveVideoSettings(); + + // Left sticker preview (custom file takes precedence over built-in preset) + if (leftStickerFile && leftStickerCustomUrl) { + const img = new Image(); + img.alt = leftStickerFile.name || 'Custom top-left sticker'; + img.src = leftStickerCustomUrl; + leftBox.replaceChildren(img); + leftBox.classList.remove('hidden'); + } else if (settings.top_left_sticker && settings.top_left_sticker !== 'none') { + try { + const url = await fetchPreviewBlobUrl({ + preview_kind: 'sticker', + sticker_kind: settings.top_left_sticker, + sticker_side: 'left', + video_title: currentTitle, + ...settings, + }); + if (version === autoMontageVersion && url) { + const img = new Image(); + img.alt = settings.top_left_sticker; + img.src = url; + await img.decode(); + leftBox.replaceChildren(img); + leftBox.classList.remove('hidden'); + if (leftStickerPreviewUrl) URL.revokeObjectURL(leftStickerPreviewUrl); + leftStickerPreviewUrl = url; + } else if (url) { + URL.revokeObjectURL(url); + } + } catch { + leftBox.classList.add('hidden'); + } + } else { + leftBox.replaceChildren(); + leftBox.classList.add('hidden'); + } + + // Right sticker preview (custom file takes precedence over built-in preset) + if (rightStickerFile && rightStickerCustomUrl) { + const img = new Image(); + img.alt = rightStickerFile.name || 'Custom top-right sticker'; + img.src = rightStickerCustomUrl; + rightBox.replaceChildren(img); + rightBox.classList.remove('hidden'); + } else if (settings.top_right_sticker && settings.top_right_sticker !== 'none') { + try { + const url = await fetchPreviewBlobUrl({ + preview_kind: 'sticker', + sticker_kind: settings.top_right_sticker, + sticker_side: 'right', + video_title: currentTitle, + ...settings, + }); + if (version === autoMontageVersion && url) { + const img = new Image(); + img.alt = settings.top_right_sticker; + img.src = url; + await img.decode(); + rightBox.replaceChildren(img); + rightBox.classList.remove('hidden'); + if (rightStickerPreviewUrl) URL.revokeObjectURL(rightStickerPreviewUrl); + rightStickerPreviewUrl = url; + } else if (url) { + URL.revokeObjectURL(url); + } + } catch { + rightBox.classList.add('hidden'); + } + } else { + rightBox.replaceChildren(); + rightBox.classList.add('hidden'); + } + + // Subscribe pill preview (custom uploaded badge image or built-in pill) + if (settings.subscribe_badge) { + if (subscribeImageFile && subscribeCustomUrl) { + const img = new Image(); + img.alt = subscribeImageFile.name || 'Custom subscribe badge'; + img.src = subscribeCustomUrl; + subBox.replaceChildren(img); + subBox.classList.remove('hidden'); + } else { + try { + const url = await fetchPreviewBlobUrl({ + preview_kind: 'subscribe', + subscribe_text: settings.subscribe_text, + ...settings, + }); + if (version === autoMontageVersion && url) { + const img = new Image(); + img.alt = settings.subscribe_text; + img.src = url; + await img.decode(); + subBox.replaceChildren(img); + subBox.classList.remove('hidden'); + if (subscribePreviewUrl) URL.revokeObjectURL(subscribePreviewUrl); + subscribePreviewUrl = url; + } else if (url) { + URL.revokeObjectURL(url); + } + } catch { + subBox.classList.add('hidden'); + } + } + } else { + subBox.replaceChildren(); + subBox.classList.add('hidden'); + } + fitStageMap(); + } + let watermarkFile = null; let watermarkImageUrl; let watermarkTextUrl; @@ -1619,12 +2626,16 @@

watermark_text: document.getElementById('watermarkTextInput').value.trim(), watermark_color: document.getElementById('watermarkColor').value, watermark_font: document.getElementById('watermarkFontSelect').value, + watermark_stars: document.getElementById('watermarkStarsToggle').checked, }; } function syncBrandingLayout() { - document.getElementById('stageCompositeBox').classList.toggle('has-branding', - Boolean(watermarkFile || watermarkSettings().watermark_text)); + const wm = watermarkSettings(); + const box = document.getElementById('stageCompositeBox'); + box.classList.toggle('has-branding', + Boolean(watermarkFile || wm.watermark_text || wm.watermark_stars)); + box.classList.toggle('has-stars', Boolean(wm.watermark_stars)); fitStageMap(); } @@ -1696,12 +2707,49 @@

function updateWatermarkPreview() { const settings = watermarkSettings(); const banner = document.getElementById('stageWatermarkText'); + const starsBox = document.getElementById('stageWatermarkStars'); const status = document.getElementById('watermarkPreviewStatus'); clearTimeout(watermarkPreviewTimer); if (watermarkPreviewRequest) watermarkPreviewRequest.abort(); const version = ++watermarkPreviewVersion; showLiveComposite(); syncBrandingLayout(); + saveVideoSettings(); + + if (!settings.watermark_stars) { + starsBox.replaceChildren(); + starsBox.classList.add('hidden'); + if (starsPreviewUrl) URL.revokeObjectURL(starsPreviewUrl); + starsPreviewUrl = null; + } else if (watermarkStarsFile && watermarkStarsCustomUrl) { + const img = new Image(); + img.alt = watermarkStarsFile.name || 'Custom stars badge'; + img.src = watermarkStarsCustomUrl; + starsBox.replaceChildren(img); + starsBox.classList.remove('hidden'); + } else { + fetchPreviewBlobUrl({ + preview_kind: 'stars', + ...titleSettings(), + ...settings, + }).then(async (url) => { + if (version !== watermarkPreviewVersion || !url) { + if (url) URL.revokeObjectURL(url); + return; + } + const img = new Image(); + img.alt = '★ ★ ★'; + img.src = url; + await img.decode(); + starsBox.replaceChildren(img); + starsBox.classList.remove('hidden'); + if (starsPreviewUrl) URL.revokeObjectURL(starsPreviewUrl); + starsPreviewUrl = url; + }).catch(() => { + starsBox.classList.add('hidden'); + }); + } + if (!settings.watermark_text) { banner.replaceChildren(); banner.classList.add('hidden'); @@ -1744,6 +2792,12 @@

}, 180); } + function shouldSyncStickersOnTitleEdit(cur) { + const box = document.getElementById('autoStickerVariantsBox'); + const boxOpen = box && !box.classList.contains('hidden'); + return boxOpen || isDynamicStickerValue(cur.top_left_sticker) || isDynamicStickerValue(cur.top_right_sticker); + } + function updateStageTitlePreview(val) { const title = (val || '').trim(); const banner = document.getElementById('stageTitleBanner'); @@ -1759,12 +2813,20 @@

if (titlePreviewUrl) URL.revokeObjectURL(titlePreviewUrl); titlePreviewUrl = null; status.textContent = ''; + const cur = titleSettings(); + if (shouldSyncStickersOnTitleEdit(cur)) { + updateAutoMontagePreview(); + } return; } status.textContent = 'Updating preview…'; // Use the same title rasterizer as the final render, including wrapping, // font metrics, shadows and automatic fitting. Debounce quick edits. titlePreviewTimer = setTimeout(async () => { + const cur = titleSettings(); + if (shouldSyncStickersOnTitleEdit(cur)) { + updateAutoMontagePreview(); + } const controller = new AbortController(); titlePreviewRequest = controller; let url; @@ -2096,11 +3158,25 @@

logToConsole(`[Render] POST /api/render_video title="${title}" codec=${codec} duration=${durationSecs}s map=${mapFile.name} bg=${bgFile.name}`, 'cmd'); try { - // Encode both materials as base64 data URLs. - const [mapB64, bgB64, watermarkB64, audioB64] = await Promise.all([ - fileToDataUrl(mapFile), fileToDataUrl(bgFile), + // Encode materials and any custom overlay images as base64 data URLs. + const [ + mapB64, + bgB64, + watermarkB64, + audioB64, + subscribeImageB64, + watermarkStarsImageB64, + leftStickerImageB64, + rightStickerImageB64, + ] = await Promise.all([ + fileToDataUrl(mapFile), + fileToDataUrl(bgFile), watermarkFile ? fileToDataUrl(watermarkFile) : '', includeAudio && cutAudioFile ? fileToDataUrl(cutAudioFile) : '', + subscribeImageFile ? fileToDataUrl(subscribeImageFile) : '', + watermarkStarsFile ? fileToDataUrl(watermarkStarsFile) : '', + leftStickerFile ? fileToDataUrl(leftStickerFile) : '', + rightStickerFile ? fileToDataUrl(rightStickerFile) : '', ]); // Everything (files as base64 + user args + selected duration) goes in a single JSON body. @@ -2116,6 +3192,10 @@

...titleSettings(), ...watermarkSettings(), watermark_image: watermarkB64, + subscribe_image: subscribeImageB64, + watermark_stars_image: watermarkStarsImageB64, + top_left_sticker_image: leftStickerImageB64, + top_right_sticker_image: rightStickerImageB64, }; const response = await fetch('/api/render_video', { @@ -2227,6 +3307,14 @@

if (titlePreviewUrl) URL.revokeObjectURL(titlePreviewUrl); if (watermarkImageUrl) URL.revokeObjectURL(watermarkImageUrl); if (watermarkTextUrl) URL.revokeObjectURL(watermarkTextUrl); + if (subscribePreviewUrl) URL.revokeObjectURL(subscribePreviewUrl); + if (leftStickerPreviewUrl) URL.revokeObjectURL(leftStickerPreviewUrl); + if (rightStickerPreviewUrl) URL.revokeObjectURL(rightStickerPreviewUrl); + if (starsPreviewUrl) URL.revokeObjectURL(starsPreviewUrl); + if (subscribeCustomUrl) URL.revokeObjectURL(subscribeCustomUrl); + if (watermarkStarsCustomUrl) URL.revokeObjectURL(watermarkStarsCustomUrl); + if (leftStickerCustomUrl) URL.revokeObjectURL(leftStickerCustomUrl); + if (rightStickerCustomUrl) URL.revokeObjectURL(rightStickerCustomUrl); }); }); diff --git a/tests/test_auto_map.py b/tests/test_auto_map.py index 4b30c01..aa7a07a 100644 --- a/tests/test_auto_map.py +++ b/tests/test_auto_map.py @@ -156,3 +156,33 @@ def test_font_objects_are_cached_within_render(scene, monkeypatch): monkeypatch.setattr(renderer.ImageFont, 'truetype', load_font) render() assert load_font.call_count == 1 + + +def test_auto_fill_from_ai_detects_numbers_and_words(): + txt_rules, num_rules = renderer._auto_fill_from_ai( + {'ukraine': 38, 'poland': 37, 'germany': 84, 'estonia': 1}, + mode='number', + ) + assert not txt_rules + assert len(num_rules) >= 2 + + txt_rules_w, num_rules_w = renderer._auto_fill_from_ai( + {'ukraine': '6 Dec', 'russia': '19 Dec', 'netherlands': '5 Dec'}, + mode='text', + ) + assert not num_rules_w + assert '6 Dec' in txt_rules_w + assert '19 Dec' in txt_rules_w + assert txt_rules_w['6 Dec'] != txt_rules_w['19 Dec'] + + # Short-form numeric strings in text mode should be grouped into gradient buckets, + # not assigned a distinct color per unique string. + short_txt, _ = renderer._auto_fill_from_ai( + {f'r{i}': f'{i}k' for i in range(1, 21)}, + mode='text', + ) + assert len(set(short_txt.values())) <= 5 + assert short_txt['1k'] == short_txt['2k'] + assert short_txt['1k'] != short_txt['20k'] + + diff --git a/tests/test_video_render.py b/tests/test_video_render.py index 5a6d715..70d7f27 100644 --- a/tests/test_video_render.py +++ b/tests/test_video_render.py @@ -247,3 +247,163 @@ def test_round_logo_center_crop_and_transparency(worker): assert logo.shape == (230, 230, 4) assert logo[0, 0, 3] == 0 and logo[-1, -1, 3] == 0 assert tuple(logo[115, 115]) == (0, 255, 0, 128) + + +def test_mixed_case_title_and_auto_montage_previews(worker): + client = worker.app.test_client() + upper_img = worker._title_image('When is Saint Nicholas', 1040, uppercase=True) + mixed_img = worker._title_image('When is Saint Nicholas', 1040, uppercase=False) + assert not np.array_equal(upper_img, mixed_img) + + for payload in [ + {'preview_kind': 'subscribe', 'subscribe_text': 'Subscribe!'}, + {'preview_kind': 'stars', 'watermark_color': '#ffffff'}, + {'preview_kind': 'sticker', 'sticker_kind': 'santa'}, + {'preview_kind': 'sticker', 'sticker_kind': 'gift'}, + ]: + res = client.post('/api/video_title_preview', json=payload) + assert res.status_code == 200 + assert res.mimetype == 'image/png' + arr = np.array(Image.open(io.BytesIO(res.data))) + assert arr.ndim == 3 and arr.shape[2] == 4 + 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) + 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(), + 'video_title': 'When is Saint Nicholas\nDay in your country?', + 'title_uppercase': False, + 'top_left_sticker': 'santa', + 'top_right_sticker': 'gift', + 'subscribe_badge': True, + 'subscribe_text': 'Subscribe!', + 'subscribe_delay': 0.1, + 'watermark_text': 'TERRAMAPPER', + 'watermark_color': '#ffffff', + 'watermark_stars': True, + 'intro_fade': True, + 'duration': 1, + }) + 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) + # 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 + green_y, _ = np.where((frame_mid[:, :, 1] > 210) & (frame_mid[:, :, 0] < 40)) + assert len(green_y) > 100 + assert green_y.min() > 380 + assert green_y.max() < 1460 + # Footer has both watermark text and the 3 stars row below y=1690 + footer_bright = np.all(frame_mid[1690:1900, :, :] > 200, axis=2) + assert np.count_nonzero(footer_bright) > 100 + + +@pytest.mark.parametrize('title,expected', [ + ('When is Saint Nicholas Day in your country?', ('santa', 'gift')), + ('Святкування Різдва та Святого Миколая', ('santa', 'gift')), + ('Spooky Halloween traditions across Europe', ('pumpkin', 'skull')), + ('GDP per capita and average salary in Europe', ('money', 'chart')), + ('ВВП та середня зарплата в країнах ЄС', ('money', 'chart')), + ('Roman Empire and ancient military history', ('shield', 'swords')), + ('Історія війн та найбільші битви', ('shield', 'swords')), + ('European Monarchs and Royal Families', ('crown', 'star')), + ('Fastest internet speed and AI technology', ('rocket', 'bolt')), + ('Visa-free travel and strongest passports', ('plane', 'compass')), + ('Top 10 best countries to visit', ('trophy', 'fire')), + ('Happiest countries and life expectancy', ('heart', 'star')), + ('Most dangerous crime rate in Europe', ('skull', 'fire')), + ('how many bears in your country?', ('bear', 'tree')), + ('What was the coldest temperature ever recorded in your country?', ('snowflake', 'globe')), + ('Hottest temperature and climate in Europe', ('sun', 'compass')), + ('Average beer and coffee consumption', ('beer', 'coffee')), + ('Average IQ and education in Europe', ('brain', 'book')), + ('Найкрасивіші країни Європи', ('globe', 'pin')), +]) +def test_resolve_auto_stickers_thematic_matching(worker, title, expected): + assert worker._resolve_auto_stickers(title) == expected + + +def test_all_sticker_kinds_and_auto_preview(worker): + client = worker.app.test_client() + for kind in worker.ALLOWED_STICKERS: + if kind == 'none': + assert worker._sticker_image(kind) is None + continue + arr = worker._sticker_image(kind) + assert arr is not None and arr.ndim == 3 and arr.shape[2] == 4 + assert np.any(arr[:, :, 3] > 200) + + res_left = client.post('/api/video_title_preview', json={ + 'preview_kind': 'sticker', + 'sticker_kind': 'auto', + 'sticker_side': 'left', + 'video_title': 'GDP per capita in Europe', + }) + res_right = client.post('/api/video_title_preview', json={ + 'preview_kind': 'sticker', + 'sticker_kind': 'auto', + 'sticker_side': 'right', + 'video_title': 'GDP per capita in Europe', + }) + assert res_left.status_code == 200 and res_right.status_code == 200 + left_arr = np.array(Image.open(io.BytesIO(res_left.data))) + right_arr = np.array(Image.open(io.BytesIO(res_right.data))) + np.testing.assert_array_equal(left_arr, worker._sticker_image('money')) + np.testing.assert_array_equal(right_arr, worker._sticker_image('chart')) + + +def test_custom_subscribe_stars_and_top_sticker_images_render(worker, tmp_path): + 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) + + 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 + Image.new('RGBA', (400, 90), (255, 0, 255, 255)).save(sub_buf, format='PNG') + # Custom yellow footer stars/badge image + Image.new('RGBA', (320, 70), (255, 255, 0, 255)).save(stars_buf, format='PNG') + # Custom cyan top-left sticker image + Image.new('RGBA', (140, 140), (0, 255, 255, 255)).save(sticker_buf, format='PNG') + + 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(), + 'video_title': 'Custom Overlays Test', + 'top_left_sticker_image': base64.b64encode(sticker_buf.getvalue()).decode(), + 'top_right_sticker': 'auto', + 'subscribe_image': base64.b64encode(sub_buf.getvalue()).decode(), + 'subscribe_delay': 0.0, + 'watermark_text': 'TERRAMAPPER', + 'watermark_stars_image': base64.b64encode(stars_buf.getvalue()).decode(), + 'duration': 1, + }) + assert response.status_code == 200, response.json + with VideoFileClip(response.json['file_path']) as result: + frame = result.get_frame(0.5) + + # Top-left custom cyan sticker is rendered near the top-left slot + cyan_top = (frame[:200, :350, 1] > 210) & (frame[:200, :350, 2] > 210) & (frame[:200, :350, 0] < 50) + assert np.count_nonzero(cyan_top) > 200 + + # Custom magenta subscribe badge is rendered below the title and shifts map down + magenta = (frame[:, :, 0] > 210) & (frame[:, :, 2] > 210) & (frame[:, :, 1] < 50) + mag_y, _ = np.where(magenta) + assert len(mag_y) > 200 + green_y, _ = np.where((frame[:, :, 1] > 210) & (frame[:, :, 0] < 40) & (frame[:, :, 2] < 40)) + assert green_y.min() > mag_y.max() + + # Custom yellow stars/footer badge is rendered at the bottom footer + yellow_footer = (frame[1760:1915, :, 0] > 210) & (frame[1760:1915, :, 1] > 210) & (frame[1760:1915, :, 2] < 60) + assert np.count_nonzero(yellow_footer) > 200 + diff --git a/tests/test_web.py b/tests/test_web.py index 3729a37..53c9d05 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -204,3 +204,19 @@ def test_codec_proxy_failure(web, monkeypatch, failure): 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_analyze_map_endpoint_returns_rules_and_style(web): + client = web.app.test_client() + res = client.post('/api/analyze_map', json={ + 'topic': 'When is Saint Nicholas Day', + 'mode': 'text', + 'map_values': {'ukraine': '6 Dec', 'serbia': '19 Dec', 'netherlands': '5 Dec'}, + }) + assert res.status_code == 200 + data = res.json + assert data['status'] == 'success' + assert data['analysis']['detected_type'] == 'text' + assert len(data['analysis']['ui_txt_rules']) == 3 + assert 'recommended_font' in data['analysis']['label_style'] + diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index f75be4d..d384fb0 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -285,14 +285,23 @@ def _title_colors(data): return colors -def _title_image(title: str, max_width: int, font_path=TITLE_FONT_PATH, font_size=100, - first_line_color='#ffffff', other_lines_color='#ffe735', - effects=True, max_height=360): +def _title_image( + title: str, + max_width: int, + font_path: str = TITLE_FONT_PATH, + font_size: int = 100, + first_line_color: str = '#ffffff', + other_lines_color: str = '#ffe735', + effects: bool = True, + max_height: int = 360, + uppercase: bool = True, +): """Lay out a centered, wrapped title with safe margins and a layered shadow.""" import numpy as np from PIL import Image, ImageColor, ImageDraw, ImageFilter, ImageFont - title = title.upper() + if uppercase: + title = title.upper() padding = 24 outline = 6 if effects else 1 text_width = max_width - padding * 2 @@ -355,13 +364,31 @@ def _title_image(title: str, max_width: int, font_path=TITLE_FONT_PATH, font_siz return np.array(image) -def _build_title_clip(title: str, duration: float, max_width: int, - font_path=TITLE_FONT_PATH, font_size=100, - first_line_color='#ffffff', other_lines_color='#ffe735', effects=True): +def _build_title_clip( + title: str, + duration: float, + max_width: int, + font_path: str = TITLE_FONT_PATH, + font_size: int = 100, + first_line_color: str = '#ffffff', + other_lines_color: str = '#ffe735', + effects: bool = True, + uppercase: bool = True, +): from moviepy import ImageClip - return ImageClip(_title_image(title, max_width, font_path, font_size, - first_line_color, other_lines_color, effects)).with_duration(duration) + return ImageClip( + _title_image( + title, + max_width, + font_path, + font_size, + first_line_color, + other_lines_color, + effects, + uppercase=uppercase, + ) + ).with_duration(duration) def _watermark_settings(data): @@ -407,24 +434,828 @@ def _with_shadow(image): return canvas +ALLOWED_STICKERS = ( + 'none', 'auto', 'santa', 'gift', 'snowflake', 'pumpkin', + 'globe', 'compass', 'pin', 'plane', + 'money', 'chart', 'diamond', 'crown', + 'shield', 'swords', 'rocket', 'bolt', + 'fire', 'trophy', 'star', 'heart', 'skull', + 'bear', 'paw', 'tree', 'wolf', + 'beer', 'coffee', 'wine', 'pizza', + 'soccer', 'car', 'brain', 'book', 'sun', +) + +TWEMOJI_CODEPOINTS: dict[str, str] = { + 'santa': '1f385', + 'gift': '1f381', + 'snowflake': '2744', + 'pumpkin': '1f383', + 'globe': '1f30d', + 'compass': '1f9ed', + 'pin': '1f4cd', + 'plane': '2708', + 'money': '1f4b0', + 'chart': '1f4c8', + 'diamond': '1f48e', + 'crown': '1f451', + 'shield': '1f6e1', + 'swords': '2694', + 'rocket': '1f680', + 'bolt': '26a1', + 'fire': '1f525', + 'trophy': '1f3c6', + 'star': '2b50', + 'heart': '2764', + 'skull': '1f480', + 'bear': '1f43b', + 'paw': '1f43e', + 'tree': '1f332', + 'wolf': '1f43a', + 'beer': '1f37a', + 'coffee': '2615', + 'wine': '1f377', + 'pizza': '1f355', + 'soccer': '26bd', + 'car': '1f697', + 'brain': '1f9e0', + 'book': '1f4da', + 'sun': '2600', +} + +_AUTO_STICKER_THEMES: tuple[tuple[tuple[str, ...], tuple[str, str]], ...] = ( + ( + ('bear', 'bears', 'grizzly', 'panda', 'wolf', 'wolves', 'fox', 'deer', 'moose', + 'boar', 'lion', 'tiger', 'dog', 'dogs', 'cat', 'cats', 'pet', 'pets', + 'animal', 'animals', 'wildlife', 'wild', 'forest', 'tree', 'trees', 'woods', + 'nature', 'park', 'hunt', 'bird', 'fish', 'shark', 'snake', 'horse', 'cow', + 'ведмід', 'ведмед', 'вовк', 'тварин', 'ліс', 'природ', 'собак', 'кіт'), + ('bear', 'tree'), + ), + ( + ('beer', 'beers', 'wine', 'alcohol', 'vodka', 'whiskey', 'drink', 'drinks', + 'pub', 'bar', 'coffee', 'tea', 'cafe', 'pizza', 'burger', 'food', 'cuisine', + 'cheese', 'meat', 'bread', 'milk', 'water', + 'пиво', 'вино', 'алкогол', 'кава', 'чай', 'їжа', 'страв'), + ('beer', 'coffee'), + ), + ( + ('iq', 'smart', 'intelligent', 'brain', 'genius', 'education', 'school', + 'university', 'student', 'literacy', 'book', 'books', 'read', 'language', + 'languages', 'speak', 'word', 'words', 'alphabet', 'name', 'names', + 'population', 'people', 'human', + 'мова', 'освіта', 'розум', 'книг', 'населення', 'люд', 'імен'), + ('brain', 'book'), + ), + ( + ('car', 'cars', 'auto', 'vehicle', 'drive', 'driving', 'highway', 'road', + 'roads', 'train', 'rail', 'railway', 'metro', 'bus', 'traffic', 'fuel', + 'gas', 'petrol', 'oil', 'tesla', 'bmw', + 'авто', 'машин', 'дорог', 'поїзд', 'транспорт', 'бензин', 'нафт'), + ('car', 'bolt'), + ), + ( + ('sport', 'sports', 'football', 'soccer', 'fifa', 'uefa', 'world cup', + 'basketball', 'hockey', 'tennis', 'olympic', 'olympics', 'medal', 'athlete', + 'gym', 'game', 'games', 'chess', + 'спорт', 'футбол', 'олімп', 'медал', 'гра', 'ігр'), + ('soccer', 'trophy'), + ), + ( + ('cold', 'coldest', 'freeze', 'freezing', 'frost', 'ice', 'icy', 'snow', + 'snowy', 'blizzard', 'minus', 'subzero', 'arctic', 'glacier', 'chill', + 'холод', 'найхолод', 'мороз', 'сніг', 'лід', 'арктик'), + ('snowflake', 'globe'), + ), + ( + ('weather', 'temperature', 'climate', 'sun', 'sunny', 'hot', 'hottest', + 'heat', 'warm', 'warmest', 'summer', 'rain', 'wind', 'celsius', 'desert', + 'погод', 'клімат', 'температур', 'сонц', 'спека', 'літо', 'тепл'), + ('sun', 'compass'), + ), + ( + ('sea', 'ocean', 'river', 'lake', 'coast', 'island', 'water', 'mountain', 'mountains', + 'море', 'океан', 'річк', 'озеро', 'острів', 'вода', 'гор'), + ('compass', 'globe'), + ), + ( + ('religion', 'christian', 'catholic', 'orthodox', 'islam', 'muslim', 'church', + 'mosque', 'god', 'faith', 'реліг', 'християн', 'церкв', 'іслам'), + ('star', 'globe'), + ), + ( + ('nicholas', 'santa', 'christmas', 'xmas', 'winter', 'holiday', 'new year', + 'миколая', 'різдв', 'санта', 'зима', 'свято', 'новий рік'), + ('santa', 'gift'), + ), + ( + ('halloween', 'spooky', 'horror', 'геловін', 'страш'), + ('pumpkin', 'skull'), + ), + ( + ('gdp', 'rich', 'poor', 'money', 'salary', 'wage', 'economy', 'tax', + 'price', 'cost', 'billion', 'wealth', + 'ввп', 'багат', 'бідн', 'грош', 'зарплат', 'економік', 'цін', 'подат'), + ('money', 'chart'), + ), + ( + ('war', 'army', 'military', 'empire', 'king', 'history', 'battle', 'nato', + 'війн', 'армі', 'імпері', 'історі', 'битв', 'королів'), + ('shield', 'swords'), + ), + ( + ('queen', 'monarch', 'royal', 'president', 'power', 'ruler', + 'монарх', 'корол', 'президент', 'влад'), + ('crown', 'star'), + ), + ( + ('space', 'nasa', 'tech', 'ai', 'internet', 'speed', 'energy', 'nuclear', 'science', + 'космос', 'технолог', 'інтернет', 'швидк', 'енерг', 'наук'), + ('rocket', 'bolt'), + ), + ( + ('travel', 'tourist', 'visa', 'passport', 'flight', 'airport', 'visit', + 'подорож', 'туризм', 'віза', 'паспорт', 'літак'), + ('plane', 'compass'), + ), + ( + ('danger', 'crime', 'dead', 'worst', 'risk', + 'небезпек', 'злочин', 'смерт', 'ризик'), + ('skull', 'fire'), + ), + ( + ('top', 'best', 'most', 'highest', 'winner', 'champion', 'rank', + 'топ', 'найкращ', 'найбільш', 'рейтинг', 'чемпіон'), + ('trophy', 'fire'), + ), + ( + ('happy', 'happi', 'happiness', 'love', 'health', 'life', 'safe', + 'щаст', 'любов', 'здоров', 'житт', 'безпек'), + ('heart', 'star'), + ), +) + +_EXACT_WORD_KEYWORDS = { + 'ai', 'gdp', 'nato', 'top', 'iq', 'car', 'sun', 'pet', 'dog', 'cat', + 'bar', 'pub', 'tea', 'oil', 'gas', 'bus', 'gym', 'ice', 'hot', 'god', + 'sea', 'топ', 'ввп', +} + + +def _resolve_auto_stickers(title: str) -> tuple[str, str]: + """Choose a thematic (left, right) sticker pair based on English or Ukrainian title keywords.""" + lowered = (title or '').lower() + if not lowered.strip(): + return ('globe', 'pin') + best_pair: tuple[str, str] | None = None + best_count = 0 + for keywords, pair in _AUTO_STICKER_THEMES: + count = 0 + for kw in keywords: + if kw in _EXACT_WORD_KEYWORDS: + pattern = rf'(? best_count: + best_count = count + best_pair = pair + return best_pair if best_pair is not None else ('globe', 'pin') + + +def _star_polygon(cx: float, cy: float, outer_r: float, inner_r: float) -> list[tuple[float, float]]: + """Return the 10 vertices of a 5-pointed star centered at (cx, cy).""" + import math + + points: list[tuple[float, float]] = [] + for i in range(10): + angle = -math.pi / 2 + i * (math.pi / 5) + r = outer_r if i % 2 == 0 else inner_r + points.append((cx + r * math.cos(angle), cy + r * math.sin(angle))) + return points + + +def _draw_heart(draw, cx: float, cy: float, size: float, fill: tuple[int, int, int, int], + outline: tuple[int, int, int, int] = (0, 0, 0, 255), width: int = 4) -> None: + """Draw a smooth vector heart icon centered at (cx, cy).""" + import math + + pts: list[tuple[float, float]] = [] + for step in range(64): + t = (step / 64.0) * 2.0 * math.pi + x = 16.0 * (math.sin(t) ** 3) + y = -(13.0 * math.cos(t) - 5.0 * math.cos(2 * t) - 2.0 * math.cos(3 * t) - math.cos(4 * t)) + pts.append((cx + x * (size / 34.0), cy + y * (size / 34.0))) + draw.polygon(pts, fill=fill, outline=outline, width=width) + + +def _subscribe_badge_image( + text: str = 'Subscribe!', + font_path: str = TITLE_FONT_PATH, + effects: bool = True, +): + """Render the dark rounded '[ ❤️ Subscribe! ▶️ ]' call-to-action pill badge.""" + import numpy as np + from PIL import Image, ImageDraw, ImageFont + + label = (text or 'Subscribe!').strip()[:40] or 'Subscribe!' + scale = 2 + font_size = 52 * scale + font = ImageFont.truetype(font_path, font_size) + measure = ImageDraw.Draw(Image.new('RGBA', (1, 1))) + bbox = measure.textbbox((0, 0), label, font=font, stroke_width=3 * scale) + text_w = bbox[2] - bbox[0] + + heart_slot = 64 * scale + play_w, play_h = 68 * scale, 48 * scale + pad_x = 28 * scale + gap = 18 * scale + pill_h = 84 * scale + pill_w = pad_x * 2 + heart_slot + gap * 2 + text_w + play_w + + canvas = Image.new('RGBA', (pill_w + 16 * scale, pill_h + 16 * scale), (0, 0, 0, 0)) + draw = ImageDraw.Draw(canvas) + ox, oy = 8 * scale, 8 * scale + + # Rounded dark charcoal pill with subtle glossy border + draw.rounded_rectangle( + (ox, oy, ox + pill_w, oy + pill_h), + radius=26 * scale, + fill=(28, 30, 36, 228), + outline=(255, 255, 255, 58), + width=2 * scale, + ) + + # Left icon: glossy red heart + heart_cx = ox + pad_x + heart_slot / 2 + heart_cy = oy + pill_h / 2 + 2 * scale + _draw_heart( + draw, + heart_cx, + heart_cy, + 54 * scale, + fill=(255, 42, 75, 255), + outline=(15, 15, 20, 255), + width=3 * scale, + ) + # Specular highlight on top-left lobe of heart + draw.ellipse( + (heart_cx - 16 * scale, heart_cy - 16 * scale, heart_cx - 6 * scale, heart_cy - 7 * scale), + fill=(255, 190, 200, 190), + ) + + # Center text: bold white Subscribe! text with dark stroke + text_x = ox + pad_x + heart_slot + gap + text_w / 2 + text_y = oy + pill_h / 2 + draw.text( + (text_x, text_y), + label, + font=font, + anchor='mm', + fill=(255, 255, 255, 255), + stroke_width=3 * scale, + stroke_fill=(0, 0, 0, 240), + ) + + # Right icon: red YouTube-style rounded play button + play_x0 = ox + pad_x + heart_slot + gap * 2 + text_w + play_y0 = oy + (pill_h - play_h) / 2 + draw.rounded_rectangle( + (play_x0, play_y0, play_x0 + play_w, play_y0 + play_h), + radius=12 * scale, + fill=(255, 32, 32, 255), + outline=(15, 15, 20, 255), + width=3 * scale, + ) + tri_cx = play_x0 + play_w / 2 + 2 * scale + tri_cy = play_y0 + play_h / 2 + tri = [ + (tri_cx - 11 * scale, tri_cy - 12 * scale), + (tri_cx - 11 * scale, tri_cy + 12 * scale), + (tri_cx + 13 * scale, tri_cy), + ] + draw.polygon(tri, fill=(255, 255, 255, 255)) + + final_img = canvas.resize((canvas.width // scale, canvas.height // scale), Image.Resampling.LANCZOS) + if effects: + final_img = _with_shadow(final_img) + return np.array(final_img) + + +def _stars_row_image(color: str = '#ffffff', effects: bool = True): + """Render three 5-pointed stars ('★ ★ ★') for the bottom watermark footer.""" + import numpy as np + from PIL import Image, ImageColor, ImageDraw + + if not isinstance(color, str) or not re.fullmatch(r'#[0-9a-fA-F]{6}', color): + color = '#ffffff' + rgb = ImageColor.getrgb(color) + + scale = 2 + w, h = 320 * scale, 76 * scale + canvas = Image.new('RGBA', (w, h), (0, 0, 0, 0)) + draw = ImageDraw.Draw(canvas) + + centers_x = (w * 0.22, w * 0.50, w * 0.78) + cy = h * 0.52 + for cx in centers_x: + pts = _star_polygon(cx, cy, outer_r=26 * scale, inner_r=11 * scale) + draw.polygon( + pts, + fill=rgb + (255,), + outline=(0, 0, 0, 240) if effects else rgb + (220,), + width=4 * scale if effects else 2 * scale, + ) + + final_img = canvas.resize((w // scale, h // scale), Image.Resampling.LANCZOS) + if effects: + final_img = _with_shadow(final_img) + return np.array(final_img) + + +def _parse_sticker_spec(raw_kind: str, title: str = '', side: str = 'left') -> tuple[str | None, str]: + """Parse a sticker specification into ``(gen_style_or_none, base_kind)``.""" + raw = (raw_kind or 'none').strip().lower() + gen_style: str | None = None + if ':' in raw: + prefix, _, base_kind = raw.partition(':') + if prefix in ('gen', 'gen_diecut', 'gen_neon', 'gen_stamp'): + gen_style = 'diecut' if prefix == 'gen' else prefix.removeprefix('gen_') + raw = base_kind or 'auto' + if raw == 'auto': + left_auto, right_auto = _resolve_auto_stickers(title) + raw = right_auto if side == 'right' else left_auto + return gen_style, raw + + +def _style_generated_sticker(icon_canvas, gen_style: str, size: int): + """Wrap a procedural vector icon in a generated sticker style (die-cut, neon, or stamp).""" + from PIL import Image, ImageDraw, ImageFilter + + s = icon_canvas.width + if gen_style == 'diecut': + # Create a crisp white vinyl die-cut sticker border around the vector silhouette. + alpha = icon_canvas.getchannel('A') + dilate = max(3, int(round(s * 0.055))) | 1 + border_mask = alpha.filter(ImageFilter.MaxFilter(dilate)) + vinyl = Image.new('RGBA', (s, s), (255, 255, 255, 0)) + vinyl.putalpha(border_mask) + white_layer = Image.new('RGBA', (s, s), (252, 253, 255, 255)) + white_layer.putalpha(border_mask) + styled = Image.alpha_composite(white_layer, icon_canvas) + styled = styled.rotate(6, resample=Image.Resampling.BICUBIC, expand=False) + return styled.resize((size, size), Image.Resampling.LANCZOS) + + if gen_style == 'neon': + badge = Image.new('RGBA', (s, s), (0, 0, 0, 0)) + glow = Image.new('RGBA', (s, s), (0, 0, 0, 0)) + gdraw = ImageDraw.Draw(glow) + pad = int(s * 0.08) + gdraw.ellipse((pad, pad, s - pad, s - pad), outline=(56, 189, 248, 230), width=int(s * 0.055)) + glow = glow.filter(ImageFilter.GaussianBlur(max(4, s // 28))) + bdraw = ImageDraw.Draw(badge) + bdraw.ellipse((pad, pad, s - pad, s - pad), fill=(15, 23, 42, 238), outline=(99, 102, 241, 255), width=int(s * 0.032)) + bdraw.ellipse((pad + 6, pad + 6, s - pad - 6, s - pad - 6), outline=(56, 189, 248, 210), width=max(2, s // 70)) + badge = Image.alpha_composite(glow, badge) + inner_size = int(s * 0.68) + icon_small = icon_canvas.resize((inner_size, inner_size), Image.Resampling.LANCZOS) + offset = (s - inner_size) // 2 + badge.alpha_composite(icon_small, (offset, offset)) + return badge.resize((size, size), Image.Resampling.LANCZOS) + + # 'stamp': tilted editorial badge with double accent frame and corner sparkles + stamp = Image.new('RGBA', (s, s), (0, 0, 0, 0)) + sdraw = ImageDraw.Draw(stamp) + pad = int(s * 0.08) + sdraw.rounded_rectangle((pad, pad, s - pad, s - pad), radius=int(s * 0.22), + fill=(30, 27, 75, 235), outline=(251, 191, 36, 255), width=int(s * 0.03)) + sdraw.rounded_rectangle((pad + 10, pad + 10, s - pad - 10, s - pad - 10), radius=int(s * 0.17), + outline=(255, 255, 255, 110), width=max(2, s // 80)) + # Tiny decorative sparkle stars in top corners + for sx, sy in ((s * 0.22, s * 0.22), (s * 0.78, s * 0.22)): + sdraw.polygon(_star_polygon(sx, sy, s * 0.055, s * 0.022), fill=(253, 224, 71, 240)) + inner_size = int(s * 0.68) + icon_small = icon_canvas.resize((inner_size, inner_size), Image.Resampling.LANCZOS) + offset = (s - inner_size) // 2 + stamp.alpha_composite(icon_small, (offset, offset + int(s * 0.03))) + stamp = stamp.rotate(-6, resample=Image.Resampling.BICUBIC, expand=False) + return stamp.resize((size, size), Image.Resampling.LANCZOS) + + +def _sticker_image(kind: str, size: int = 140, effects: bool = True, allow_remote: bool = False): + """Render a decorative top-corner sticker (library Twemoji or procedural generated style).""" + import numpy as np + from PIL import Image, ImageDraw, ImageOps + + gen_style, kind = _parse_sticker_spec(kind) + if kind not in ALLOWED_STICKERS or kind == 'none': + return None + + # Library stickers (without a gen_ prefix) use Twemoji cache/CDN when available. + codepoint = None if gen_style else TWEMOJI_CODEPOINTS.get(kind) + if codepoint: + stickers_dir = os.path.join(STORAGE_DIR, 'stickers') + cache_path = os.path.join(stickers_dir, f'{kind}.png') + if not os.path.isfile(cache_path) and allow_remote: + try: + import requests + os.makedirs(stickers_dir, exist_ok=True) + url = f'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/{codepoint}.png' + resp = requests.get(url, timeout=1.5) + if resp.status_code == 200 and resp.content: + with Image.open(io.BytesIO(resp.content)) as fetched: + fetched.convert('RGBA').save(cache_path, format='PNG') + except Exception: + pass + if os.path.isfile(cache_path): + try: + with Image.open(cache_path) as cached: + final_img = ImageOps.contain(cached.convert('RGBA'), (size, size), method=Image.Resampling.LANCZOS) + if final_img.size != (size, size): + padded = Image.new('RGBA', (size, size), (0, 0, 0, 0)) + padded.paste(final_img, ((size - final_img.width) // 2, (size - final_img.height) // 2)) + final_img = padded + if effects: + final_img = _with_shadow(final_img) + return np.array(final_img) + except Exception: + pass + + scale = 2 + s = size * scale + canvas = Image.new('RGBA', (s, s), (0, 0, 0, 0)) + draw = ImageDraw.Draw(canvas) + outline = (18, 18, 24, 255) + ow = 4 * scale + + if kind == 'santa': + # Fluffy white beard base + draw.ellipse((s * 0.16, s * 0.44, s * 0.84, s * 0.94), fill=(250, 252, 255, 255), outline=outline, width=ow) + draw.ellipse((s * 0.12, s * 0.52, s * 0.46, s * 0.84), fill=(250, 252, 255, 255), outline=outline, width=ow) + draw.ellipse((s * 0.54, s * 0.52, s * 0.88, s * 0.84), fill=(250, 252, 255, 255), outline=outline, width=ow) + # Warm face + draw.ellipse((s * 0.24, s * 0.30, s * 0.76, s * 0.72), fill=(255, 214, 186, 255), outline=outline, width=ow) + # Re-fill inner beard over lower face + draw.chord((s * 0.18, s * 0.42, s * 0.82, s * 0.92), start=0, end=180, fill=(250, 252, 255, 255), outline=outline, width=ow) + # Rosy cheeks & eyes + draw.ellipse((s * 0.28, s * 0.48, s * 0.39, s * 0.56), fill=(255, 138, 138, 210)) + draw.ellipse((s * 0.61, s * 0.48, s * 0.72, s * 0.56), fill=(255, 138, 138, 210)) + draw.ellipse((s * 0.35, s * 0.41, s * 0.42, s * 0.48), fill=outline) + draw.ellipse((s * 0.58, s * 0.41, s * 0.65, s * 0.48), fill=outline) + # Mustache & rosy nose + draw.ellipse((s * 0.30, s * 0.53, s * 0.52, s * 0.65), fill=(255, 255, 255, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.48, s * 0.53, s * 0.70, s * 0.65), fill=(255, 255, 255, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.44, s * 0.47, s * 0.56, s * 0.57), fill=(244, 92, 92, 255), outline=outline, width=ow // 2) + # Red Santa hat & white fur brim + pom-pom + hat_pts = [(s * 0.18, s * 0.34), (s * 0.52, s * 0.06), (s * 0.86, s * 0.28), (s * 0.80, s * 0.36)] + draw.polygon(hat_pts, fill=(228, 34, 46, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.15, s * 0.27, s * 0.83, s * 0.40), radius=14 * scale, fill=(252, 253, 255, 255), outline=outline, width=ow) + draw.ellipse((s * 0.76, s * 0.18, s * 0.94, s * 0.36), fill=(252, 253, 255, 255), outline=outline, width=ow) + + elif kind == 'gift': + # Candy cane behind top-right of gift box + draw.arc((s * 0.52, s * 0.06, s * 0.90, s * 0.46), start=180, end=20, fill=(235, 38, 50, 255), width=12 * scale) + # Golden ribbon bow Loops on top + draw.ellipse((s * 0.24, s * 0.14, s * 0.52, s * 0.38), fill=(255, 204, 42, 255), outline=outline, width=ow) + draw.ellipse((s * 0.48, s * 0.14, s * 0.76, s * 0.38), fill=(255, 204, 42, 255), outline=outline, width=ow) + # Red gift box body + draw.rounded_rectangle((s * 0.18, s * 0.36, s * 0.82, s * 0.90), radius=12 * scale, fill=(224, 36, 48, 255), outline=outline, width=ow) + # Gift box lid + draw.rounded_rectangle((s * 0.14, s * 0.28, s * 0.86, s * 0.44), radius=10 * scale, fill=(242, 52, 64, 255), outline=outline, width=ow) + # Vertical & horizontal gold ribbon stripes + draw.rectangle((s * 0.44, s * 0.28, s * 0.56, s * 0.90), fill=(255, 208, 46, 255), outline=outline, width=ow // 2) + draw.rectangle((s * 0.18, s * 0.58, s * 0.82, s * 0.69), fill=(255, 208, 46, 255), outline=outline, width=ow // 2) + # Holly leaves & berry accent + draw.ellipse((s * 0.64, s * 0.20, s * 0.88, s * 0.34), fill=(40, 184, 86, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.44, s * 0.22, s * 0.56, s * 0.34), fill=(255, 230, 90, 255), outline=outline, width=ow // 2) + + elif kind == 'snowflake': + import math + draw.ellipse((s * 0.14, s * 0.14, s * 0.86, s * 0.86), fill=(48, 168, 255, 255), outline=outline, width=ow) + cx, cy = s * 0.50, s * 0.50 + for i in range(6): + ang = i * (math.pi / 3) + x2 = cx + s * 0.30 * math.cos(ang) + y2 = cy + s * 0.30 * math.sin(ang) + draw.line((cx, cy, x2, y2), fill=(255, 255, 255, 255), width=6 * scale) + bx = cx + s * 0.19 * math.cos(ang) + by = cy + s * 0.19 * math.sin(ang) + for delta in (-0.55, 0.55): + tx = bx + s * 0.09 * math.cos(ang + delta) + ty = by + s * 0.09 * math.sin(ang + delta) + draw.line((bx, by, tx, ty), fill=(255, 255, 255, 255), width=4 * scale) + draw.ellipse((s * 0.42, s * 0.42, s * 0.58, s * 0.58), fill=(225, 248, 255, 255), outline=outline, width=ow // 2) + + elif kind == 'pumpkin': + # Stem + draw.polygon([(s * 0.45, s * 0.10), (s * 0.57, s * 0.10), (s * 0.54, s * 0.28), (s * 0.46, s * 0.28)], + fill=(46, 164, 72, 255), outline=outline, width=ow) + # Ribbed orange pumpkin lobes + draw.ellipse((s * 0.12, s * 0.24, s * 0.58, s * 0.88), fill=(242, 116, 28, 255), outline=outline, width=ow) + draw.ellipse((s * 0.42, s * 0.24, s * 0.88, s * 0.88), fill=(242, 116, 28, 255), outline=outline, width=ow) + draw.ellipse((s * 0.26, s * 0.22, s * 0.74, s * 0.90), fill=(255, 138, 36, 255), outline=outline, width=ow) + # Glowing jack-o'-lantern eyes & grin + draw.polygon([(s * 0.30, s * 0.48), (s * 0.40, s * 0.36), (s * 0.45, s * 0.48)], fill=(255, 232, 64, 255), outline=outline, width=ow // 2) + draw.polygon([(s * 0.55, s * 0.48), (s * 0.60, s * 0.36), (s * 0.70, s * 0.48)], fill=(255, 232, 64, 255), outline=outline, width=ow // 2) + draw.polygon([(s * 0.28, s * 0.64), (s * 0.50, s * 0.72), (s * 0.72, s * 0.64), (s * 0.64, s * 0.78), (s * 0.36, s * 0.78)], + fill=(255, 232, 64, 255), outline=outline, width=ow // 2) + + elif kind == 'globe': + draw.ellipse((s * 0.12, s * 0.12, s * 0.88, s * 0.88), fill=(36, 146, 245, 255), outline=outline, width=ow) + # Stylized green continents + draw.polygon([(s * 0.26, s * 0.30), (s * 0.46, s * 0.24), (s * 0.48, s * 0.46), (s * 0.34, s * 0.66), (s * 0.22, s * 0.50)], fill=(58, 204, 112, 255), outline=outline, width=ow // 2) + draw.polygon([(s * 0.56, s * 0.28), (s * 0.78, s * 0.36), (s * 0.74, s * 0.68), (s * 0.54, s * 0.58)], fill=(58, 204, 112, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.12, s * 0.12, s * 0.88, s * 0.88), outline=outline, width=ow) + + elif kind == 'compass': + draw.ellipse((s * 0.12, s * 0.12, s * 0.88, s * 0.88), fill=(245, 194, 48, 255), outline=outline, width=ow) + draw.ellipse((s * 0.20, s * 0.20, s * 0.80, s * 0.80), fill=(30, 42, 62, 255), outline=outline, width=ow // 2) + # North red pointer & South white pointer + draw.polygon([(s * 0.50, s * 0.24), (s * 0.60, s * 0.50), (s * 0.40, s * 0.50)], fill=(244, 54, 68, 255), outline=outline, width=ow // 2) + draw.polygon([(s * 0.50, s * 0.76), (s * 0.60, s * 0.50), (s * 0.40, s * 0.50)], fill=(245, 248, 255, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.45, s * 0.45, s * 0.55, s * 0.55), fill=(255, 214, 64, 255), outline=outline, width=ow // 2) + + elif kind == 'pin': + draw.polygon([(s * 0.24, s * 0.46), (s * 0.50, s * 0.90), (s * 0.76, s * 0.46)], fill=(238, 42, 62, 255), outline=outline, width=ow) + draw.ellipse((s * 0.20, s * 0.12, s * 0.80, s * 0.68), fill=(238, 42, 62, 255), outline=outline, width=ow) + draw.ellipse((s * 0.36, s * 0.26, s * 0.64, s * 0.54), fill=(255, 255, 255, 255), outline=outline, width=ow // 2) + + elif kind == 'plane': + # Sky badge + white/blue jet plane + draw.ellipse((s * 0.14, s * 0.14, s * 0.86, s * 0.86), fill=(46, 156, 255, 255), outline=outline, width=ow) + wings = [(s * 0.18, s * 0.56), (s * 0.82, s * 0.24), (s * 0.64, s * 0.82), (s * 0.48, s * 0.58), (s * 0.32, s * 0.68)] + draw.polygon(wings, fill=(250, 252, 255, 255), outline=outline, width=ow) + + elif kind == 'money': + # Tie top + plump golden money sack + draw.polygon([(s * 0.36, s * 0.14), (s * 0.64, s * 0.14), (s * 0.58, s * 0.30), (s * 0.42, s * 0.30)], + fill=(238, 188, 52, 255), outline=outline, width=ow) + draw.ellipse((s * 0.18, s * 0.26, s * 0.82, s * 0.90), fill=(246, 198, 58, 255), outline=outline, width=ow) + draw.ellipse((s * 0.34, s * 0.44, s * 0.66, s * 0.76), fill=(46, 192, 96, 255), outline=outline, width=ow // 2) + + elif kind == 'chart': + draw.rounded_rectangle((s * 0.12, s * 0.14, s * 0.88, s * 0.88), radius=14 * scale, fill=(245, 248, 255, 255), outline=outline, width=ow) + draw.rectangle((s * 0.22, s * 0.56, s * 0.36, s * 0.80), fill=(52, 152, 245, 255), outline=outline, width=ow // 2) + draw.rectangle((s * 0.43, s * 0.40, s * 0.57, s * 0.80), fill=(46, 204, 113, 255), outline=outline, width=ow // 2) + draw.rectangle((s * 0.64, s * 0.24, s * 0.78, s * 0.80), fill=(255, 196, 42, 255), outline=outline, width=ow // 2) + + elif kind == 'diamond': + gem = [(s * 0.28, s * 0.18), (s * 0.72, s * 0.18), (s * 0.90, s * 0.40), (s * 0.50, s * 0.88), (s * 0.10, s * 0.40)] + draw.polygon(gem, fill=(56, 214, 255, 255), outline=outline, width=ow) + draw.polygon([(s * 0.28, s * 0.18), (s * 0.72, s * 0.18), (s * 0.64, s * 0.40), (s * 0.36, s * 0.40)], + fill=(165, 242, 255, 255), outline=outline, width=ow // 2) + + elif kind == 'shield': + pts = [(s * 0.18, s * 0.14), (s * 0.82, s * 0.14), (s * 0.82, s * 0.50), (s * 0.50, s * 0.90), (s * 0.18, s * 0.50)] + draw.polygon(pts, fill=(42, 118, 238, 255), outline=outline, width=ow) + inner = [(s * 0.28, s * 0.22), (s * 0.72, s * 0.22), (s * 0.72, s * 0.48), (s * 0.50, s * 0.78), (s * 0.28, s * 0.48)] + draw.polygon(inner, fill=(255, 204, 46, 255), outline=outline, width=ow // 2) + + elif kind == 'swords': + # Crossed silver blades with gold guards + draw.polygon([(s * 0.16, s * 0.22), (s * 0.24, s * 0.14), (s * 0.84, s * 0.74), (s * 0.76, s * 0.82)], + fill=(224, 232, 245, 255), outline=outline, width=ow) + draw.polygon([(s * 0.84, s * 0.22), (s * 0.76, s * 0.14), (s * 0.16, s * 0.74), (s * 0.24, s * 0.82)], + fill=(224, 232, 245, 255), outline=outline, width=ow) + draw.ellipse((s * 0.40, s * 0.40, s * 0.60, s * 0.60), fill=(255, 204, 46, 255), outline=outline, width=ow) + + elif kind == 'rocket': + # Exhaust flame + draw.polygon([(s * 0.38, s * 0.72), (s * 0.50, s * 0.94), (s * 0.62, s * 0.72)], fill=(255, 112, 34, 255), outline=outline, width=ow // 2) + # Side fins + draw.polygon([(s * 0.20, s * 0.74), (s * 0.34, s * 0.52), (s * 0.36, s * 0.74)], fill=(235, 44, 58, 255), outline=outline, width=ow) + draw.polygon([(s * 0.80, s * 0.74), (s * 0.66, s * 0.52), (s * 0.64, s * 0.74)], fill=(235, 44, 58, 255), outline=outline, width=ow) + # Rocket fuselage & nose cone + draw.polygon([(s * 0.50, s * 0.08), (s * 0.68, s * 0.34), (s * 0.66, s * 0.74), (s * 0.34, s * 0.74), (s * 0.32, s * 0.34)], + fill=(248, 250, 255, 255), outline=outline, width=ow) + draw.polygon([(s * 0.50, s * 0.08), (s * 0.66, s * 0.30), (s * 0.34, s * 0.30)], + fill=(235, 44, 58, 255), outline=outline, width=ow) + draw.ellipse((s * 0.40, s * 0.38, s * 0.60, s * 0.58), fill=(58, 198, 255, 255), outline=outline, width=ow // 2) + + elif kind == 'bolt': + bolt_pts = [ + (s * 0.56, s * 0.08), + (s * 0.22, s * 0.54), + (s * 0.48, s * 0.54), + (s * 0.38, s * 0.92), + (s * 0.78, s * 0.44), + (s * 0.52, s * 0.44), + ] + draw.polygon(bolt_pts, fill=(255, 214, 36, 255), outline=outline, width=ow) + + elif kind == 'fire': + outer_flame = [(s * 0.50, s * 0.08), (s * 0.82, s * 0.48), (s * 0.74, s * 0.84), (s * 0.50, s * 0.92), (s * 0.26, s * 0.84), (s * 0.18, s * 0.48)] + inner_flame = [(s * 0.50, s * 0.32), (s * 0.68, s * 0.58), (s * 0.62, s * 0.82), (s * 0.50, s * 0.88), (s * 0.38, s * 0.82), (s * 0.32, s * 0.58)] + draw.polygon(outer_flame, fill=(255, 86, 34, 255), outline=outline, width=ow) + draw.polygon(inner_flame, fill=(255, 214, 46, 255), outline=outline, width=ow // 2) + + elif kind == 'trophy': + # Handles + draw.ellipse((s * 0.12, s * 0.22, s * 0.40, s * 0.52), fill=(255, 204, 38, 255), outline=outline, width=ow) + draw.ellipse((s * 0.60, s * 0.22, s * 0.88, s * 0.52), fill=(255, 204, 38, 255), outline=outline, width=ow) + # Cup body + stem + base + draw.polygon([(s * 0.24, s * 0.16), (s * 0.76, s * 0.16), (s * 0.66, s * 0.58), (s * 0.34, s * 0.58)], + fill=(255, 214, 46, 255), outline=outline, width=ow) + draw.rectangle((s * 0.44, s * 0.56, s * 0.56, s * 0.76), fill=(235, 180, 28, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.28, s * 0.74, s * 0.72, s * 0.88), radius=8 * scale, fill=(215, 152, 24, 255), outline=outline, width=ow) + + elif kind == 'crown': + crown_pts = [ + (s * 0.14, s * 0.78), + (s * 0.10, s * 0.28), + (s * 0.34, s * 0.52), + (s * 0.50, s * 0.18), + (s * 0.66, s * 0.52), + (s * 0.90, s * 0.28), + (s * 0.86, s * 0.78), + ] + draw.polygon(crown_pts, fill=(255, 204, 38, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.14, s * 0.74, s * 0.86, s * 0.88), radius=8 * scale, fill=(235, 168, 20, 255), outline=outline, width=ow) + draw.ellipse((s * 0.45, s * 0.56, s * 0.55, s * 0.66), fill=(244, 42, 75, 255), outline=outline, width=ow // 2) + + elif kind == 'star': + pts = _star_polygon(s * 0.50, s * 0.52, outer_r=s * 0.40, inner_r=s * 0.18) + draw.polygon(pts, fill=(255, 216, 46, 255), outline=outline, width=ow) + + elif kind == 'heart': + _draw_heart(draw, s * 0.50, s * 0.52, s * 0.78, fill=(255, 42, 78, 255), outline=outline, width=ow) + + elif kind == 'skull': + draw.rounded_rectangle((s * 0.32, s * 0.56, s * 0.68, s * 0.88), radius=10 * scale, fill=(245, 247, 252, 255), outline=outline, width=ow) + draw.ellipse((s * 0.18, s * 0.14, s * 0.82, s * 0.74), fill=(245, 247, 252, 255), outline=outline, width=ow) + draw.ellipse((s * 0.28, s * 0.36, s * 0.44, s * 0.52), fill=outline) + draw.ellipse((s * 0.56, s * 0.36, s * 0.72, s * 0.52), fill=outline) + draw.polygon([(s * 0.50, s * 0.50), (s * 0.45, s * 0.60), (s * 0.55, s * 0.60)], fill=outline) + + elif kind == 'bear': + # Round ears + warm inner ears + draw.ellipse((s * 0.12, s * 0.12, s * 0.42, s * 0.42), fill=(142, 82, 42, 255), outline=outline, width=ow) + draw.ellipse((s * 0.58, s * 0.12, s * 0.88, s * 0.42), fill=(142, 82, 42, 255), outline=outline, width=ow) + draw.ellipse((s * 0.19, s * 0.19, s * 0.35, s * 0.35), fill=(216, 158, 108, 255)) + draw.ellipse((s * 0.65, s * 0.19, s * 0.81, s * 0.35), fill=(216, 158, 108, 255)) + # Plump brown bear head + draw.ellipse((s * 0.16, s * 0.22, s * 0.84, s * 0.88), fill=(158, 94, 48, 255), outline=outline, width=ow) + # Light tan muzzle + dark nose + draw.ellipse((s * 0.32, s * 0.48, s * 0.68, s * 0.78), fill=(234, 192, 146, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.42, s * 0.50, s * 0.58, s * 0.62), fill=outline) + # Eyes + draw.ellipse((s * 0.31, s * 0.38, s * 0.39, s * 0.46), fill=outline) + draw.ellipse((s * 0.61, s * 0.38, s * 0.69, s * 0.46), fill=outline) + + elif kind == 'paw': + draw.ellipse((s * 0.12, s * 0.12, s * 0.88, s * 0.88), fill=(252, 211, 77, 255), outline=outline, width=ow) + pad_color = (120, 53, 15, 255) + draw.ellipse((s * 0.30, s * 0.48, s * 0.70, s * 0.78), fill=pad_color, outline=outline, width=ow // 2) + for px, py in ((0.24, 0.34), (0.39, 0.24), (0.61, 0.24), (0.76, 0.34)): + draw.ellipse((s * (px - 0.08), s * (py - 0.09), s * (px + 0.08), s * (py + 0.09)), fill=pad_color, outline=outline, width=ow // 2) + + elif kind == 'tree': + draw.rectangle((s * 0.42, s * 0.68, s * 0.58, s * 0.90), fill=(132, 78, 42, 255), outline=outline, width=ow) + draw.polygon([(s * 0.50, s * 0.34), (s * 0.86, s * 0.74), (s * 0.14, s * 0.74)], fill=(22, 163, 74, 255), outline=outline, width=ow) + draw.polygon([(s * 0.50, s * 0.20), (s * 0.80, s * 0.56), (s * 0.20, s * 0.56)], fill=(34, 197, 94, 255), outline=outline, width=ow) + draw.polygon([(s * 0.50, s * 0.08), (s * 0.72, s * 0.38), (s * 0.28, s * 0.38)], fill=(74, 222, 128, 255), outline=outline, width=ow) + + elif kind == 'wolf': + draw.polygon([(s * 0.18, s * 0.42), (s * 0.22, s * 0.10), (s * 0.42, s * 0.28)], fill=(100, 116, 139, 255), outline=outline, width=ow) + draw.polygon([(s * 0.82, s * 0.42), (s * 0.78, s * 0.10), (s * 0.58, s * 0.28)], fill=(100, 116, 139, 255), outline=outline, width=ow) + draw.polygon([(s * 0.16, s * 0.38), (s * 0.50, s * 0.22), (s * 0.84, s * 0.38), (s * 0.76, s * 0.68), (s * 0.50, s * 0.88), (s * 0.24, s * 0.68)], + fill=(148, 163, 184, 255), outline=outline, width=ow) + draw.polygon([(s * 0.34, s * 0.54), (s * 0.50, s * 0.88), (s * 0.66, s * 0.54)], fill=(241, 245, 249, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.32, s * 0.42, s * 0.42, s * 0.50), fill=(250, 204, 21, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.58, s * 0.42, s * 0.68, s * 0.50), fill=(250, 204, 21, 255), outline=outline, width=ow // 2) + draw.ellipse((s * 0.44, s * 0.74, s * 0.56, s * 0.84), fill=outline) + + elif kind == 'beer': + draw.rounded_rectangle((s * 0.62, s * 0.38, s * 0.86, s * 0.76), radius=12 * scale, outline=outline, width=ow) + draw.rounded_rectangle((s * 0.22, s * 0.28, s * 0.70, s * 0.88), radius=10 * scale, fill=(245, 158, 11, 255), outline=outline, width=ow) + for fx in (0.28, 0.44, 0.60): + draw.ellipse((s * (fx - 0.12), s * 0.14, s * (fx + 0.12), s * 0.38), fill=(255, 255, 255, 255), outline=outline, width=ow // 2) + + elif kind == 'coffee': + draw.rounded_rectangle((s * 0.64, s * 0.42, s * 0.86, s * 0.70), radius=12 * scale, outline=outline, width=ow) + draw.chord((s * 0.18, s * 0.28, s * 0.74, s * 0.84), start=0, end=180, fill=(248, 250, 252, 255), outline=outline, width=ow) + draw.ellipse((s * 0.18, s * 0.32, s * 0.74, s * 0.48), fill=(120, 53, 15, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.12, s * 0.78, s * 0.82, s * 0.88), radius=6 * scale, fill=(226, 232, 240, 255), outline=outline, width=ow) + + elif kind == 'wine': + draw.polygon([(s * 0.28, s * 0.14), (s * 0.72, s * 0.14), (s * 0.64, s * 0.54), (s * 0.36, s * 0.54)], fill=(225, 29, 72, 255), outline=outline, width=ow) + draw.rectangle((s * 0.47, s * 0.54, s * 0.53, s * 0.82), fill=(226, 232, 240, 255), outline=outline, width=ow // 2) + draw.rounded_rectangle((s * 0.32, s * 0.80, s * 0.68, s * 0.88), radius=6 * scale, fill=(226, 232, 240, 255), outline=outline, width=ow) + + elif kind == 'pizza': + draw.polygon([(s * 0.50, s * 0.88), (s * 0.16, s * 0.22), (s * 0.84, s * 0.22)], fill=(250, 204, 21, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.14, s * 0.14, s * 0.86, s * 0.28), radius=10 * scale, fill=(217, 119, 6, 255), outline=outline, width=ow) + for px, py in ((0.40, 0.40), (0.58, 0.44), (0.48, 0.62)): + draw.ellipse((s * (px - 0.07), s * (py - 0.07), s * (px + 0.07), s * (py + 0.07)), fill=(220, 38, 38, 255), outline=outline, width=ow // 2) + + elif kind == 'soccer': + draw.ellipse((s * 0.12, s * 0.12, s * 0.88, s * 0.88), fill=(248, 250, 252, 255), outline=outline, width=ow) + pent = _star_polygon(s * 0.50, s * 0.50, outer_r=s * 0.18, inner_r=s * 0.15) + draw.polygon(pent, fill=outline) + for vx, vy in pent[::2]: + draw.line((vx, vy, s * 0.50 + (vx - s * 0.50) * 2.0, s * 0.50 + (vy - s * 0.50) * 2.0), fill=outline, width=ow // 2) + + elif kind == 'car': + draw.polygon([(s * 0.24, s * 0.48), (s * 0.36, s * 0.28), (s * 0.66, s * 0.28), (s * 0.78, s * 0.48)], fill=(56, 189, 248, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.12, s * 0.46, s * 0.88, s * 0.74), radius=12 * scale, fill=(239, 68, 68, 255), outline=outline, width=ow) + draw.ellipse((s * 0.20, s * 0.62, s * 0.38, s * 0.80), fill=(30, 41, 59, 255), outline=outline, width=ow) + draw.ellipse((s * 0.62, s * 0.62, s * 0.80, s * 0.80), fill=(30, 41, 59, 255), outline=outline, width=ow) + + elif kind == 'brain': + for bx in (0.36, 0.64): + draw.ellipse((s * (bx - 0.22), s * 0.18, s * (bx + 0.22), s * 0.82), fill=(244, 114, 182, 255), outline=outline, width=ow) + draw.line((s * 0.50, s * 0.18, s * 0.50, s * 0.82), fill=outline, width=ow) + + elif kind == 'book': + draw.rounded_rectangle((s * 0.18, s * 0.58, s * 0.84, s * 0.82), radius=8 * scale, fill=(59, 130, 246, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.16, s * 0.38, s * 0.82, s * 0.62), radius=8 * scale, fill=(16, 185, 129, 255), outline=outline, width=ow) + draw.rounded_rectangle((s * 0.20, s * 0.18, s * 0.86, s * 0.42), radius=8 * scale, fill=(244, 63, 94, 255), outline=outline, width=ow) + + elif kind == 'sun': + pts = _star_polygon(s * 0.50, s * 0.50, outer_r=s * 0.42, inner_r=s * 0.28) + draw.polygon(pts, fill=(251, 146, 60, 255), outline=outline, width=ow) + draw.ellipse((s * 0.24, s * 0.24, s * 0.76, s * 0.76), fill=(250, 204, 21, 255), outline=outline, width=ow) + + if gen_style: + final_img = _style_generated_sticker(canvas, gen_style, size) + else: + final_img = canvas.resize((size, size), Image.Resampling.LANCZOS) + if effects: + final_img = _with_shadow(final_img) + return np.array(final_img) + + +def _apply_clip_fade_in(clip, total_duration: float, fade_start: float = 0.0, fade_duration: float = 0.6): + """Smoothly fade a clip's alpha mask in starting at ``fade_start`` over ``fade_duration`` seconds.""" + import numpy as np + from moviepy import VideoClip + + if fade_start <= 0.0 and fade_duration <= 0.0: + return clip.with_duration(total_duration) + base_frame = clip.get_frame(0) + if base_frame.ndim == 3 and base_frame.shape[2] == 4: + base_mask = base_frame[:, :, 3].astype(np.float32) / 255.0 + elif clip.mask is not None: + base_mask = clip.mask.get_frame(0).astype(np.float32) + else: + base_mask = np.ones((clip.h, clip.w), dtype=np.float32) + + def _mask_frame(t: float) -> np.ndarray: + if t < fade_start: + return np.zeros_like(base_mask) + if fade_duration <= 0.0 or t >= fade_start + fade_duration: + return base_mask + alpha = float((t - fade_start) / fade_duration) + return base_mask * max(0.0, min(1.0, alpha)) + + mask_clip = VideoClip(_mask_frame, is_mask=True, duration=total_duration) + return clip.with_duration(total_duration).with_mask(mask_clip) + + @app.route('/api/video_title_preview', methods=['POST']) def video_title_preview(): from PIL import Image data = request.get_json(silent=True) or {} + preview_kind = str(data.get('preview_kind') or 'title').strip() title = str(data.get('video_title') or '').strip() - if not title or len(title) > 1000: + if preview_kind in ('title', 'watermark') and (not title or len(title) > 1000): return jsonify(error='Enter a title of up to 1000 characters.'), 400 try: font_path, font_size = _title_settings(data) first_color, other_color = _title_colors(data) effects = data.get('visual_effects', True) is not False - if data.get('preview_kind') == 'watermark': + title_uppercase = data.get('title_uppercase', True) is not False + if preview_kind == 'watermark': text, color = _watermark_settings(data) image = _title_image(text, 936, _watermark_font_path(data), 96, color, color, effects, max_height=110) + elif preview_kind == 'subscribe': + sub_text = str(data.get('subscribe_text') or 'Subscribe!').strip()[:40] or 'Subscribe!' + image = _subscribe_badge_image(sub_text, font_path, effects) + elif preview_kind == 'stars': + _, color = _watermark_settings(data) + image = _stars_row_image(color, effects) + elif preview_kind == 'sticker': + raw_sticker = str(data.get('sticker_kind') or 'santa').strip().lower() + side = str(data.get('sticker_side') or 'left').strip().lower() + gen_style, base_kind = _parse_sticker_spec(raw_sticker, title=title, side=side) + sticker_kind = f'gen_{gen_style}:{base_kind}' if gen_style else base_kind + image = _sticker_image( + sticker_kind, + size=140, + effects=effects, + allow_remote=bool(data.get('allow_remote_stickers', True)), + ) + if image is None: + return jsonify(error='Unknown sticker kind.'), 400 else: - image = _title_image(title, 1040, font_path, font_size, first_color, other_color, effects) + image = _title_image(title, 1040, font_path, font_size, first_color, + other_color, effects, uppercase=title_uppercase) except ValueError as error: return jsonify(error=str(error)), 400 output = io.BytesIO() @@ -488,17 +1319,26 @@ def _decode_material(value: str, label: str) -> bytes: try: map_bytes = _decode_material(map_b64, "map_file") bg_bytes = _decode_material(background_b64, "background_video") - watermark_bytes = _decode_material(str(data['watermark_image']), 'watermark_image') if data.get('watermark_image') else None - from PIL import Image, UnidentifiedImageError - watermark_image = None - if watermark_bytes: + from PIL import Image, ImageOps, UnidentifiedImageError + + def _decode_optional_image(field: str, label: str): + raw_val = data.get(field) + if not raw_val: + return None + raw_bytes = _decode_material(str(raw_val), field) try: - with Image.open(io.BytesIO(watermark_bytes)) as uploaded: + with Image.open(io.BytesIO(raw_bytes)) as uploaded: if uploaded.width * uploaded.height > 20_000_000: - raise ValueError('Watermark image must be at most 20 megapixels.') - watermark_image = uploaded.convert('RGBA') + raise ValueError(f'{label} image must be at most 20 megapixels.') + return uploaded.convert('RGBA') except (UnidentifiedImageError, OSError, Image.DecompressionBombError): - raise ValueError('Watermark must be a valid image.') + raise ValueError(f'{label} must be a valid image.') + + watermark_image = _decode_optional_image('watermark_image', 'Watermark') + subscribe_custom_img = _decode_optional_image('subscribe_image', 'Subscribe') + watermark_stars_custom_img = _decode_optional_image('watermark_stars_image', 'Watermark stars') + top_left_custom_img = _decode_optional_image('top_left_sticker_image', 'Top-left sticker') + top_right_custom_img = _decode_optional_image('top_right_sticker_image', 'Top-right sticker') except ValueError as ve: return jsonify({"status": "error", "error": str(ve)}), 400 @@ -588,14 +1428,80 @@ def soften(frame): scrim = ImageClip(shade).with_duration(bg_duration) # Anchor the headline near the top and let the map fill the space below. - title_clip = _build_title_clip(title, bg_duration, 1040, font_path, - font_size, first_color, other_color, effects) + title_uppercase = data.get('title_uppercase', True) is not False + allow_remote_stickers = data.get('allow_remote_stickers', True) is not False + left_gen, left_base = _parse_sticker_spec(str(data.get('top_left_sticker') or 'none'), title=title, side='left') + right_gen, right_base = _parse_sticker_spec(str(data.get('top_right_sticker') or 'none'), title=title, side='right') + top_left_sticker = f'gen_{left_gen}:{left_base}' if left_gen else left_base + top_right_sticker = f'gen_{right_gen}:{right_base}' if right_gen else right_base + + if top_left_custom_img is not None: + left_pil = ImageOps.contain(top_left_custom_img, (140, 140), method=Image.Resampling.LANCZOS) + if effects: + left_pil = _with_shadow(left_pil) + left_sticker_arr = np.array(left_pil) + else: + left_sticker_arr = _sticker_image(top_left_sticker, size=140, effects=effects, allow_remote=allow_remote_stickers) + + if top_right_custom_img is not None: + right_pil = ImageOps.contain(top_right_custom_img, (140, 140), method=Image.Resampling.LANCZOS) + if effects: + right_pil = _with_shadow(right_pil) + right_sticker_arr = np.array(right_pil) + else: + right_sticker_arr = _sticker_image(top_right_sticker, size=140, effects=effects, allow_remote=allow_remote_stickers) + + has_top_stickers = left_sticker_arr is not None or right_sticker_arr is not None + + subscribe_enabled = bool(data.get('subscribe_badge', False)) + subscribe_text = str(data.get('subscribe_text') or 'Subscribe!').strip()[:40] or 'Subscribe!' + try: + subscribe_delay = float(data.get('subscribe_delay', 2.5)) + except (TypeError, ValueError): + subscribe_delay = 2.5 + subscribe_delay = max(0.0, min(25.0, subscribe_delay)) + + watermark_stars = bool(data.get('watermark_stars', False)) + has_stars = bool(watermark_stars or watermark_stars_custom_img is not None) + intro_fade = bool(data.get('intro_fade', False)) + + title_clip = _build_title_clip( + title, + bg_duration, + 1040, + font_path, + font_size, + first_color, + other_color, + effects, + uppercase=title_uppercase, + ) map_clip = ImageClip(map_path).with_duration(bg_duration) - title_top, gap = 70, 16 - map_top = title_top + title_clip.h + gap - branded = bool(watermark_image is not None or watermark_text) + title_top = 175 if has_top_stickers else 70 + gap = 16 + + subscribe_clip = None + subscribe_top = title_top + title_clip.h + 8 + if subscribe_custom_img is not None or subscribe_enabled: + if subscribe_custom_img is not None: + sub_pil = ImageOps.contain(subscribe_custom_img, (680, 115), method=Image.Resampling.LANCZOS) + if effects: + sub_pil = _with_shadow(sub_pil) + sub_arr = np.array(sub_pil) + else: + sub_arr = _subscribe_badge_image(subscribe_text, font_path, effects) + subscribe_clip = ImageClip(sub_arr).with_duration(bg_duration) + fade_start = min(subscribe_delay, max(0.0, bg_duration - 0.5)) if bg_duration > 1.0 else 0.0 + fade_dur = min(0.6, max(0.15, bg_duration - fade_start)) if bg_duration > 0.4 else 0.0 + 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', subscribe_top)) + map_top = subscribe_top + subscribe_clip.h + gap + else: + map_top = title_top + title_clip.h + gap + + branded = bool(watermark_image is not None or watermark_text or has_stars) map_bottom = 1450 if branded else 1760 - map_area_height = map_bottom - map_top + map_area_height = max(240, map_bottom - map_top) # Fit both dimensions so the whole map stays inside the space below the title. scale = min(1040 / map_clip.w, map_area_height / map_clip.h) map_clip = map_clip.resized(scale) @@ -605,6 +1511,16 @@ def soften(frame): title_clip = title_clip.with_position(("center", title_top)) map_clip = map_clip.with_position(("center", map_top - (24 if effects else 0))) clips = [background_video, scrim, map_clip, title_clip] + + if left_sticker_arr is not None: + left_clip = ImageClip(left_sticker_arr).with_duration(bg_duration) + clips.append(left_clip.with_position((145, 16))) + if right_sticker_arr is not None: + right_clip = ImageClip(right_sticker_arr).with_duration(bg_duration) + clips.append(right_clip.with_position((canvas_w - 145 - right_clip.w, 16))) + if subscribe_clip is not None: + clips.append(subscribe_clip) + if watermark_image is not None: watermark_image = _round_watermark(watermark_image) logo_top = 1470 @@ -617,7 +1533,37 @@ def soften(frame): lettering = _title_image(watermark_text, 936, watermark_font_path, 96, watermark_color, watermark_color, effects, max_height=110) branding = ImageClip(lettering).with_duration(bg_duration) - clips.append(branding.with_position(('center', 1740))) + watermark_y = 1695 if has_stars else 1740 + clips.append(branding.with_position(('center', watermark_y))) + if has_stars: + if watermark_stars_custom_img is not None: + stars_pil = ImageOps.contain(watermark_stars_custom_img, (480, 95), method=Image.Resampling.LANCZOS) + if effects: + stars_pil = _with_shadow(stars_pil) + stars_arr = np.array(stars_pil) + else: + stars_arr = _stars_row_image(watermark_color or '#ffffff', effects) + stars_clip = ImageClip(stars_arr).with_duration(bg_duration) + 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_y = 1805 if watermark_text else 1785 + clips.append(stars_clip.with_position(('center', stars_y))) + if intro_fade: + from moviepy import VideoClip + fade_in_dur = min(0.75, max(0.2, bg_duration * 0.3)) + black_frame = np.zeros((canvas_h, canvas_w, 3), dtype=np.uint8) + intro_veil = ImageClip(black_frame).with_duration(fade_in_dur) + base_ones = np.ones((canvas_h, canvas_w), dtype=np.float32) + + def _veil_mask(t: float) -> np.ndarray: + if t >= fade_in_dur or fade_in_dur <= 0: + return np.zeros_like(base_ones) + alpha = 0.88 * (1.0 - float(t / fade_in_dur)) + return base_ones * max(0.0, min(1.0, alpha)) + + veil_mask = VideoClip(_veil_mask, is_mask=True, duration=fade_in_dur) + clips.append(intro_veil.with_mask(veil_mask)) final_clip = CompositeVideoClip(clips, size=(canvas_w, canvas_h)) media_resources.append(final_clip) From 54e41c1b81d7660a5a8f170312ac0229a03ba71d Mon Sep 17 00:00:00 2001 From: bibed234 Date: Sat, 14 Nov 2026 16:32:01 +0200 Subject: [PATCH 2/4] Fix Color Filling Studio backend endpoints, image inspection, and optimize code --- main.py | 348 +++++++++++++++++++--- map/auto_map.py | 368 +++++++++++++++++++----- map/functions.py | 21 +- map/log.py | 9 +- resources/othr/white_pixels_cleaning.py | 17 +- tests/test_auto_map.py | 36 +++ tests/test_web.py | 89 ++++++ yt-dlp_serv.py | 12 +- 8 files changed, 748 insertions(+), 152 deletions(-) diff --git a/main.py b/main.py index c95398e..b744d2f 100644 --- a/main.py +++ b/main.py @@ -21,11 +21,16 @@ value is forwarded to the generation request only. """ +import ast +import base64 +import io import os import re import time from pathlib import Path +from PIL import Image, UnidentifiedImageError +import requests # auto_map() loads fonts/maps via *relative* paths ("resources/fonts", ...), # so the process must run from the AutoMap-cli project directory. Anchor the @@ -44,8 +49,11 @@ from map.auto_map import ( auto_map, _auto_fill_from_ai, - LAST_GENERATED_MAP_STATE, + _parse_short_number, + _resolve_theme_name, + _to_rgba_tuple, ) +from map.constants import europe_coords, world_coords from flask import Flask, request, jsonify, send_file, render_template, Response @@ -157,47 +165,87 @@ def api_status(): def _build_analysis_from_ai( ai_answer: dict[str, object], mode: str = "auto", + palette_theme: str = "auto", + topic: str = "", + render_meta: dict[str, object] | None = None, ) -> dict[str, object]: - """Build UI-friendly color rules and stats directly from AI map values.""" + """Build UI-friendly color rules and stats from AI map values or render metadata.""" vals = [v for v in ai_answer.values() if v is not None and str(v).strip() != ""] num_vals: list[int] = [] for v in vals: - if isinstance(v, bool): - continue - try: - num_vals.append(int(float(str(v).replace(",", "").strip()))) - except (ValueError, TypeError): - pass + parsed = _parse_short_number(v) + if parsed is not None: + num_vals.append(int(round(parsed))) resolved_mode = mode if mode in ("number", "text") else ( "number" if vals and len(num_vals) >= max(1, int(len(vals) * 0.6)) else "text" ) - auto_txt, auto_num = _auto_fill_from_ai(ai_answer, resolved_mode) + resolved_theme = ( + str(render_meta.get("resolved_theme")) + if isinstance(render_meta, dict) and render_meta.get("resolved_theme") + else _resolve_theme_name(palette_theme, prompt=topic, mode=resolved_mode) + ) + + txt_dict: dict[str, tuple[int, int, int, int]] = {} + num_dict: dict[tuple[int, int], tuple[int, int, int, int]] = {} + + if isinstance(render_meta, dict): + raw_txt = render_meta.get("used_txt") or render_meta.get("filling_txt") + if isinstance(raw_txt, dict) and raw_txt: + for k, v in raw_txt.items(): + rgba = _to_rgba_tuple(v) + if rgba is not None: + txt_dict[str(k)] = rgba + raw_num = render_meta.get("used_num") or render_meta.get("filling_num") + if isinstance(raw_num, dict) and raw_num: + for k, v in raw_num.items(): + rgba = _to_rgba_tuple(v) + if rgba is None: + continue + try: + b = k if isinstance(k, tuple) else ast.literal_eval(str(k)) + if isinstance(b, (list, tuple)) and len(b) == 2: + num_dict[(int(float(b[0])), int(float(b[1])))] = rgba + except (ValueError, SyntaxError, TypeError): + continue + + if not txt_dict and not num_dict: + txt_dict, num_dict = _auto_fill_from_ai( + ai_answer, + resolved_mode, + palette_theme=palette_theme, + prompt=topic, + ) ui_txt_rules = [ {"key": str(k), "hex": f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}", "alpha": c[3]} - for k, c in auto_txt.items() + for k, c in txt_dict.items() ] ui_num_rules = [ {"low": lo, "high": hi, "hex": f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}", "alpha": c[3]} - for (lo, hi), c in auto_num.items() + for (lo, hi), c in num_dict.items() ] + + default_label_style = { + "text_color": "#ffffff", + "stroke_color": "#090d16", + "stroke_width": 15, + "auto_fit": True, + "recommended_font": "Bips.ttf" if resolved_mode == "number" else "DIN Condensed.ttf", + "recommended_gsm": 15, + } + if isinstance(render_meta, dict) and isinstance(render_meta.get("label_style"), dict): + default_label_style.update(render_meta["label_style"]) + return { "detected_type": resolved_mode, "resolved_mode": resolved_mode, - "resolved_theme": "auto", - "filling_txt": {str(k): list(c) for k, c in auto_txt.items()}, - "filling_num": {f"({lo}, {hi})": list(c) for (lo, hi), c in auto_num.items()}, + "resolved_theme": resolved_theme, + "filling_txt": {str(k): list(c) for k, c in txt_dict.items()}, + "filling_num": {f"({lo}, {hi})": list(c) for (lo, hi), c in num_dict.items()}, "ui_txt_rules": ui_txt_rules, "ui_num_rules": ui_num_rules, - "label_style": { - "text_color": "#ffffff", - "stroke_color": "#090d16", - "stroke_width": 15, - "auto_fit": True, - "recommended_font": "Bips.ttf" if resolved_mode == "number" else "DIN Condensed.ttf", - "recommended_gsm": 15, - }, + "label_style": default_label_style, "stats": { "total_regions": len(vals), "unique_values": len({str(v).strip().lower() for v in vals}), @@ -208,6 +256,124 @@ def _build_analysis_from_ai( } +def _inspect_uploaded_map_image( + image_data: object, + map_type: str = "default", + palette_theme: str = "auto", +) -> tuple[dict[str, object], dict[str, object]]: + """Decode and inspect an uploaded map image's region fill colors.""" + if not isinstance(image_data, str) or not image_data.strip(): + raise ValueError("Empty image data.") + raw_b64 = image_data.strip() + if "," in raw_b64 and raw_b64.lower().startswith("data:"): + header, raw_b64 = raw_b64.split(",", 1) + if not header.lower().startswith("data:image/"): + raise ValueError("Unsupported data URL media type.") + try: + decoded = base64.b64decode(raw_b64, validate=True) + except Exception as exc: + raise ValueError("Invalid base64 image payload.") from exc + if not decoded: + raise ValueError("Decoded image payload is empty.") + try: + with Image.open(io.BytesIO(decoded)) as opened: + img = opened.convert("RGBA") + except (UnidentifiedImageError, OSError, ValueError) as exc: + raise ValueError("Uploaded file is not a valid image.") from exc + + width, height = img.size + if width < 8 or height < 8: + raise ValueError("Uploaded map image is too small to inspect.") + + ref_coords = world_coords if map_type == "world" else europe_coords + base_name = "world_map.png" if map_type == "world" else "default_map.png" + base_path = BASE_DIR / "resources" / "maps" / base_name + ref_w, ref_h = (2200, 1800) + if base_path.is_file(): + try: + with Image.open(base_path) as ref_img: + ref_w, ref_h = ref_img.size + except OSError: + pass + + px = img.load() + clusters: list[tuple[int, int, int, int]] = [] + region_values: dict[str, str] = {} + rule_colors: dict[str, tuple[int, int, int, int]] = {} + scale_x = width / max(1, ref_w) + scale_y = height / max(1, ref_h) + + for name, points in ref_coords.items(): + if not points: + continue + px_x, px_y = points[0] + sx = max(0, min(width - 1, int(round(px_x * scale_x)))) + sy = max(0, min(height - 1, int(round(px_y * scale_y)))) + samples: list[tuple[int, int, int, int]] = [] + for dx in (-6, 0, 6): + cx = max(0, min(width - 1, sx + dx)) + for dy in (-6, 0, 6): + cy = max(0, min(height - 1, sy + dy)) + r, g, b, a = px[cx, cy] + if a >= 32 and (r + g + b) > 35: + samples.append((r, g, b, 255)) + if not samples: + r, g, b, a = px[sx, sy] + samples.append((r, g, b, 255 if a >= 32 else a)) + + avg = ( + int(round(sum(p[0] for p in samples) / len(samples))), + int(round(sum(p[1] for p in samples) / len(samples))), + int(round(sum(p[2] for p in samples) / len(samples))), + 255, + ) + matched: tuple[int, int, int, int] | None = None + for existing in clusters: + dist = abs(avg[0] - existing[0]) + abs(avg[1] - existing[1]) + abs(avg[2] - existing[2]) + if dist <= 36: + matched = existing + break + if matched is None: + clusters.append(avg) + matched = avg + + hex_label = f"#{matched[0]:02x}{matched[1]:02x}{matched[2]:02x}" + region_values[name] = hex_label + rule_colors.setdefault(hex_label, matched) + + meta = { + "resolved_theme": palette_theme if palette_theme and palette_theme != "auto" else "inspected", + "used_txt": {k: list(v) for k, v in rule_colors.items()}, + } + analysis = _build_analysis_from_ai( + region_values, + mode="text", + palette_theme=palette_theme, + render_meta=meta, + ) + return region_values, analysis + + +def _parse_render_params(data: dict[str, object]) -> tuple[str, str | None, int]: + """Validate font, normalize extra_option, and parse gsm safely.""" + font_name = data.get("font") + if font_name not in _available_fonts(): + font_name = "Bips.ttf" + + extra_option = data.get("extra_option") + if extra_option in ("none", "", None): + extra_option = None + else: + extra_option = str(extra_option) + + try: + gsm = int(data.get("gsm", 15)) + except (TypeError, ValueError): + gsm = 15 + + return str(font_name), extra_option, gsm + + @app.route('/api/generate/', methods=['POST']) @app.route('/api/generate', methods=['POST']) def generate(): @@ -219,7 +385,6 @@ def generate(): Response JSON: { "status": "success", "command": "...", "image_url": "data:image/png;base64,..." } """ - import base64 data = request.get_json(silent=True) or {} # Optional user-supplied key (used only when .env has none). @@ -230,18 +395,7 @@ def generate(): # Validate the requested font against what is actually on disk, otherwise # auto_map would raise FileNotFoundError when loading the TrueType file. - font_name = data.get('font') - if font_name not in _available_fonts(): - font_name = "Bips.ttf" - - extra_option = data.get('extra_option') - if extra_option in ("none", "", None): - extra_option = None - - try: - gsm = int(data.get('gsm', 15)) - except (TypeError, ValueError): - gsm = 15 + font_name, extra_option, gsm = _parse_render_params(data) # Rebuild the equivalent CLI command for display only; it is never executed. command = ( @@ -251,6 +405,17 @@ def generate(): f"--model {data.get('model', 'gemini-2.5-flash')} --font \"{font_name}\"" ) + style_kwargs: dict[str, object] = {} + for style_key, kw_name in ( + ("filling_txt", "filling_txt_override"), + ("filling_num", "filling_num_override"), + ("label_style", "label_style"), + ("auto_style", "auto_style"), + ("palette_theme", "palette_theme"), + ): + if style_key in data: + style_kwargs[kw_name] = data[style_key] + try: buffer = auto_map( prompt=data['topic'], @@ -263,6 +428,7 @@ def generate(): show_result=False, io_res=True, api_key=api_key, + **style_kwargs, ) except KeyError as e: return jsonify({"status": "error", "command": command, @@ -284,30 +450,119 @@ def generate(): "command": command, "image_url": f"data:image/png;base64,{encoded}", } - ai_vals = LAST_GENERATED_MAP_STATE.get("ai_answer") + render_meta = getattr(buffer, "map_meta", None) + 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"] = ai_vals - resp_payload["analysis"] = _build_analysis_from_ai(ai_vals, str(data.get("mode") or "auto")) + resp_payload["analysis"] = _build_analysis_from_ai( + ai_vals, + mode=str(data.get("mode") or "auto"), + palette_theme=str(data.get("palette_theme") or "auto"), + topic=str(data.get("topic") or ""), + render_meta=render_meta, + ) return jsonify(resp_payload) +@app.route('/api/restyle_map/', methods=['POST']) +@app.route('/api/restyle_map', methods=['POST']) +def api_restyle_map(): + """Repaint the map from existing map_values without making another AI request.""" + data = request.get_json(silent=True) or {} + map_values = data.get("map_values") + if not isinstance(map_values, dict) or not map_values: + return jsonify({ + "status": "error", + "error": "No map_values provided. Generate a map first to re-paint it live.", + }), 400 + + font_name, extra_option, gsm = _parse_render_params(data) + + mode = str(data.get("mode") or "text") + map_type = str(data.get("map_type") or "default") + palette_theme = str(data.get("palette_theme") or "auto") + auto_style = bool(data.get("auto_style", False)) + + try: + buffer = auto_map( + prompt=str(data.get("topic") or ""), + mode=mode, + map_type=map_type, + size_mod=gsm, + optional_feature=extra_option, + model=str(data.get("model") or "gemini-2.5-flash"), + font_name=font_name, + show_result=False, + io_res=True, + api_key=None, + filling_txt_override=data.get("filling_txt"), + filling_num_override=data.get("filling_num"), + label_style=data.get("label_style"), + auto_style=auto_style, + palette_theme=palette_theme, + ai_answer_override=map_values, + ) + except Exception as e: # noqa: BLE001 + return jsonify({"status": "error", "error": str(e)}), 500 + + if buffer is None: + return jsonify({"status": "error", "error": "Map repainting failed."}), 500 + + encoded = base64.b64encode(buffer.getvalue()).decode("ascii") + render_meta = getattr(buffer, "map_meta", None) + analysis = _build_analysis_from_ai( + map_values, + mode=mode, + palette_theme=palette_theme, + topic=str(data.get("topic") or ""), + render_meta=render_meta if isinstance(render_meta, dict) else None, + ) + return jsonify({ + "status": "success", + "image_url": f"data:image/png;base64,{encoded}", + "map_values": map_values, + "analysis": analysis, + }) + + @app.route('/api/analyze_map/', methods=['POST']) @app.route('/api/analyze_map', methods=['POST']) def api_analyze_map(): - """Inspect AI map values (or topic sample) and auto-determine colors for numbers or words.""" + """Inspect uploaded map images, explicit map_values, or topic previews.""" data = request.get_json(silent=True) or {} mode = str(data.get('mode') or 'auto') topic = str(data.get('topic') or '').strip() + map_type = str(data.get('map_type') or 'default') + palette_theme = str(data.get('palette_theme') or 'auto') map_values = data.get('map_values') - if not isinstance(map_values, dict) or not map_values: - cached = LAST_GENERATED_MAP_STATE.get("ai_answer") - if isinstance(cached, dict) and cached: - map_values = cached + image_data = data.get('image_data') + + if image_data is not None and (not isinstance(map_values, dict) or not map_values): + try: + inspected_values, analysis = _inspect_uploaded_map_image( + image_data, + map_type=map_type, + palette_theme=palette_theme, + ) + except ValueError as err: + return jsonify({"status": "error", "error": str(err)}), 400 + return jsonify({ + "status": "success", + "source": "image_inspection", + "topic": topic, + "map_values": inspected_values, + "analysis": analysis, + }) if isinstance(map_values, dict) and map_values: - analysis = _build_analysis_from_ai(map_values, mode=mode) + analysis = _build_analysis_from_ai( + map_values, + mode=mode, + palette_theme=palette_theme, + topic=topic, + ) return jsonify({ "status": "success", "source": "ai_answer", @@ -333,7 +588,12 @@ def api_analyze_map(): "poland": 37, "romania": 19, "netherlands": 18, "sweden": 10, "estonia": 1, } - analysis = _build_analysis_from_ai(sample_values, mode=mode) + analysis = _build_analysis_from_ai( + sample_values, + mode=mode, + palette_theme=palette_theme, + topic=topic, + ) return jsonify({ "status": "success", "source": "topic_preview", diff --git a/map/auto_map.py b/map/auto_map.py index 34127e0..8e6ae0a 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -12,9 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +import ast import random import io import math +import re from collections import Counter from pathlib import Path @@ -25,8 +27,6 @@ from . import log -LAST_GENERATED_MAP_STATE: dict[str, object] = {} - _AUTO_PALETTE: tuple[tuple[int, int, int, int], ...] = ( (56, 189, 248, 255), # #38bdf8 Sky (99, 102, 241, 255), # #6366f1 Indigo @@ -40,6 +40,42 @@ (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), + ), +} + _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), @@ -47,6 +83,111 @@ "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)} +_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, +} + + +def _resolve_theme_name(palette_theme: str = "auto", prompt: str = "", mode: str = "text") -> str: + theme = (palette_theme or "auto").strip().lower() + if theme in _PALETTE_THEMES and theme != "auto": + return theme + low = (prompt or "").lower() + if any(w in low for w in ("nicholas", "christmas", "santa", "holiday", "xmas")): + return "festive" + if any(w in low for w in ("sea", "ocean", "water", "cold", "ice", "winter")): + return "ocean" + if any(w in low for w in ("hot", "heat", "sun", "fire", "summer")): + return "sunset" + if mode == "number": + return "viridis" + return "auto" + + +def _hex_to_rgba(val: object, default: tuple[int, int, int, int]) -> tuple[int, int, int, int]: + if not isinstance(val, str): + return default + clean = val.strip().lstrip("#") + if not re.fullmatch(r"[0-9a-fA-F]{6}", clean): + return default + return (int(clean[0:2], 16), int(clean[2:4], 16), int(clean[4:6], 16), 255) + + +def _to_rgba_tuple(val: object) -> tuple[int, int, int, int] | None: + if isinstance(val, (list, tuple)) and len(val) in (3, 4): + try: + r, g, b = int(val[0]), int(val[1]), int(val[2]) + a = int(val[3]) if len(val) == 4 else 255 + return (max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b)), max(0, min(255, a))) + except (ValueError, TypeError): + return None + if isinstance(val, str) and val.strip().startswith("#"): + return _hex_to_rgba(val, (99, 102, 241, 255)) + return None + + +def _parse_filling_overrides( + raw_txt: object, + raw_num: object, +) -> tuple[dict[str, tuple[int, int, int, int]], dict[tuple[int, int], tuple[int, int, int, int]]]: + txt_out: dict[str, tuple[int, int, int, int]] = {} + num_out: dict[tuple[int, int], tuple[int, int, int, int]] = {} + if isinstance(raw_txt, dict): + for k, v in raw_txt.items(): + key_str = str(k).strip() + rgba = _to_rgba_tuple(v) + if key_str and rgba is not None: + txt_out[key_str] = rgba + if isinstance(raw_num, dict): + for k, v in raw_num.items(): + rgba = _to_rgba_tuple(v) + if rgba is None: + continue + try: + bounds = k if isinstance(k, tuple) else ast.literal_eval(str(k)) + if isinstance(bounds, (list, tuple)) and len(bounds) == 2: + num_out[(int(float(bounds[0])), int(float(bounds[1])))] = rgba + except (ValueError, SyntaxError, TypeError): + continue + elif isinstance(raw_num, list): + for item in raw_num: + if not isinstance(item, dict): + continue + rgba = _to_rgba_tuple(item.get("color") or item.get("hex")) + if rgba is None: + continue + try: + num_out[(int(float(item["low"])), int(float(item["high"])))] = rgba + except (KeyError, ValueError, TypeError): + continue + return txt_out, num_out + def _parse_short_number(val: object) -> float | None: """Parse plain numbers or short-form numbers like '10k', '2.5M', '1B'.""" @@ -73,10 +214,15 @@ def _parse_short_number(val: object) -> float | None: def _auto_fill_from_ai( ai_answer: dict[str, object], mode: str, + palette_theme: str = "auto", + prompt: str = "", ) -> tuple[dict[str, tuple[int, int, int, int]], dict[tuple[int, int], tuple[int, int, int, int]]]: """Inspect AI response values (numbers, short-form numbers, or words) and pick colors.""" auto_txt: dict[str, tuple[int, int, int, int]] = {} auto_num: dict[tuple[int, int], tuple[int, int, int, int]] = {} + resolved = _resolve_theme_name(palette_theme, prompt=prompt, mode=mode) + palette = _PALETTE_THEMES.get(resolved, _AUTO_PALETTE) + use_semantic = (palette_theme or "auto").strip().lower() == "auto" if mode == "number": nums: list[int] = [] @@ -94,7 +240,7 @@ def _auto_fill_from_ai( bounds.append(max(bounds[-1] + 1, q)) bounds.append(max(bounds[-1] + 1, nums[-1])) for i in range(buckets): - auto_num[(bounds[i], bounds[i + 1])] = _AUTO_PALETTE[i % len(_AUTO_PALETTE)] + auto_num[(bounds[i], bounds[i + 1])] = palette[i % len(palette)] else: labels = [str(v).strip() for v in ai_answer.values() if v is not None and str(v).strip()] parsed_pairs = [(lbl, _parse_short_number(lbl)) for lbl in labels] @@ -111,9 +257,9 @@ def _auto_fill_from_ai( for lbl, num in parsed_pairs: if num is not None: b_idx = sum(1 for t in thresholds if num > t) - auto_txt[lbl] = _AUTO_PALETTE[b_idx % len(_AUTO_PALETTE)] + auto_txt[lbl] = palette[b_idx % len(palette)] else: - auto_txt.setdefault(lbl, _SEMANTIC_COLORS.get(lbl.lower(), _AUTO_PALETTE[5])) + auto_txt.setdefault(lbl, _SEMANTIC_COLORS.get(lbl.lower(), palette[-1])) else: canonical: dict[str, str] = {} for lbl in labels: @@ -121,10 +267,10 @@ 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 low_lbl in _SEMANTIC_COLORS: + if use_semantic and low_lbl in _SEMANTIC_COLORS: auto_txt[orig] = _SEMANTIC_COLORS[low_lbl] else: - auto_txt[orig] = _AUTO_PALETTE[idx % len(_AUTO_PALETTE)] + auto_txt[orig] = palette[idx % len(palette)] idx += 1 return auto_txt, auto_num @@ -150,7 +296,14 @@ def _numeric_extrema(values): 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): + show_result: bool = True, io_res = False, api_key: str | None = None, + *, + filling_txt_override: dict[str, object] | None = None, + filling_num_override: object | None = None, + label_style: dict[str, object] | None = None, + auto_style: bool | None = None, + palette_theme: str = "auto", + ai_answer_override: dict[str, object] | None = None): """Create a map from an AI query and save it as ``result.png``. CLI options: @@ -175,12 +328,30 @@ def get_font(size): _font_cache[key] = ImageFont.truetype(str(font_path), size) return _font_cache[key] - filling_txt, filling_num = load_filling() # Loading filling from JSON + req_txt, req_num = _parse_filling_overrides(filling_txt_override, filling_num_override) + has_txt_override = filling_txt_override is not None + has_num_override = filling_num_override is not None + if has_txt_override and has_num_override: + filling_txt, filling_num = dict(req_txt), dict(req_num) + else: + disk_txt, disk_num = load_filling() # Loading filling from JSON + filling_txt = dict(req_txt) if has_txt_override else disk_txt + filling_num = dict(req_num) if has_num_override else disk_num # Case-insensitive lookups for text mode. Keys from the JSON are trimmed and # lower-cased so that AI answers like "Yes", "yes" or " yes " all match. filling_txt_ci = {str(k).strip().lower(): v for k, v in filling_txt.items()} + ls = label_style if isinstance(label_style, dict) else {} + label_fill = _hex_to_rgba(ls.get("text_color"), (255, 255, 255, 255)) + label_stroke_fill = _hex_to_rgba(ls.get("stroke_color"), (0, 0, 0, 255)) + try: + raw_sw = ls.get("stroke_width", 15) + label_stroke_width = max(0, min(40, int(15 if raw_sw is None else raw_sw))) + except (ValueError, TypeError): + label_stroke_width = 15 + label_auto_fit = bool(ls.get("auto_fit", False)) if "auto_fit" in ls else False + # Most least and short form conflict solution # @TODO Make most/least and short form compatible @@ -196,7 +367,7 @@ def get_font(size): showwarning("Warning", "Most/Least feature is not available for world map. It will be disabled.") optional_feature = None - if optional_feature == "short_form": + if optional_feature == "short_form" and ai_answer_override is None: prompt += " Write in short form, for example 1000=1k, 1000000=1M etc." random_colors = {} @@ -232,9 +403,12 @@ def get_font(size): text_layer = Image.new("RGBA", img.size, (255, 255, 255, 0)) draw = ImageDraw.Draw(text_layer) - # Requesting information from AI - log.step("Requesting data from AI") - ai_answer = ai_request(prompt, map_type, model, api_key) + if ai_answer_override is not None: + ai_answer = dict(ai_answer_override) + else: + # Requesting information from AI + log.step("Requesting data from AI") + ai_answer = ai_request(prompt, map_type, model, api_key) if ai_answer is None: showerror("Error", "No information or bad info received from AI") @@ -242,20 +416,40 @@ def get_font(size): log.success(f"Got information from AI ({len(ai_answer)} entries)") - # Auto-pick colors based on the numbers or words returned by AI when filling.json has no rules - auto_txt, auto_num = _auto_fill_from_ai(ai_answer, mode) - if not filling_txt and auto_txt: - filling_txt = auto_txt - filling_txt_ci = {str(k).strip().lower(): v for k, v in filling_txt.items()} - if not filling_num and auto_num: - filling_num = auto_num - - LAST_GENERATED_MAP_STATE.clear() - LAST_GENERATED_MAP_STATE.update({ - "ai_answer": dict(ai_answer), - "filling_txt": {str(k): list(v) for k, v in (filling_txt or auto_txt).items()}, - "filling_num": {f"({lo}, {hi})": list(v) for (lo, hi), v in (filling_num or auto_num).items()}, - }) + resolved_theme = _resolve_theme_name(palette_theme, prompt=prompt, mode=mode) + auto_txt, auto_num = _auto_fill_from_ai( + ai_answer, + mode, + palette_theme=palette_theme, + prompt=prompt, + ) + theme_requested = (palette_theme or "auto").strip().lower() != "auto" + + if auto_style is True: + 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): + ci_to_orig = {k.strip().lower(): k for k in merged_txt} + for rk, rv in req_txt.items(): + target_k = ci_to_orig.get(rk.strip().lower(), rk) + merged_txt[target_k] = rv + 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: + filling_num = dict(req_num) + elif auto_num: + filling_num = dict(auto_num) + elif auto_style is False: + # Honor the request's explicit rules without overwriting them with auto_fill. + pass + else: + if not filling_txt and auto_txt: + filling_txt = auto_txt + filling_txt_ci = {str(k).strip().lower(): v for k, v in filling_txt.items()} + if not filling_num and auto_num: + filling_num = auto_num most_least = None extrema = _numeric_extrema(ai_answer) if optional_feature == "show_most_least" else None @@ -271,13 +465,15 @@ def get_font(size): ml_draw.text((106, 1240), f'Most: {most_country.capitalize()}\nLeast: {least_country.capitalize()}', - font=ImageFont.truetype(str(Path("resources/fonts") / font_name), 150), - fill=(255, 255, 255, 255), - stroke_width=15, - stroke_fill=(0, 0, 0, 255)) + font=get_font(150), + fill=label_fill, + stroke_width=label_stroke_width, + stroke_fill=label_stroke_fill) total = len(dict_) log.step(f"Painting {total} regions") + used_txt_rules: dict[str, tuple[int, int, int, int]] = {} + used_num_rules: dict[tuple[int, int], tuple[int, int, int, int]] = {} for index, (name, points) in enumerate(dict_.items(), start=1): '''Number mode''' @@ -294,10 +490,20 @@ def get_font(size): if num_value is not None: # Pick the colour of the first matching range. Ranges are # treated as (low < value <= high) per the docs. + matched_bounds = None for (low_lim, high_lim), color_tup in filling_num.items(): if low_lim < num_value <= high_lim: color = color_tup + matched_bounds = (low_lim, high_lim) break + if matched_bounds is None and auto_style is True and auto_num: + for (low_lim, high_lim), color_tup in auto_num.items(): + if low_lim < num_value <= high_lim: + color = color_tup + matched_bounds = (low_lim, high_lim) + break + if matched_bounds is not None: + used_num_rules[matched_bounds] = color except KeyError as e: info = "" log.warning(f"No data / color for {e}; using random color") @@ -325,6 +531,7 @@ def get_font(size): random_colors[info] = color else: color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + used_txt_rules.setdefault(info, color) else: showerror("Error", f"Unknown mode: {mode}") return @@ -355,70 +562,75 @@ def get_font(size): x -= 70 elif len(info) >= 2: x -= 30 - # number in countries - - if name in ['cyprus', 'kosovo', 'montenegro']: - size = 70 - elif name in ['ukraine', 'poland', 'france', 'spain', - 'turkey', 'romania', 'italy', 'belarus', 'united_kingdom', 'germany']: - size = 175 - elif name in ['sweden', 'norway', 'finland']: - size = 100 - elif name in ['russia', 'usa']: + + size = _EUROPE_LABEL_SIZES.get(name, 125) + if name in ('russia', 'usa'): y -= 10 - size = 250 - elif name in ['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']: - size = 70 - elif name in ['ireland', 'belgium', 'estonia', 'lithuania', 'north_macedonia', - 'switzerland', 'bosnia']: + elif name in ('north_macedonia', 'bosnia'): y -= 25 - size = 125 - else: - size = 125 if len(info) == 1: y -= 20 size += 25 - size += size_mod # Global size modifier for other fonts. Main font is BIPS + if label_auto_fit and len(info) >= 6: + size = max(45, int(size * max(0.55, 5.0 / len(info)))) + + size = max(20, size + size_mod) # Global size modifier for other fonts. Main font is BIPS font = get_font(size) # getting font from cache draw.text((x, y), info, font=font, - fill=(255, 255, 255, 255), - stroke_width=15, - stroke_fill=(0, 0, 0, 255)) + fill=label_fill, + stroke_width=label_stroke_width, + stroke_fill=label_stroke_fill) elif map_type == 'world': # text size for World map + size = _WORLD_LABEL_SIZES.get(name, 100) - if name == "asia": - size = 200 - elif name == "africa": - size = 100 - elif name == "europe": - size = 110 - elif name == "australia": - size = 50 - elif name == "south_America": - size = 100 - elif name == "north_America": - size = 120 - else: - size = 100 - - size += size_mod # Global size modifier for other fonts. Main font is BIPS + if label_auto_fit and len(info) >= 6: + size = max(40, int(size * max(0.55, 5.0 / len(info)))) + + size = max(20, size + size_mod) # Global size modifier for other fonts. Main font is BIPS draw.text((x, y), info, font=get_font(size), - fill=(255, 255, 255, 255), - stroke_width=15, - stroke_fill=(0, 0, 0, 255)) + fill=label_fill, + stroke_width=label_stroke_width, + stroke_fill=label_stroke_fill) + + effective_txt = dict(used_txt_rules) if used_txt_rules else dict(filling_txt or auto_txt) + seen_txt_lower = {str(uk).strip().lower() for uk in effective_txt} + for k, v in (filling_txt or {}).items(): + k_str = str(k) + k_low = k_str.strip().lower() + if k_low not in seen_txt_lower: + effective_txt[k_str] = v + seen_txt_lower.add(k_low) + effective_num = dict(filling_num or auto_num) + for bounds, c in used_num_rules.items(): + effective_num[bounds] = c + + render_meta = { + "ai_answer": dict(ai_answer), + "mode": mode, + "resolved_theme": resolved_theme, + "filling_txt": {str(k): list(v) for k, v in effective_txt.items()}, + "filling_num": {f"({lo}, {hi})": list(v) for (lo, hi), v in effective_num.items()}, + "used_txt": {str(k): list(v) for k, v in (used_txt_rules or effective_txt).items()}, + "used_num": {f"({lo}, {hi})": list(v) for (lo, hi), v in (used_num_rules or effective_num).items()}, + "label_style": { + "text_color": f"#{label_fill[0]:02x}{label_fill[1]:02x}{label_fill[2]:02x}", + "stroke_color": f"#{label_stroke_fill[0]:02x}{label_stroke_fill[1]:02x}{label_stroke_fill[2]:02x}", + "stroke_width": label_stroke_width, + "auto_fit": label_auto_fit, + "recommended_font": font_name or ("Bips.ttf" if mode == "number" else "DIN Condensed.ttf"), + "recommended_gsm": size_mod, + }, + } # adding relief map log.step("Compositing layers") @@ -428,9 +640,8 @@ def get_font(size): relief = relief.resize(img.size) # Reduce relief opacity to preserve the generated region colors beneath it. - r, g, b, a = relief.split() - new_alpha = a.point(lambda p: int(p * 0.3)) - relief.putalpha(new_alpha) + _, _, _, a = relief.split() + relief.putalpha(a.point(_RELIEF_ALPHA_LUT)) result = Image.alpha_composite(img, relief) @@ -462,6 +673,7 @@ def get_font(size): result.save(buffer, format='PNG') # Consumers should be able to read the PNG from its first byte. buffer.seek(0) + buffer.map_meta = render_meta return buffer diff --git a/map/functions.py b/map/functions.py index aacab10..47903cb 100644 --- a/map/functions.py +++ b/map/functions.py @@ -72,18 +72,19 @@ def ai_request(prompt: str, mode: str, ai_model: str, api_key: str | None = None try: # Models may wrap otherwise valid JSON in a Markdown code fence. - json_style = request.strip().replace("```json", "").replace("```", "").strip() + json_style = ( + request.strip() + .removeprefix("```json") + .removeprefix("```python") + .removeprefix("```") + .removesuffix("```") + .strip() + ) country_dict = json.loads(json_style) - except json.JSONDecodeError: - try: - json_style = request.strip().replace("```python", "").replace("```", "").strip() - country_dict = json.loads(json_style) - - except json.JSONDecodeError: - _error(f"Failed to convert into dictionary. Result {json_style}") - print("Result:", json_style) - return None + _error(f"Failed to convert into dictionary. Result {json_style}") + print("Result:", json_style) + return None except (AttributeError, TypeError) as e: _error("AI response parsing error", str(e)) return None diff --git a/map/log.py b/map/log.py index e9e6ceb..196994c 100644 --- a/map/log.py +++ b/map/log.py @@ -99,10 +99,7 @@ def spinner(message: str = "Working..."): and collapses into a success/failure line when the block finishes. """ with console.status(f"[bold cyan]{message}", spinner="dots") as status: - try: - # Keep the status active for the caller's block; errors propagate - # after the status context has had a chance to stop the animation. - yield status - except Exception: - raise + # Keep the status active for the caller's block; errors propagate + # after the status context has had a chance to stop the animation. + yield status diff --git a/resources/othr/white_pixels_cleaning.py b/resources/othr/white_pixels_cleaning.py index 98c672a..d268a5b 100644 --- a/resources/othr/white_pixels_cleaning.py +++ b/resources/othr/white_pixels_cleaning.py @@ -1,15 +1,12 @@ from PIL import Image -# Run from the asset directory: this utility overwrites map.png in place. -img = Image.open("map.png").convert("RGBA") - -pixels = img.load() -for x in range(img.width): - for y in range(img.height): - r, g, b, a = pixels[x, y] +_OPAQUE_ALPHA_LUT: list[int] = [255 if a == 255 else 0 for a in range(256)] - # Remove partially transparent edge pixels while preserving opaque artwork. - if a < 255: - pixels[x, y] = (r, g, b, 0) +# Run from the asset directory: this utility overwrites map.png in place. +with Image.open("map.png") as opened: + img = opened.convert("RGBA") +# Remove partially transparent edge pixels in C via LUT while preserving opaque artwork. +r, g, b, a = img.split() +img = Image.merge("RGBA", (r, g, b, a.point(_OPAQUE_ALPHA_LUT))) img.save("map.png") diff --git a/tests/test_auto_map.py b/tests/test_auto_map.py index aa7a07a..48ddd14 100644 --- a/tests/test_auto_map.py +++ b/tests/test_auto_map.py @@ -186,3 +186,39 @@ def test_auto_fill_from_ai_detects_numbers_and_words(): assert short_txt['1k'] != short_txt['20k'] +def test_auto_map_applies_request_color_and_label_overrides(scene, monkeypatch): + answer, _, real_open = scene + answer.return_value = {'one': 'CustomLabel', 'two': 'OtherLabel', 'three': ''} + draw_text = Mock(wraps=ImageDraw.ImageDraw.text) + monkeypatch.setattr(ImageDraw.ImageDraw, 'text', draw_text) + + buf = render( + filling_txt_override={'CustomLabel': [12, 34, 56, 255], 'OtherLabel': [65, 43, 21, 255]}, + label_style={'text_color': '#ff1122', 'stroke_color': '#010203', 'stroke_width': 9, 'auto_fit': True}, + auto_style=False, + palette_theme='emerald', + ) + image = real_open(buf) + assert image.getpixel((80, 600)) == (12, 34, 56, 255) + assert image.getpixel((290, 600)) == (65, 43, 21, 255) + assert draw_text.call_args.kwargs['fill'] == (255, 17, 34, 255) + assert draw_text.call_args.kwargs['stroke_fill'] == (1, 2, 3, 255) + assert draw_text.call_args.kwargs['stroke_width'] == 9 + assert buf.map_meta['label_style']['text_color'] == '#ff1122' + assert buf.map_meta['used_txt']['CustomLabel'] == [12, 34, 56, 255] + + +def test_auto_map_restyle_override_skips_ai_request(scene): + answer, _, real_open = scene + buf = render( + ai_answer_override={'one': 'Alpha', 'two': 'Beta', 'three': 'Alpha'}, + filling_txt_override={'Alpha': [10, 200, 100, 255], 'Beta': [200, 10, 100, 255]}, + auto_style=False, + ) + answer.assert_not_called() + image = real_open(buf) + assert image.getpixel((80, 600)) == (10, 200, 100, 255) + assert image.getpixel((290, 600)) == (200, 10, 100, 255) + + + diff --git a/tests/test_web.py b/tests/test_web.py index 53c9d05..486a0a8 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -220,3 +220,92 @@ def test_analyze_map_endpoint_returns_rules_and_style(web): assert len(data['analysis']['ui_txt_rules']) == 3 assert 'recommended_font' in data['analysis']['label_style'] + +def test_restyle_map_repaints_without_ai_request(web, monkeypatch): + client = web.app.test_client() + fake_buf = io.BytesIO(b'repainted-png') + fake_buf.map_meta = { + 'ai_answer': {'ukraine': 'Yes', 'poland': 'No'}, + 'resolved_theme': 'emerald', + 'used_txt': {'Yes': [16, 185, 129, 255], 'No': [239, 68, 68, 255]}, + 'label_style': { + 'text_color': '#ffeeaa', + 'stroke_color': '#112233', + 'stroke_width': 11, + 'auto_fit': True, + 'recommended_font': 'Bips.ttf', + 'recommended_gsm': 15, + }, + } + mock_auto_map = Mock(return_value=fake_buf) + monkeypatch.setattr(web, 'auto_map', mock_auto_map) + + res = client.post('/api/restyle_map', json={ + 'topic': 'Test', + 'mode': 'text', + 'map_type': 'default', + 'gsm': 15, + 'font': 'Bips.ttf', + 'auto_style': False, + 'palette_theme': 'emerald', + 'filling_txt': {'Yes': [16, 185, 129, 255], 'No': [239, 68, 68, 255]}, + 'label_style': {'text_color': '#ffeeaa', 'stroke_color': '#112233', 'stroke_width': 11, 'auto_fit': True}, + 'map_values': {'ukraine': 'Yes', 'poland': 'No'}, + }) + assert res.status_code == 200 + assert res.json['status'] == 'success' + assert base64.b64decode(res.json['image_url'].split(',')[1]) == b'repainted-png' + assert mock_auto_map.call_args.kwargs['ai_answer_override'] == {'ukraine': 'Yes', 'poland': 'No'} + assert mock_auto_map.call_args.kwargs['auto_style'] is False + assert res.json['analysis']['label_style']['text_color'] == '#ffeeaa' + assert res.json['analysis']['filling_txt']['Yes'] == [16, 185, 129, 255] + + +def test_restyle_map_requires_map_values(web): + client = web.app.test_client() + res = client.post('/api/restyle_map', json={'topic': 'Test', 'mode': 'text'}) + assert res.status_code == 400 + assert res.json['status'] == 'error' + + +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)) + buf = io.BytesIO() + img.save(buf, format='PNG') + b64 = base64.b64encode(buf.getvalue()).decode('ascii') + + ok_res = client.post('/api/analyze_map', json={ + 'image_data': f'data:image/png;base64,{b64}', + 'map_type': 'default', + 'prefer_cached': False, + }) + assert ok_res.status_code == 200 + assert ok_res.json['source'] == 'image_inspection' + assert '#14b45a' in ok_res.json['analysis']['filling_txt'] + + +def test_analyze_map_prefer_cached_false_does_not_leak_previous_state(web): + client = web.app.test_client() + res = client.post('/api/analyze_map', json={ + 'topic': 'When is Saint Nicholas Day', + 'mode': 'text', + 'prefer_cached': False, + }) + assert res.status_code == 200 + assert res.json['source'] == 'topic_preview' + assert res.json['map_values']['ukraine'] == '6 Dec' + + diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index d384fb0..7c6c890 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -31,6 +31,10 @@ # h264_nvenc - NVIDIA GPUs # h264_videotoolbox - Apple Silicon chips ALLOWED_CODECS = ("libx264", "h264_nvenc", "h264_videotoolbox") +_OG_TITLE_RE = re.compile(r'(.*?)') +_SAFE_TITLE_RE = re.compile(r'[^\w\-]') +_AUDIO_TITLE_RE = re.compile(r'[\w\-]+') @lru_cache(maxsize=1) @@ -79,12 +83,12 @@ def _get_song_title(url: str) -> str | None: response = requests.get(url, timeout=10) response.raise_for_status() - match = re.search(r'(.*?)', response.text) + match_title = _HTML_TITLE_RE.search(response.text) if match_title: return match_title.group(1) @@ -1342,10 +1346,10 @@ def _decode_optional_image(field: str, label: str): except ValueError as ve: return jsonify({"status": "error", "error": str(ve)}), 400 - safe_title = re.sub(r'[^\w\-]', '_', title) + safe_title = _SAFE_TITLE_RE.sub('_', title) # The video headline and the selected song are independent identifiers. audio_title = data.get('audio_title', '') - if not isinstance(audio_title, str) or (audio_title and not re.fullmatch(r'[\w\-]+', audio_title)): + if not isinstance(audio_title, str) or (audio_title and not _AUDIO_TITLE_RE.fullmatch(audio_title)): return jsonify(status='error', error='Invalid audio track title.'), 400 try: audio_bytes = _decode_material(str(data['audio_file']), 'audio_file') if data.get('audio_file') else None From 1b260109a1a8851baab504678f7773e9176fd471 Mon Sep 17 00:00:00 2001 From: bibed234 Date: Sat, 14 Nov 2026 16:49:53 +0200 Subject: [PATCH 3/4] Address P2 review findings: numeric UI defaults, all palette themes, palette-only image inspection, and bound text spy test --- main.py | 54 ++++++++++++++++++++++++++++-------------- map/auto_map.py | 34 ++++++++++++++++++++------ templates/index.html | 18 ++++++++++---- tests/test_auto_map.py | 38 +++++++++++++++++++++++++---- tests/test_web.py | 20 +++++++++++++++- 5 files changed, 129 insertions(+), 35 deletions(-) diff --git a/main.py b/main.py index b744d2f..9bd8347 100644 --- a/main.py +++ b/main.py @@ -260,8 +260,8 @@ def _inspect_uploaded_map_image( image_data: object, map_type: str = "default", palette_theme: str = "auto", -) -> tuple[dict[str, object], dict[str, object]]: - """Decode and inspect an uploaded map image's region fill colors.""" +) -> dict[str, object]: + """Decode an uploaded map image and extract its sampled region color palette.""" if not isinstance(image_data, str) or not image_data.strip(): raise ValueError("Empty image data.") raw_b64 = image_data.strip() @@ -298,14 +298,15 @@ def _inspect_uploaded_map_image( px = img.load() clusters: list[tuple[int, int, int, int]] = [] - region_values: dict[str, str] = {} rule_colors: dict[str, tuple[int, int, int, int]] = {} + sampled_regions = 0 scale_x = width / max(1, ref_w) scale_y = height / max(1, ref_h) - for name, points in ref_coords.items(): + for points in ref_coords.values(): if not points: continue + sampled_regions += 1 px_x, px_y = points[0] sx = max(0, min(width - 1, int(round(px_x * scale_x)))) sy = max(0, min(height - 1, int(round(px_y * scale_y)))) @@ -338,20 +339,37 @@ def _inspect_uploaded_map_image( matched = avg hex_label = f"#{matched[0]:02x}{matched[1]:02x}{matched[2]:02x}" - region_values[name] = hex_label rule_colors.setdefault(hex_label, matched) - meta = { - "resolved_theme": palette_theme if palette_theme and palette_theme != "auto" else "inspected", - "used_txt": {k: list(v) for k, v in rule_colors.items()}, + ui_txt_rules = [ + {"key": k, "hex": k, "alpha": c[3]} + for k, c in rule_colors.items() + ] + return { + "detected_type": "palette", + "resolved_mode": "palette", + "resolved_theme": palette_theme if palette_theme and palette_theme != "auto" else "sampled", + "inspection_only": True, + "filling_txt": {k: list(c) for k, c in rule_colors.items()}, + "filling_num": {}, + "ui_txt_rules": ui_txt_rules, + "ui_num_rules": [], + "label_style": { + "text_color": "#ffffff", + "stroke_color": "#090d16", + "stroke_width": 15, + "auto_fit": True, + "recommended_font": "Bips.ttf", + "recommended_gsm": 15, + }, + "stats": { + "total_regions": sampled_regions, + "unique_values": len(rule_colors), + "min_value": None, + "max_value": None, + "sample_values": [], + }, } - analysis = _build_analysis_from_ai( - region_values, - mode="text", - palette_theme=palette_theme, - render_meta=meta, - ) - return region_values, analysis def _parse_render_params(data: dict[str, object]) -> tuple[str, str | None, int]: @@ -541,7 +559,7 @@ def api_analyze_map(): if image_data is not None and (not isinstance(map_values, dict) or not map_values): try: - inspected_values, analysis = _inspect_uploaded_map_image( + analysis = _inspect_uploaded_map_image( image_data, map_type=map_type, palette_theme=palette_theme, @@ -550,9 +568,9 @@ def api_analyze_map(): return jsonify({"status": "error", "error": str(err)}), 400 return jsonify({ "status": "success", - "source": "image_inspection", + "source": "palette_inspection", "topic": topic, - "map_values": inspected_values, + "map_values": None, "analysis": analysis, }) diff --git a/map/auto_map.py b/map/auto_map.py index 8e6ae0a..dc10895 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -74,6 +74,21 @@ (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), + ), } _SEMANTIC_COLORS: dict[str, tuple[int, int, int, int]] = { @@ -84,7 +99,7 @@ } _DEFAULT_UI_TXT_KEYS = {"yes", "no", "tea", "coffee"} -_DEFAULT_UI_NUM_BOUNDS = {(0, 100), (100, 1000)} +_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] = { @@ -232,13 +247,18 @@ def _auto_fill_from_ai( nums.append(int(round(parsed))) if nums: nums.sort() + unique_nums = sorted(set(nums)) low_start = min(0, nums[0] - 1) if nums[0] <= 10 else nums[0] - 1 - buckets = min(5, max(1, len(set(nums)))) - bounds = [low_start] - for i in range(1, buckets): - q = nums[int(round((len(nums) - 1) * (i / buckets)))] - bounds.append(max(bounds[-1] + 1, q)) - bounds.append(max(bounds[-1] + 1, nums[-1])) + if len(unique_nums) <= 5: + bounds = [low_start] + unique_nums + buckets = len(unique_nums) + else: + buckets = 5 + bounds = [low_start] + for i in range(1, buckets): + q = nums[int(round((len(nums) - 1) * (i / buckets)))] + bounds.append(max(bounds[-1] + 1, q)) + bounds.append(max(bounds[-1] + 1, nums[-1])) for i in range(buckets): auto_num[(bounds[i], bounds[i + 1])] = palette[i % len(palette)] else: diff --git a/templates/index.html b/templates/index.html index 29e9b3e..10d1a2a 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1650,7 +1650,9 @@

function applyAnalysisToFillingStudio(analysis, mapValues = null, notifyToast = true) { if (!analysis) return; lastMapAnalysis = analysis; - if (mapValues && typeof mapValues === 'object') { + if (analysis.inspection_only || !mapValues || typeof mapValues !== 'object') { + lastMapValues = null; + } else { lastMapValues = mapValues; } if (Array.isArray(analysis.ui_txt_rules) && analysis.ui_txt_rules.length > 0) { @@ -1693,7 +1695,11 @@

renderFillingStudio(); if (notifyToast) { - showToast(`Detected ${analysis.detected_type} map values -> applied ${analysis.resolved_theme} palette & style!`, 'success'); + if (analysis.inspection_only) { + showToast(`Extracted ${analysis.ui_txt_rules?.length || 0} palette colors from uploaded map (palette-only inspection).`, 'success'); + } else { + showToast(`Detected ${analysis.detected_type} map values -> applied ${analysis.resolved_theme} palette & style!`, 'success'); + } } } @@ -1753,7 +1759,7 @@

} if (emptyEl) emptyEl.classList.add('hidden'); - showToast(`Inspecting "${file.name}" for numbers, words & colors...`, 'info'); + showToast(`Extracting color palette from "${file.name}"...`, 'info'); const state = getFormState(); try { const res = await fetch('/api/analyze_map', { @@ -1775,7 +1781,7 @@

throw new Error(data.error || 'Map image inspection failed'); } applyAnalysisToFillingStudio(data.analysis, data.map_values, true); - logToConsole(`[Map Inspector] Analyzed uploaded map "${file.name}" -> detected ${data.analysis?.detected_type} values & "${data.analysis?.resolved_theme}" theme`, 'success'); + logToConsole(`[Map Inspector] Extracted ${data.analysis?.ui_txt_rules?.length || 0} palette colors from "${file.name}" (palette-only)`, 'success'); } catch (err) { showToast(err.message || 'Could not inspect map image', 'error'); } finally { @@ -1786,6 +1792,10 @@

} async function restyleCurrentMapFromStudio() { + if (!lastMapValues || lastMapAnalysis?.inspection_only) { + showToast('Generate a map first to re-paint it live (uploaded images only extract palette colors).', 'warn'); + return; + } const state = getFormState(); const btn = document.getElementById('restyleCurrentMapBtn'); if (btn) btn.disabled = true; diff --git a/tests/test_auto_map.py b/tests/test_auto_map.py index 48ddd14..38e07ab 100644 --- a/tests/test_auto_map.py +++ b/tests/test_auto_map.py @@ -189,8 +189,14 @@ def test_auto_fill_from_ai_detects_numbers_and_words(): def test_auto_map_applies_request_color_and_label_overrides(scene, monkeypatch): answer, _, real_open = scene answer.return_value = {'one': 'CustomLabel', 'two': 'OtherLabel', 'three': ''} - draw_text = Mock(wraps=ImageDraw.ImageDraw.text) - monkeypatch.setattr(ImageDraw.ImageDraw, 'text', draw_text) + orig_text = ImageDraw.ImageDraw.text + text_calls = [] + + def spy_text(self, *args, **kwargs): + text_calls.append((args, kwargs)) + return orig_text(self, *args, **kwargs) + + monkeypatch.setattr(ImageDraw.ImageDraw, 'text', spy_text) buf = render( filling_txt_override={'CustomLabel': [12, 34, 56, 255], 'OtherLabel': [65, 43, 21, 255]}, @@ -201,13 +207,35 @@ def test_auto_map_applies_request_color_and_label_overrides(scene, monkeypatch): image = real_open(buf) assert image.getpixel((80, 600)) == (12, 34, 56, 255) assert image.getpixel((290, 600)) == (65, 43, 21, 255) - assert draw_text.call_args.kwargs['fill'] == (255, 17, 34, 255) - assert draw_text.call_args.kwargs['stroke_fill'] == (1, 2, 3, 255) - assert draw_text.call_args.kwargs['stroke_width'] == 9 + assert len(text_calls) == 2 + assert text_calls[0][1]['fill'] == (255, 17, 34, 255) + assert text_calls[0][1]['stroke_fill'] == (1, 2, 3, 255) + assert text_calls[0][1]['stroke_width'] == 9 assert buf.map_meta['label_style']['text_color'] == '#ff1122' assert buf.map_meta['used_txt']['CustomLabel'] == [12, 34, 56, 255] +def test_numeric_auto_style_ignores_untouched_four_ui_defaults(scene): + answer, _, real_open = scene + answer.return_value = {'one': 1, 'two': 50, 'three': 99} + untouched_ui_num = { + '(0, 100)': [56, 189, 248, 255], + '(100, 1000)': [99, 102, 241, 255], + '(1000, 10000)': [168, 85, 247, 255], + '(10000, 100000000)': [244, 63, 94, 255], + } + buf = render( + mode='number', + filling_num_override=untouched_ui_num, + auto_style=True, + palette_theme='auto', + ) + image = real_open(buf) + assert len(buf.map_meta['used_num']) == 3 + assert image.getpixel((80, 600)) != image.getpixel((290, 600)) + assert image.getpixel((290, 600)) != image.getpixel((500, 600)) + + def test_auto_map_restyle_override_skips_ai_request(scene): answer, _, real_open = scene buf = render( diff --git a/tests/test_web.py b/tests/test_web.py index 486a0a8..40e7abd 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -293,10 +293,28 @@ def test_analyze_map_validates_and_inspects_uploaded_image(web): 'prefer_cached': False, }) assert ok_res.status_code == 200 - assert ok_res.json['source'] == 'image_inspection' + assert ok_res.json['source'] == 'palette_inspection' + assert ok_res.json['map_values'] is None + assert ok_res.json['analysis']['detected_type'] == 'palette' + assert ok_res.json['analysis']['inspection_only'] is True + assert ok_res.json['analysis']['stats']['sample_values'] == [] assert '#14b45a' in ok_res.json['analysis']['filling_txt'] +@pytest.mark.parametrize('theme', ['auto', 'viridis', 'heatmap', 'emerald_gold', 'festive', 'oceanic', 'categorical']) +def test_analyze_map_supports_every_ui_palette_theme(web, theme): + 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 + + def test_analyze_map_prefer_cached_false_does_not_leak_previous_state(web): client = web.app.test_client() res = client.post('/api/analyze_map', json={ From b54b612af0a1fdd6447e617dc7a5831b87700101 Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Sat, 14 Nov 2026 17:02:54 +0200 Subject: [PATCH 4/4] test: cover map styling and analysis request paths --- tests/test_auto_map.py | 51 ++++++++++++++++++++ tests/test_map_styling.py | 99 +++++++++++++++++++++++++++++++++++++++ tests/test_web.py | 67 ++++++++++++++++++++++++++ 3 files changed, 217 insertions(+) create mode 100644 tests/test_map_styling.py diff --git a/tests/test_auto_map.py b/tests/test_auto_map.py index 38e07ab..37d811f 100644 --- a/tests/test_auto_map.py +++ b/tests/test_auto_map.py @@ -249,4 +249,55 @@ def test_auto_map_restyle_override_skips_ai_request(scene): assert image.getpixel((290, 600)) == (200, 10, 100, 255) +@pytest.mark.parametrize('theme', ['auto', 'oceanic']) +def test_auto_style_preserves_explicit_text_rule_case_insensitively(scene, theme): + scene[0].return_value = {'one': 'Yes', 'two': 'Other', 'three': 'yes'} + output = render(auto_style=True, palette_theme=theme, + filling_txt_override={' YES ': '#123456'}) + image = scene[2](output) + assert image.getpixel((80, 600)) == (18, 52, 86, 255) + assert image.getpixel((500, 600)) == (18, 52, 86, 255) + assert image.getpixel((290, 600)) != (18, 52, 86, 255) + + +def test_explicit_theme_replaces_untouched_default_text_rules(scene): + scene[0].return_value = {'one': 'Yes', 'two': 'No', 'three': 'Tea'} + defaults = {'yes': '#2ecc71', 'no': '#e74c3c', 'tea': '#10b981', 'coffee': '#f59e0b'} + output = render(auto_style=True, palette_theme='oceanic', filling_txt_override=defaults) + image = scene[2](output) + assert image.getpixel((80, 600)) == (56, 189, 248, 255) + assert image.getpixel((290, 600)) == (14, 165, 233, 255) + + +def test_numeric_auto_style_keeps_manual_range_and_fills_unmatched_values(scene): + scene[0].return_value = {'one': 1, 'two': 50, 'three': 99} + output = render(mode='number', auto_style=True, + filling_num_override={'(0, 10)': '#123456'}) + image = scene[2](output) + assert image.getpixel((80, 600)) == (18, 52, 86, 255) + assert image.getpixel((290, 600)) != (160, 160, 160, 255) + assert image.getpixel((500, 600)) != (160, 160, 160, 255) + assert len(output.map_meta['used_num']) == 3 + + +@pytest.mark.parametrize('stroke,expected', [('bad', 15), (None, 15), (-1, 0), (100, 40)]) +def test_label_stroke_validation_keeps_rendering_usable(scene, stroke, expected): + output = render(label_style={'stroke_width': stroke}) + assert scene[2](output).format == 'PNG' + assert output.map_meta['label_style']['stroke_width'] == expected + + +@pytest.mark.parametrize('map_type', ['default', 'world']) +def test_long_labels_auto_fit_without_changing_their_text(scene, monkeypatch, map_type): + label = 'A very long region label' + scene[0].return_value = {'one': label} + text = Mock() + monkeypatch.setattr(ImageDraw.ImageDraw, 'text', text) + render(map_type=map_type, label_style={'auto_fit': False}) + original_size = text.call_args.kwargs['font'].size + render(map_type=map_type, label_style={'auto_fit': True}) + assert text.call_args.args[1] == label + assert text.call_args.kwargs['font'].size < original_size + + diff --git a/tests/test_map_styling.py b/tests/test_map_styling.py new file mode 100644 index 0000000..228b783 --- /dev/null +++ b/tests/test_map_styling.py @@ -0,0 +1,99 @@ +"""Color configuration and AI-value analysis without external services.""" +import importlib + +import pytest + + +renderer = importlib.import_module('map.auto_map') + + +@pytest.mark.parametrize('value,expected', [ + (' 2.5M ', 2_500_000), ('1B', 1_000_000_000), ('-1.5k', -1500), + ('1,234', 1234), ('1 234', 1234), (0, 0), + ('', None), ('NaN', None), ('inf', None), ('unknown', None), + (True, None), (None, None), +]) +def test_short_number_parsing_accepts_measurements_not_missing_or_nonfinite_values(value, expected): + assert renderer._parse_short_number(value) == expected + + +@pytest.mark.parametrize('topic,mode,expected', [ + ('Christmas holidays', 'text', 'festive'), + ('Winter temperatures', 'number', 'ocean'), + ('Summer temperatures', 'number', 'sunset'), + ('Population', 'number', 'viridis'), + ('Favorite drink', 'text', 'auto'), +]) +def test_automatic_theme_follows_topic_and_data_type(topic, mode, expected): + assert renderer._resolve_theme_name('auto', topic, mode) == expected + + +def test_explicit_theme_takes_precedence_over_topic(): + assert renderer._resolve_theme_name(' OCEANIC ', 'Christmas', 'number') == 'oceanic' + + +def test_color_overrides_accept_hex_rgb_and_rgba_and_ignore_invalid_rules(): + txt, num = renderer._parse_filling_overrides({ + ' Yes ': '#12Ab34', 'No': [300, -5, 25, 500], 'RGB': [1, 2, 3], + '': [1, 2, 3], 'bad': ['not-a-channel', 2, 3], 'missing': None, + }, { + '(0, 10)': '#112233', (10, 20): [4, 5, 6, 128], + 'invalid': [1, 2, 3], '(20,)': [1, 2, 3], '(20, 30)': None, + }) + assert txt == {'Yes': (18, 171, 52, 255), 'No': (255, 0, 25, 255), + 'RGB': (1, 2, 3, 255)} + assert num == {(0, 10): (17, 34, 51, 255), (10, 20): (4, 5, 6, 128)} + + +def test_numeric_rule_list_accepts_supported_colors_and_skips_incomplete_entries(): + _, rules = renderer._parse_filling_overrides(None, [ + {'low': '0', 'high': '10', 'hex': '#112233'}, + {'low': 10, 'high': 20, 'color': [4, 5, 6, 128]}, + None, {'low': 20, 'high': 30, 'color': None}, + {'low': 20, 'hex': '#112233'}, + {'low': 'bad', 'high': 30, 'hex': '#112233'}, + ]) + assert rules == {(0, 10): (17, 34, 51, 255), (10, 20): (4, 5, 6, 128)} + + +@pytest.mark.parametrize('value', [None, 'not-a-color', '#xyz']) +def test_invalid_label_color_uses_safe_default(value): + fallback = (255, 255, 255, 255) + assert renderer._hex_to_rgba(value, fallback) == fallback + + +def test_numeric_palette_covers_every_value_when_more_than_five_values_exist(): + values = {'region' + str(i): i for i in range(-3, 12)} + txt, rules = renderer._auto_fill_from_ai(values, 'number', palette_theme='heatmap') + assert not txt + assert len(rules) == 5 + for value in values.values(): + matches = [color for (lo, hi), color in rules.items() if lo < value <= hi] + assert len(matches) == 1 + assert len(set(rules.values())) == 5 + + +def test_short_form_text_palette_keeps_unknown_labels_as_separate_categories(): + rules, _ = renderer._auto_fill_from_ai( + {'a': '1k', 'b': '2k', 'c': '3k', 'd': 'unknown'}, 'text') + assert set(rules) == {'1k', '2k', '3k', 'unknown'} + assert rules['1k'] != rules['3k'] + assert rules['unknown'] not in (rules['1k'], rules['3k']) + + +def test_analysis_preserves_actual_render_rules_and_skips_malformed_metadata(web): + analysis = web._build_analysis_from_ai({'a': '2.5M', 'b': 10}, mode='number', render_meta={ + 'resolved_theme': 'heatmap', + 'used_txt': {'Yes': '#112233', 'invalid': None}, + 'used_num': {'(0, 10)': [1, 2, 3, 128], (10, 3_000_000): '#445566', + 'broken': [1, 2, 3], '(1,)': [1, 2, 3], '(4, 5)': None}, + 'label_style': {'text_color': '#abcdef', 'stroke_width': 9}, + }) + assert analysis['resolved_theme'] == 'heatmap' + assert analysis['filling_txt'] == {'Yes': [17, 34, 51, 255]} + assert analysis['filling_num'] == { + '(0, 10)': [1, 2, 3, 128], '(10, 3000000)': [68, 85, 102, 255]} + assert analysis['label_style']['text_color'] == '#abcdef' + assert analysis['label_style']['stroke_width'] == 9 + assert analysis['stats']['min_value'] == 10 + assert analysis['stats']['max_value'] == 2_500_000 diff --git a/tests/test_web.py b/tests/test_web.py index 40e7abd..023687e 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -327,3 +327,70 @@ def test_analyze_map_prefer_cached_false_does_not_leak_previous_state(web): assert res.json['map_values']['ukraine'] == '6 Dec' +def test_generate_returns_request_values_and_effective_style(web, monkeypatch, generation_request): + output = io.BytesIO(b'png') + output.map_meta = { + 'ai_answer': {'ukraine': 38}, 'resolved_theme': 'oceanic', + 'used_num': {'(0, 100)': [56, 189, 248, 255]}, + 'label_style': {'text_color': '#abcdef'}, + } + generate = Mock(return_value=output) + monkeypatch.setattr(web, 'auto_map', generate) + style = {'filling_txt': {}, 'filling_num': {'(0, 100)': '#38bdf8'}, + 'label_style': {'text_color': '#abcdef'}, 'auto_style': False, + 'palette_theme': 'oceanic'} + response = web.app.test_client().post('/api/generate', json={**generation_request, **style}) + assert response.status_code == 200 + assert response.json['map_values'] == {'ukraine': 38} + assert response.json['analysis']['ui_num_rules'] == [ + {'low': 0, 'high': 100, 'hex': '#38bdf8', 'alpha': 255}] + assert response.json['analysis']['label_style']['text_color'] == '#abcdef' + kwargs = generate.call_args.kwargs + assert kwargs['filling_txt_override'] == {} + assert kwargs['filling_num_override'] == style['filling_num'] + for key in ('auto_style', 'palette_theme', 'label_style'): + 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_palette_inspection_rejects_images_too_small_for_sampling(web): + from PIL import Image + output = io.BytesIO() + Image.new('RGB', (7, 7)).save(output, format='PNG') + response = web.app.test_client().post('/api/analyze_map', json={ + 'image_data': base64.b64encode(output.getvalue()).decode('ascii')}) + assert response.status_code == 400 + 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'] + +