From b7f022623a0477619d7cafab22a293eae5898b8e Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Wed, 18 Nov 2026 15:43:06 +0200 Subject: [PATCH 1/4] Capitalize text labels on countries and legend --- map/auto_map.py | 10 ++++++++-- tests/test_auto_map.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/map/auto_map.py b/map/auto_map.py index de2edf9..e031e15 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -537,6 +537,12 @@ def _numeric_extrema(values): return max(numeric, key=numeric.get), min(numeric, key=numeric.get) +def _format_text_label(value: object) -> str: + """Uppercase the first character while preserving acronyms and other casing.""" + label = "" if value is None else str(value).strip() + return label[:1].upper() + label[1:] + + def _format_legend_bound(val: float) -> str: """Format a numeric legend bound compactly so ranges fit in open sea space.""" abs_val = abs(val) @@ -1109,7 +1115,7 @@ def _report(stage: int, label: str) -> None: elif mode == 'text': '''Text mode''' raw_info = ai_answer_norm.get(name_key) - info = "" if raw_info is None else str(raw_info).strip() + info = _format_text_label(raw_info) if not info: log.info(f"No information for {name}, skipping") continue @@ -1302,7 +1308,7 @@ def _report(stage: int, label: str) -> None: else: legend_src = used_txt_rules or effective_txt legend_entries = [ - (tuple(c), str(label).strip()) + (tuple(c), _format_text_label(label)) for label, c in legend_src.items() if str(label).strip() ] diff --git a/tests/test_auto_map.py b/tests/test_auto_map.py index a4506dc..1cde523 100644 --- a/tests/test_auto_map.py +++ b/tests/test_auto_map.py @@ -104,6 +104,21 @@ def test_label_offset_for_short_and_long_text(scene, monkeypatch, map_type, labe assert draw_text.call_args.args[1] == label +@pytest.mark.parametrize('label,expected', [ + (' dog ', 'Dog'), ('dog breed', 'Dog breed'), + ('iPhone', 'IPhone'), ('USA', 'USA'), ('кіт', 'Кіт'), +]) +def test_text_labels_start_uppercase_on_countries_and_legend(scene, monkeypatch, label, expected): + scene[0].return_value = {'one': label} + draw_text = Mock() + legend = Mock(return_value=None) + monkeypatch.setattr(ImageDraw.ImageDraw, 'text', draw_text) + monkeypatch.setattr(renderer, '_draw_legend_overlay', legend) + render(show_legend=True) + assert draw_text.call_args.args[1] == expected + assert [entry[1] for entry in legend.call_args.args[1]] == [expected] + + def test_unknown_text_reuses_color(scene): answer, random, real_open = scene answer.return_value = {'one': 'unknown', 'two': 'unknown'} From 7fe1d3ea8df5eccce99a5fc60e2af1daf3083a15 Mon Sep 17 00:00:00 2001 From: bibed234 Date: Thu, 19 Nov 2026 13:51:18 +0200 Subject: [PATCH 2/4] Fix video rendering and improve map idea generation --- automap_rs/src/lib.rs | 53 ++++++++++---- main.py | 4 ++ map/functions.py | 130 ++++++++++++++++++++++++---------- render_progress.py | 13 +++- templates/index.html | 28 ++++++++ templates/video.html | 1 + tests/test_render_progress.py | 22 ++++++ tests/test_video_render.py | 2 +- video_render.py | 4 +- yt-dlp_serv.py | 7 +- 10 files changed, 204 insertions(+), 60 deletions(-) diff --git a/automap_rs/src/lib.rs b/automap_rs/src/lib.rs index 59b7e69..e219bfc 100644 --- a/automap_rs/src/lib.rs +++ b/automap_rs/src/lib.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use pyo3::exceptions::PyValueError; +use pyo3::exceptions::{PyRuntimeError, PyValueError}; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyTuple}; use std::io::{Read, Write}; @@ -189,12 +189,19 @@ fn render_video_rs( } enc_args.extend(["-pix_fmt".into(), "yuv420p".into(), output_path.into()]); - let mut encoder = Command::new(&ffmpeg_bin) + let mut encoder = match Command::new(&ffmpeg_bin) .args(&enc_args) .stdin(Stdio::piped()) .stderr(Stdio::null()) .spawn() - .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("ffmpeg encoder spawn failed: {e}")))?; + { + Ok(child) => child, + Err(error) => { + let _ = decoder.kill(); + let _ = decoder.wait(); + return Err(PyRuntimeError::new_err(format!("ffmpeg encoder spawn failed: {error}"))); + } + }; let mut enc_in = encoder .stdin @@ -213,12 +220,22 @@ fn render_video_rs( let mut ca_row_buf = if impact_fx_enabled { vec![0u8; width * 4] } else { Vec::new() }; let mut x_resample_lut = if need_zoom_buf { Vec::with_capacity(width) } else { Vec::new() }; + let mut frame_read_error = None; + let mut frame_write_error = None; + let mut decoder_finished = false; for frame_idx in 0..total_frames { - if dec_out.read_exact(&mut bg_buf).is_err() { - if frame_idx == 0 { - break; + if !decoder_finished { + // Keep a complete previous frame when the decoder ends early. + match dec_out.read_exact(&mut frame_buf) { + Ok(()) => std::mem::swap(&mut bg_buf, &mut frame_buf), + Err(error) if frame_idx > 0 && error.kind() == std::io::ErrorKind::UnexpectedEof => { + decoder_finished = true; + } + Err(error) => { + frame_read_error = Some(error); + break; + } } - // Hold the last decoded background frame if the source ended slightly early. } frame_buf.copy_from_slice(&bg_buf); @@ -350,17 +367,25 @@ fn render_video_rs( }; // Stream the composited frame into ffmpeg's stdin. - enc_in - .write_all(out_buf) - .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("encoder write failed: {e}")))?; + if let Err(error) = enc_in.write_all(out_buf) { + frame_write_error = Some(error); + break; + } } - // Close stdin so ffmpeg flushes and finalizes the MP4 container. + // Close the decoder pipe before waiting. FFmpeg may still be writing frames + // past the requested count and would block on a full pipe. drop(enc_in); - let status = encoder - .wait() - .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("encoder wait failed: {e}")))?; + drop(dec_out); let _ = decoder.wait(); + let status = encoder.wait(); + if let Some(error) = frame_read_error { + return Err(PyRuntimeError::new_err(format!("decoder read failed: {error}"))); + } + if let Some(error) = frame_write_error { + return Err(PyRuntimeError::new_err(format!("encoder write failed: {error}"))); + } + let status = status.map_err(|e| PyRuntimeError::new_err(format!("encoder wait failed: {e}")))?; if !status.success() { return Err(pyo3::exceptions::PyRuntimeError::new_err(format!( diff --git a/main.py b/main.py index 58e253a..67d7f9b 100644 --- a/main.py +++ b/main.py @@ -754,6 +754,9 @@ def api_generate_idea(): except ValueError as err: return jsonify(status='error', error=str(err)), 400 + raw_avoid = data.get("avoid_ideas") + avoid_ideas = [str(item).strip() for item in raw_avoid if str(item).strip()][:30] if isinstance(raw_avoid, list) else [] + try: result = generate_map_idea( model, @@ -762,6 +765,7 @@ def api_generate_idea(): available_themes=list(_PALETTE_THEMES.keys()), available_fonts=_available_fonts(), temperature=temperature, + avoid_ideas=avoid_ideas, ) except AIServiceError as error: return jsonify(status='error', error=str(error)), error.status_code diff --git a/map/functions.py b/map/functions.py index a09dbc0..e88e8b4 100644 --- a/map/functions.py +++ b/map/functions.py @@ -17,6 +17,7 @@ import json import math import os +import random import re import sys import requests @@ -486,6 +487,26 @@ def _call_model_text( return text.strip() +IDEA_CATEGORIES = ( + "food, drinks, and dining habits", + "driving, traffic, and public transport", + "work, salaries, holidays, and retirement", + "language, slang, names, and alphabets", + "housing, everyday prices, and cost of living", + "climate, weather, nature, and wildlife", + "school, education, and university life", + "sports, hobbies, and pop culture", + "internet, technology, and gaming", + "health, sleep, and daily routines", + "unusual laws, rules, and traditions", + "cities, borders, and surprising geography", +) + + +def _normalize_idea_key(text: str) -> str: + return re.sub(r"[^a-z0-9]+", " ", str(text or "").lower()).strip() + + def generate_map_idea( ai_model: str, api_key: str | None = None, @@ -494,25 +515,49 @@ def generate_map_idea( available_themes: list[str] | tuple[str, ...] | None = None, available_fonts: list[str] | tuple[str, ...] | None = None, temperature: float | None = None, + avoid_ideas: list[str] | tuple[str, ...] | None = None, ) -> dict[str, object]: """Generate a single map idea (and optionally matching map parameters) via the selected AI model.""" - examples_block = "\n".join(f'- "{ex}"' for ex in IDEA_EXAMPLES) + sampled_examples = random.sample(IDEA_EXAMPLES, min(6, len(IDEA_EXAMPLES))) + examples_block = "\n".join(f'- "{ex}"' for ex in sampled_examples) + cleaned_avoid = [str(item).strip() for item in (avoid_ideas or ()) if str(item).strip()][:30] + avoid_keys = {_normalize_idea_key(item) for item in cleaned_avoid} + avoid_block = "" + if cleaned_avoid: + avoid_lines = "\n".join(f'- "{item}"' for item in cleaned_avoid[-20:]) + avoid_block = ( + "\n\nIMPORTANT — Do NOT repeat or closely rephrase any of these already-used ideas:\n" + f"{avoid_lines}" + ) + idea_temp = 1.0 if temperature is None else validate_temperature(temperature) if not with_params: system_msg = ( "You generate short, engaging, curiosity-sparking map topic questions in English. " + "Always pick a fresh, surprising angle and never repeat recent topics. " "Return ONLY the idea itself as a single plain-text sentence/question, with no quotes, " "no numbering, no markdown, and no explanation." ) - user_prompt = ( - "Generate 1 new creative map topic idea in the exact same style and format as these examples:\n" - f"{examples_block}\n\n" - "Return only the idea text." - ) - raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=temperature, json_mode=False) - idea = raw.strip().splitlines()[0].strip().strip('"\'` ') - if not idea: - raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + idea = "" + for attempt in range(2): + focus_category = random.choice(IDEA_CATEGORIES) + nonce = random.randint(1000, 9999) + retry_note = "\nPrevious candidate was a duplicate — choose a completely different subject." if attempt else "" + user_prompt = ( + f"Generate 1 fresh, creative map topic idea focused on: {focus_category} (variation #{nonce}).\n" + "Match the concise style of these examples without copying them:\n" + f"{examples_block}" + f"{avoid_block}" + f"{retry_note}\n\n" + "Return only the idea text." + ) + raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=idea_temp, json_mode=False) + candidate = next(iter(raw.strip().splitlines()), '').strip().strip('"\'` ') + if not candidate: + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + idea = candidate + if _normalize_idea_key(candidate) not in avoid_keys: + break return {"idea": idea} raw_themes = [str(t) for t in (available_themes or list(constants._PALETTE_THEMES.keys()))] @@ -524,34 +569,47 @@ def generate_map_idea( system_msg = ( "You generate short, engaging map topic questions in English along with the best map rendering parameters. " + "Always pick a fresh, surprising angle and never repeat recent topics. " "Return ONLY a valid JSON object (no markdown fences, no commentary)." ) - user_prompt = ( - "Generate 1 new creative map topic idea in the same style as these examples:\n" - f"{examples_block}\n\n" - "Return a JSON object with these exact keys:\n" - '- "idea": string (the single map question/topic, no surrounding quotes)\n' - f'- "mode": one of {list(allowed_modes)} ("number" for numeric counts/amounts/years, "text" for names/words/categories)\n' - f'- "map_type": one of {list(allowed_map_types)} ("default" = Europe painted, "flag" = Europe flags, "world" = continents, "world_countries" = all world countries)\n' - f'- "palette_theme": one of {themes}\n' - f'- "font": one of {fonts}\n' - f'- "extra_option": one of {list(allowed_extras)} ("show_most_least" or "show_short_form" only when mode is "number" and map_type is not "world", otherwise "none")\n' - '- "show_legend": boolean (true if a legend helps explain the map, false otherwise)' - ) - raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=temperature, json_mode=True) - cleaned = raw.strip() - if cleaned.startswith("```"): - cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.IGNORECASE | re.DOTALL).strip() - try: - parsed = json.loads(cleaned) - except json.JSONDecodeError as error: - raise AIServiceError('AI returned invalid JSON for the map idea. Please try again.', 502) from error - if not isinstance(parsed, dict): - raise AIServiceError('AI returned an unexpected format for the map idea.', 502) - - idea = str(parsed.get("idea") or "").strip().strip('"\'` ') - if not idea: - raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + parsed = None + idea = "" + for attempt in range(2): + focus_category = random.choice(IDEA_CATEGORIES) + nonce = random.randint(1000, 9999) + retry_note = "\nPrevious candidate was a duplicate — choose a completely different subject." if attempt else "" + user_prompt = ( + f"Generate 1 fresh, creative map topic idea focused on: {focus_category} (variation #{nonce}).\n" + "Match the concise style of these examples without copying them:\n" + f"{examples_block}" + f"{avoid_block}" + f"{retry_note}\n\n" + "Return a JSON object with these exact keys:\n" + '- "idea": string (the single map question/topic, no surrounding quotes)\n' + f'- "mode": one of {list(allowed_modes)} ("number" for numeric counts/amounts/years, "text" for names/words/categories)\n' + f'- "map_type": one of {list(allowed_map_types)} ("default" = Europe painted, "flag" = Europe flags, "world" = continents, "world_countries" = all world countries)\n' + f'- "palette_theme": one of {themes}\n' + f'- "font": one of {fonts}\n' + f'- "extra_option": one of {list(allowed_extras)} ("show_most_least" or "show_short_form" only when mode is "number" and map_type is not "world", otherwise "none")\n' + '- "show_legend": boolean (true if a legend helps explain the map, false otherwise)' + ) + raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=idea_temp, json_mode=True) + cleaned = raw.strip() + if cleaned.startswith("```"): + cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.IGNORECASE | re.DOTALL).strip() + try: + candidate_obj = json.loads(cleaned) + except json.JSONDecodeError as error: + raise AIServiceError('AI returned invalid JSON for the map idea. Please try again.', 502) from error + if not isinstance(candidate_obj, dict): + raise AIServiceError('AI returned an unexpected format for the map idea.', 502) + candidate_idea = str(candidate_obj.get("idea") or "").strip().strip('"\'` ') + if not candidate_idea: + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + parsed = candidate_obj + idea = candidate_idea + if _normalize_idea_key(candidate_idea) not in avoid_keys: + break mode = str(parsed.get("mode") or "text").strip().lower() if mode not in allowed_modes: diff --git a/render_progress.py b/render_progress.py index 9e989de..d3d881f 100644 --- a/render_progress.py +++ b/render_progress.py @@ -63,13 +63,20 @@ def tracked(*args, **kwargs): return jsonify(status='error', error='Invalid render ID.'), 400 with self.lock: now = monotonic() - # Evict stale records older than 1 hour before checking capacity/duplicates. + # Keep active renders even if an encoding phase has no progress callbacks. self.records = {key: value for key, value in self.records.items() - if now - value['updated_at'] < 3600} + if value['status'] == 'rendering' or now - value['updated_at'] < 3600} if render_id in self.records: return jsonify(status='error', error='This render ID has already been used.'), 409 if len(self.records) >= 256: - return jsonify(status='error', error='Render service is busy. Try again later.'), 503 + oldest_finished = min( + (key for key, value in self.records.items() if value['status'] != 'rendering'), + key=lambda key: self.records[key]['updated_at'], + default=None, + ) + if oldest_finished is None: + return jsonify(status='error', error='Render service is busy. Try again later.'), 503 + del self.records[oldest_finished] self.records[render_id] = dict(status='rendering', progress=0, phase='Preparing materials', updated_at=now) g.render_progress_id = render_id diff --git a/templates/index.html b/templates/index.html index c5de43a..44050c6 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1643,12 +1643,38 @@

updateCommandPreview(); } + const RECENT_IDEAS_STORAGE_KEY = 'automap-recent-ideas'; + + function loadRecentIdeas() { + try { + const parsed = JSON.parse(localStorage.getItem(RECENT_IDEAS_STORAGE_KEY) || '[]'); + return Array.isArray(parsed) ? parsed.map(x => String(x || '').trim()).filter(Boolean).slice(-30) : []; + } catch { + return []; + } + } + + function rememberGeneratedIdea(ideaText) { + const cleaned = String(ideaText || '').trim(); + if (!cleaned) return; + const current = loadRecentIdeas().filter(item => item.toLowerCase() !== cleaned.toLowerCase()); + current.push(cleaned); + try { + localStorage.setItem(RECENT_IDEAS_STORAGE_KEY, JSON.stringify(current.slice(-30))); + } catch {} + } + async function generateIdea() { const btn = document.getElementById('generateIdeaBtn'); const icon = document.getElementById('generateIdeaIcon'); const textEl = document.getElementById('generateIdeaText'); const withParams = document.getElementById('ideaModeSelect')?.value === 'idea_and_params'; const state = getFormState(); + const avoidIdeas = loadRecentIdeas(); + const currentTopic = document.getElementById('topicInput')?.value?.trim(); + if (currentTopic && !avoidIdeas.some(item => item.toLowerCase() === currentTopic.toLowerCase())) { + avoidIdeas.push(currentTopic); + } if (btn) btn.disabled = true; if (icon) icon.className = 'fa-solid fa-spinner fa-spin text-[10px]'; @@ -1664,6 +1690,7 @@

api_key: state.api_key, with_params: withParams, temperature: state.temperature, + avoid_ideas: avoidIdeas.slice(-30), }), }); let result; @@ -1682,6 +1709,7 @@

scheduleTopicPreview(); flushTopicPreview(); } + rememberGeneratedIdea(result.idea); if (withParams && result.params) { const p = result.params; diff --git a/templates/video.html b/templates/video.html index 821cd5e..9a4f955 100644 --- a/templates/video.html +++ b/templates/video.html @@ -2514,6 +2514,7 @@

const map = document.getElementById('stageMapPreview'); const area = document.getElementById('stageMapArea'); if (!map.naturalWidth || !map.naturalHeight) return; + area.style.justifyContent = map.naturalWidth < map.naturalHeight ? 'flex-end' : 'center'; const scale = Math.min(area.clientWidth / map.naturalWidth, area.clientHeight / map.naturalHeight); map.style.width = `${map.naturalWidth * scale}px`; map.style.height = `${map.naturalHeight * scale}px`; diff --git a/tests/test_render_progress.py b/tests/test_render_progress.py index e29ef13..9baa2df 100644 --- a/tests/test_render_progress.py +++ b/tests/test_render_progress.py @@ -61,6 +61,28 @@ def test_worker_records_validation_failures_and_rejects_bad_ids(worker): assert client.post('/api/render_video', json={'render_id': 'invalid'}).status_code == 400 +def test_completed_records_do_not_block_new_renders_at_capacity(): + app = Flask(__name__) + tracker = RenderProgress() + active_id, oldest_finished_id = str(uuid4()), str(uuid4()) + tracker.records[active_id] = dict(status='rendering', progress=0, updated_at=0) + + @app.post('/render') + @tracker.track + def render(): + return jsonify(status='success') + + with app.test_client() as client: + assert client.post('/render', json={'render_id': oldest_finished_id}).status_code == 200 + for _ in range(255): + assert client.post('/render', json={'render_id': str(uuid4())}).status_code == 200 + assert client.post('/render', json={'render_id': active_id}).status_code == 409 + + assert tracker.snapshot(oldest_finished_id) is None + assert tracker.snapshot(active_id)['status'] == 'rendering' + assert len(tracker.records) == 256 + + def test_failed_render_does_not_claim_completion(): app = Flask(__name__) tracker = RenderProgress() diff --git a/tests/test_video_render.py b/tests/test_video_render.py index a4c9828..4499cb1 100644 --- a/tests/test_video_render.py +++ b/tests/test_video_render.py @@ -143,7 +143,7 @@ def test_portrait_render_with_centered_title_and_right_aligned_map(worker, tmp_p frame = result.get_frame(.1) green = (frame[:, :, 1] > 220) & (frame[:, :, 0] < 30) ys, xs = np.where(green) - assert abs((xs.min() + xs.max()) / 2 - 540) < 3 + assert xs.max() >= 1078 assert ys.max() <= 1865 if map_size[1] > map_size[0]: assert (xs.max() - xs.min()) / (ys.max() - ys.min()) == pytest.approx(map_size[0] / map_size[1], abs=.03) diff --git a/video_render.py b/video_render.py index 2e1cce5..ce44f66 100644 --- a/video_render.py +++ b/video_render.py @@ -124,9 +124,7 @@ def flush(): pos = compute_position(layer.size, size, clip.pos(0), clip.relative_pos) if canvas is None: canvas = Image.new('RGBA', size, (0, 0, 0, 0)) - placed = Image.new('RGBA', size, (0, 0, 0, 0)) - placed.paste(layer, tuple(int(v) for v in pos)) - canvas = Image.alpha_composite(canvas, placed) + canvas.alpha_composite(layer, tuple(int(v) for v in pos)) flush() return out diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index 724267b..02f38b1 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -1123,7 +1123,8 @@ def _decode_optional_image(field: str, label: str): map_clip = map_clip.resized(scale) box_w, box_h = int(map_clip.w), int(map_clip.h) map_y = map_top + (map_area_height - box_h) / 2 - map_x = (canvas_w - box_w) / 2.0 + map_x = float(canvas_w - box_w) if box_w < canvas_w else (canvas_w - box_w) / 2.0 + map_clip_x = map_x - (24 if effects else 0) zoom_enabled = bool(data.get('zoom_enabled', False)) zoom_x = max(0.0, min(1.0, _parse_finite_float(data.get('zoom_x'), 0.80))) @@ -1165,7 +1166,7 @@ def _decode_optional_image(field: str, label: str): if raw_reveal is not None: spec_w, spec_h, f1, f2, f3, blk, base, rt, pe, fd = raw_reveal rust_reveal_spec = ( - (canvas_w - spec_w) // 2, + int(map_clip_x), int(map_y), spec_w, spec_h, @@ -1186,7 +1187,7 @@ def _decode_optional_image(field: str, label: str): map_y -= 24 title_clip = title_clip.with_position(("center", title_top)) - map_clip = map_clip.with_position(("center", map_y)) + map_clip = map_clip.with_position((map_clip_x, map_y)) if reveal_active: dynamic_layers.add(id(map_clip)) From d66e851aaa848b0c2a0c514322d9ae220148b4b9 Mon Sep 17 00:00:00 2001 From: bibed234 Date: Thu, 19 Nov 2026 14:54:34 +0200 Subject: [PATCH 3/4] Skip color rules/legend for flag maps and raise material upload limit to 15 MB --- main.py | 2 +- map/auto_map.py | 96 +++++++++++++++++++++----------------- templates/index.html | 28 ++++++++--- templates/video.html | 24 +++++----- tests/test_audio_upload.py | 4 +- tests/test_worker.py | 2 +- tests/test_worker_audit.py | 2 +- yt-dlp_serv.py | 16 +++---- 8 files changed, 101 insertions(+), 73 deletions(-) diff --git a/main.py b/main.py index 67d7f9b..424c1af 100644 --- a/main.py +++ b/main.py @@ -123,7 +123,7 @@ def _available_fonts(): app = Flask(__name__) # Three 10 MiB materials (map, background and music) grow by 4/3 in JSON. -app.config["MAX_CONTENT_LENGTH"] = 48 * 1024 * 1024 +app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024 from web_auth import init_web_auth diff --git a/map/auto_map.py b/map/auto_map.py index e031e15..7cc17d6 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -967,16 +967,24 @@ def _report(stage: int, label: str) -> None: log.success(f"Got information from AI ({len(ai_answer)} entries)") - 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, - ) + is_painted_map = map_type in constants._PAINTED_MAP_TYPES + if is_painted_map: + 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, + ) + else: + resolved_theme = "flags" + auto_txt, auto_num = {}, {} + filling_txt = {} + filling_txt_ci = {} + filling_num = {} theme_requested = (palette_theme or "auto").strip().lower() != "auto" - if auto_style is True: + if is_painted_map and auto_style is True: if mode == "text": merged_txt = dict(auto_txt) req_keys_low = {k.strip().lower() for k in req_txt} @@ -1078,39 +1086,43 @@ def _report(stage: int, label: str) -> None: if mode == 'number': try: info = ai_answer_norm[name_key] - color = _random_region_color() + color = _random_region_color() if is_painted_map else (0, 0, 0, 0) num_value = _parse_short_number(info) raw_num_value = _parse_short_number(raw_ai_answer_norm.get(name_key)) - if num_value is None: + if num_value is None and is_painted_map: log.warning(f"Non-numeric value for {name}: {info!r}; using random color") if num_value is not None: if highlight_extrema: numeric_region_values[index] = float(raw_num_value if raw_num_value is not None else num_value) - # Pick the colour of the first matching range. Ranges are - # treated as (low < value <= high) per the docs. - matched_bounds = None - for candidate in (num_value, raw_num_value): - if candidate is None or matched_bounds is not None: - continue - for (low_lim, high_lim), color_tup in filling_num.items(): - if low_lim < candidate <= 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 + if is_painted_map: + # Pick the colour of the first matching range. Ranges are + # treated as (low < value <= high) per the docs. + matched_bounds = None + for candidate in (num_value, raw_num_value): + if candidate is None or matched_bounds is not None: + continue + for (low_lim, high_lim), color_tup in filling_num.items(): + if low_lim < candidate <= 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") - color = _random_region_color() - random_colors[name] = color + if is_painted_map: + log.warning(f"No data / color for {e}; using random color") + color = _random_region_color() + random_colors[name] = color + else: + color = (0, 0, 0, 0) elif mode == 'text': '''Text mode''' @@ -1119,12 +1131,12 @@ def _report(stage: int, label: str) -> None: if not info: log.info(f"No information for {name}, skipping") continue - try: - # Match filling colours case-insensitively and ignoring whitespace, - # so "Yes", "yes" and " yes " all find the same colour. - color = filling_txt_ci[info.lower()] - except KeyError: - if map_type in constants._PAINTED_MAP_TYPES: + if is_painted_map: + try: + # Match filling colours case-insensitively and ignoring whitespace, + # so "Yes", "yes" and " yes " all find the same colour. + color = filling_txt_ci[info.lower()] + except KeyError: log.info(f"No filling color for '{info}'; using random") # Repeated answers share a color so categories remain recognizable. try: @@ -1132,9 +1144,9 @@ def _report(stage: int, label: str) -> None: except KeyError: color = _random_region_color() random_colors[info] = color - else: - color = _random_region_color() - used_txt_rules.setdefault(info, color) + used_txt_rules.setdefault(info, color) + else: + color = (0, 0, 0, 0) else: showerror("Error", f"Unknown mode: {mode}") return @@ -1298,7 +1310,7 @@ def _report(stage: int, label: str) -> None: else: result = _alpha_composite(img, text_layer) - if show_legend: + if show_legend and is_painted_map: if mode == "number": legend_src = used_num_rules or effective_num legend_entries = [ diff --git a/templates/index.html b/templates/index.html index 44050c6..c4fe9f6 100644 --- a/templates/index.html +++ b/templates/index.html @@ -2338,15 +2338,23 @@

// Match cli.py's signature: `cli.py make "" -m ... -mp ... -gsm ... -eop ... --model ... --font ...` const escapedTopic = (state.topic || '').replace(/"/g, '\\"'); let cmd = `python cli.py make "${escapedTopic}" -m ${state.mode} -mp ${state.map_type} -gsm ${state.gsm} -eop ${state.extra_option} --model ${state.model} --font "${state.font}" --temperature ${state.temperature}`; - if (state.show_legend) cmd += ' --legend'; + const isFlagMap = state.map_type === 'flag' || state.map_type === 'world_countries'; + if (state.show_legend && !isFlagMap) cmd += ' --legend'; if (state.highlight_extrema) cmd += ' --highlight-extrema'; document.getElementById('cliCommandDisplay').textContent = cmd; const hlColorsRow = document.getElementById('highlightColorsRow'); if (hlColorsRow) hlColorsRow.classList.toggle('hidden', !state.highlight_extrema); + const legendEl = document.getElementById('showLegendToggle'); + if (legendEl) { + legendEl.disabled = isFlagMap; + const legendLabel = legendEl.closest('label'); + if (legendLabel) legendLabel.classList.toggle('opacity-50', isFlagMap); + } updateActiveBadges(state); updateCompatibilityHint(state); updateHudCoords(state); + if (typeof renderFillingStudio === 'function') renderFillingStudio(); } function updateCompatibilityHint(state) { @@ -3160,18 +3168,26 @@

jsonPreview.textContent = JSON.stringify(fillingObj, null, 2); } + const currentMapType = document.querySelector('input[name="map_type"]:checked')?.value || 'default'; + const isFlagMap = currentMapType === 'flag' || currentMapType === 'world_countries'; const allColors = [...fillingTxtRules.map(r => r.hex), ...fillingNumRules.map(r => r.hex)].slice(0, 6); if (miniSwatches) { - miniSwatches.innerHTML = allColors.map(hex => + miniSwatches.innerHTML = isFlagMap ? '' : allColors.map(hex => `` ).join(''); } const totalRules = fillingTxtRules.length + fillingNumRules.length; if (summaryBadge) { - summaryBadge.textContent = isAuto ? `Auto • ${totalRules} rules` : `Custom • ${totalRules} rules`; - } - if (sidebarSub && lastMapAnalysis) { - sidebarSub.textContent = `Detected ${lastMapAnalysis.detected_type} (${lastMapAnalysis.resolved_theme}) • Font: ${labelStyleConfig.recommended_font}`; + summaryBadge.textContent = isFlagMap + ? 'Flags (no fill)' + : (isAuto ? `Auto • ${totalRules} rules` : `Custom • ${totalRules} rules`); + } + if (sidebarSub) { + if (isFlagMap) { + sidebarSub.textContent = `Flag artwork active • Font: ${labelStyleConfig.recommended_font}`; + } else if (lastMapAnalysis) { + sidebarSub.textContent = `Detected ${lastMapAnalysis.detected_type} (${lastMapAnalysis.resolved_theme}) • Font: ${labelStyleConfig.recommended_font}`; + } } } diff --git a/templates/video.html b/templates/video.html index 9a4f955..3fbf08a 100644 --- a/templates/video.html +++ b/templates/video.html @@ -505,7 +505,7 @@

Music Downloader

-

MP3, WAV, M4A, AAC, OGG or FLAC · up to 10 MB. Upload a track to preview, cut or use it in your video.

+

MP3, WAV, M4A, AAC, OGG or FLAC · up to 15 MB. Upload a track to preview, cut or use it in your video.

@@ -755,7 +755,7 @@

Frame Com

Drop map image or click to browse

-

PNG / JPG · max 10 MB

+

PNG / JPG · max 15 MB