diff --git a/.dockerignore b/.dockerignore index ab54a02..273e032 100644 --- a/.dockerignore +++ b/.dockerignore @@ -57,3 +57,6 @@ result.png Dockerfile* docker-compose*.yml .dockerignore + +client_secret*.json +client_secrets*.json diff --git a/.gitignore b/.gitignore index f41a3b1..79d59f1 100644 --- a/.gitignore +++ b/.gitignore @@ -66,3 +66,7 @@ instance/ *.so *.dylib *.pyd + +# Google OAuth client downloads must never be committed. +client_secret*.json +client_secrets*.json diff --git a/automap_rs/.cargo/config.toml b/automap_rs/.cargo/config.toml new file mode 100644 index 0000000..7cb83a1 --- /dev/null +++ b/automap_rs/.cargo/config.toml @@ -0,0 +1,11 @@ +[target.aarch64-apple-darwin] +rustflags = [ + "-C", "link-arg=-undefined", + "-C", "link-arg=dynamic_lookup", +] + +[target.x86_64-apple-darwin] +rustflags = [ + "-C", "link-arg=-undefined", + "-C", "link-arg=dynamic_lookup", +] diff --git a/automap_rs/src/lib.rs b/automap_rs/src/lib.rs index a0ee964..59b7e69 100644 --- a/automap_rs/src/lib.rs +++ b/automap_rs/src/lib.rs @@ -12,27 +12,71 @@ // See the License for the specific language governing permissions and // limitations under the License. +use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +use pyo3::types::{PyBytes, PyTuple}; use std::io::{Read, Write}; use std::process::{Command, Stdio}; /// Describes a single dynamic overlay layer passed from Python as a tuple: /// `(rgba_bytes, x, y, width, height, start_sec, fade_in_sec)`. #[derive(FromPyObject)] -struct DynamicLayer { - rgba: Vec, - x: i32, - y: i32, - width: usize, - height: usize, - start_sec: f32, - fade_in_sec: f32, +struct DynamicLayer(Vec, i32, i32, usize, usize, f32, f32); + +/// Optional camera zoom parameters: +/// `(target_cx, target_cy, z_scale, z_start, z_dur, z_out_enabled, z_out_dur)`. +type ZoomParams = (f32, f32, f32, f32, f32, bool, f32); + +/// Optional country reveal animation & impact FX specification: +/// `(x, y, w, h, frame1_rgba, frame2_rgba, frame3_rgba, black_rgba, base_rgba, r_time, phase_end, fade_dur, impact_fx)`. +struct RevealSpec( + i32, + i32, + usize, + usize, + Vec, + Vec, + Vec, + Vec, + Vec, + f32, + f32, + f32, + bool, +); + +impl<'py> FromPyObject<'py> for RevealSpec { + fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult { + let t = ob.downcast::()?; + if t.len() != 13 { + return Err(PyValueError::new_err(format!( + "reveal_spec must be a 13-tuple, got length {}", + t.len() + ))); + } + Ok(Self( + t.get_item(0)?.extract()?, + t.get_item(1)?.extract()?, + t.get_item(2)?.extract()?, + t.get_item(3)?.extract()?, + t.get_item(4)?.extract()?, + t.get_item(5)?.extract()?, + t.get_item(6)?.extract()?, + t.get_item(7)?.extract()?, + t.get_item(8)?.extract()?, + t.get_item(9)?.extract()?, + t.get_item(10)?.extract()?, + t.get_item(11)?.extract()?, + t.get_item(12)?.extract()?, + )) + } } -/// Composites the background video, static foreground, dynamic overlays, and intro veil -/// frame-by-frame in a single reusable RGBA buffer, streaming directly to/from `ffmpeg`. +/// Composites the background video, static foreground, country reveal animation, +/// dynamic overlays, intro veil, camera zoom, and impact FX frame-by-frame in reusable +/// RGBA buffers, streaming directly to/from `ffmpeg`. #[pyfunction] -#[pyo3(signature = (bg_video_path, static_rgba, dynamic_layers, veil_duration, audio_path, output_path, width, height, fps, duration, codec, preset=None, draft=false))] +#[pyo3(signature = (bg_video_path, static_rgba, dynamic_layers, veil_duration, audio_path, output_path, width, height, fps, duration, codec, preset=None, draft=false, zoom_params=None, reveal_spec=None))] #[allow(clippy::too_many_arguments)] fn render_video_rs( py: Python<'_>, @@ -49,6 +93,8 @@ fn render_video_rs( codec: &str, preset: Option<&str>, draft: bool, + zoom_params: Option, + reveal_spec: Option, ) -> PyResult<()> { let expected_len = width * height * 4; if static_rgba.len() != expected_len { @@ -60,18 +106,42 @@ fn render_video_rs( expected_len ))); } + if let Some(RevealSpec(_, _, rw, rh, ref f1, ref f2, ref f3, ref black, ref base, _, _, _, _)) = reveal_spec { + let rev_len = rw * rh * 4; + for (name, buf) in [ + ("frame1_rgba", f1), + ("frame2_rgba", f2), + ("frame3_rgba", f3), + ("black_rgba", black), + ("base_rgba", base), + ] { + if buf.len() != rev_len { + return Err(PyValueError::new_err(format!( + "reveal_spec {name} length {} does not match {}x{}x4 ({})", + buf.len(), + rw, + rh, + rev_len + ))); + } + } + } // Release Python's GIL so other Flask/worker threads are not blocked during rendering. py.allow_threads(|| { + let ffmpeg_bin = std::env::var("FFMPEG_BINARY").unwrap_or_else(|_| "ffmpeg".to_string()); let total_frames = (duration * fps as f32).round().max(1.0) as u32; let dur_str = format!("{duration:.3}"); + let fps_str = fps.to_string(); - // 1. Spawn ffmpeg decoder: reads the prepared background MP4 and outputs raw RGBA frames. - let mut decoder = Command::new("ffmpeg") + // 1. Spawn ffmpeg decoder: reads the prepared background MP4 and outputs raw RGBA frames at `fps`. + let mut decoder = Command::new(&ffmpeg_bin) .args([ "-y", "-i", bg_video_path, + "-r", + &fps_str, "-t", &dur_str, "-f", @@ -92,7 +162,6 @@ fn render_video_rs( // 2. Build ffmpeg encoder args: reads raw RGBA frames from stdin and encodes with the chosen codec. let size_str = format!("{width}x{height}"); - let fps_str = fps.to_string(); let mut enc_args: Vec = vec![ "-y".into(), "-f".into(), @@ -120,7 +189,7 @@ fn render_video_rs( } enc_args.extend(["-pix_fmt".into(), "yuv420p".into(), output_path.into()]); - let mut encoder = Command::new("ffmpeg") + let mut encoder = Command::new(&ffmpeg_bin) .args(&enc_args) .stdin(Stdio::piped()) .stderr(Stdio::null()) @@ -132,56 +201,157 @@ fn render_video_rs( .take() .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("missing encoder stdin"))?; - // 3. Single reusable frame buffer (~8.3 MB for 1080x1920 RGBA) to avoid per-frame allocations. + // 3. Precompute non-transparent byte spans in static_rgba so alpha==0 regions are skipped per frame. + let static_spans = build_non_transparent_spans(static_rgba); + + // 4. Reusable background, compositing, and zoom/FX frame buffers (~8.3 MB each for 1080x1920 RGBA). + let impact_fx_enabled = reveal_spec.as_ref().is_some_and(|r| r.12); + let need_zoom_buf = zoom_params.is_some() || impact_fx_enabled; + let mut bg_buf = vec![0u8; expected_len]; let mut frame_buf = vec![0u8; expected_len]; + let mut zoom_buf = if need_zoom_buf { vec![0u8; expected_len] } else { Vec::new() }; + let mut ca_row_buf = if impact_fx_enabled { vec![0u8; width * 4] } else { Vec::new() }; + let mut x_resample_lut = if need_zoom_buf { Vec::with_capacity(width) } else { Vec::new() }; for frame_idx in 0..total_frames { - if dec_out.read_exact(&mut frame_buf).is_err() { - break; + if dec_out.read_exact(&mut bg_buf).is_err() { + if frame_idx == 0 { + break; + } + // Hold the last decoded background frame if the source ended slightly early. } + frame_buf.copy_from_slice(&bg_buf); let t = frame_idx as f32 / fps as f32; // Layer 1: flattened static foreground (map, title, watermark). - blend_full_in_place(&mut frame_buf, static_rgba, 1.0); + blend_spans_in_place(&mut frame_buf, static_rgba, &static_spans); + + // Layer 1b: country reveal animation (dots -> fade from black to base). + if let Some(RevealSpec(rx, ry, rw, rh, ref f1, ref f2, ref f3, ref black, ref base, r_time, phase_end, fade_dur, _)) = + reveal_spec + { + if t < r_time { + let dot_frame = if t < phase_end * 0.33 { + f1 + } else if t < phase_end * 0.66 { + f2 + } else { + f3 + }; + blend_rect_in_place(&mut frame_buf, width, height, dot_frame, rx, ry, rw, rh, 255); + } else if t >= r_time + fade_dur { + blend_rect_in_place(&mut frame_buf, width, height, base, rx, ry, rw, rh, 255); + } else { + let fade_alpha = (1.0 - (t - r_time) / fade_dur).clamp(0.0, 1.0); + let fade_q8 = (fade_alpha * 256.0).round().clamp(0.0, 256.0) as i32; + blend_lerp_rect_in_place(&mut frame_buf, width, height, base, black, rx, ry, rw, rh, fade_q8); + } + } // Layer 2: dynamic overlays (subscribe badge, stars) with optional fade-in. for layer in &dynamic_layers { - if t < layer.start_sec { + let start_sec = layer.5; + let fade_in_sec = layer.6; + if t < start_sec { continue; } - let opacity = if layer.fade_in_sec > 0.0 { - ((t - layer.start_sec) / layer.fade_in_sec).clamp(0.0, 1.0) + let opacity = if fade_in_sec > 0.0 { + ((t - start_sec) / fade_in_sec).clamp(0.0, 1.0) } else { 1.0 }; + let op_u8 = (opacity * 255.0).round().clamp(0.0, 255.0) as u32; + if op_u8 == 0 { + continue; + } blend_rect_in_place( &mut frame_buf, width, height, - &layer.rgba, - layer.x, - layer.y, - layer.width, - layer.height, - opacity, + &layer.0, + layer.1, + layer.2, + layer.3, + layer.4, + op_u8, ); } // Layer 3: intro fade-in veil (darkens RGB channels linearly at the start). if veil_duration > 0.0 && t < veil_duration { let veil_alpha = (0.88 * (1.0 - (t / veil_duration))).clamp(0.0, 1.0); - let brightness = 1.0 - veil_alpha; - for px in frame_buf.chunks_exact_mut(4) { - px[0] = (px[0] as f32 * brightness) as u8; - px[1] = (px[1] as f32 * brightness) as u8; - px[2] = (px[2] as f32 * brightness) as u8; + let brightness_q8 = ((1.0 - veil_alpha) * 256.0).round().clamp(0.0, 256.0) as u32; + if brightness_q8 < 256 { + for px in frame_buf.chunks_exact_mut(4) { + px[0] = ((px[0] as u32 * brightness_q8) >> 8) as u8; + px[1] = ((px[1] as u32 * brightness_q8) >> 8) as u8; + px[2] = ((px[2] as u32 * brightness_q8) >> 8) as u8; + } } } + // Layer 4: camera zoom + reveal impact FX (punch, shake, CA, glitch bands, flash). + let out_buf: &[u8] = if need_zoom_buf { + let (mut cw, mut ch, mut x0, mut y0) = if let Some(zp) = zoom_params { + compute_zoom_crop(zp, width as f32, height as f32, t, duration) + } else { + (width as f32, height as f32, 0.0, 0.0) + }; + + let impact_dt = if impact_fx_enabled { + reveal_spec.as_ref().map(|r| t - r.9).filter(|&dt| (0.0..0.60).contains(&dt)) + } else { + None + }; + + if let Some(dt) = impact_dt { + let env = (-dt * 5.8).exp() * (1.0 - dt / 0.60).max(0.0); + let punch = 1.0 + 0.042 * env; + let inv_p = 1.0 / punch; + let new_cw = cw * inv_p; + let new_ch = ch * inv_p; + let margin_x = (cw - new_cw) * 0.5; + let margin_y = (ch - new_ch) * 0.5; + let shake_x = env * 22.0 * (dt * 85.0).sin() + env * 8.0 * (dt * 145.0).cos(); + let shake_y = env * 18.0 * (dt * 78.0).cos() - env * 6.0 * (dt * 130.0).sin(); + cw = new_cw; + ch = new_ch; + x0 = (x0 + margin_x + shake_x).clamp(0.0, (width as f32 - cw).max(0.0)); + y0 = (y0 + margin_y + shake_y).clamp(0.0, (height as f32 - ch).max(0.0)); + } + + let do_resample = cw < width as f32 - 0.5 || x0.abs() > 0.1 || y0.abs() > 0.1; + let active_buf: &mut [u8] = if do_resample { + bilinear_resample_rgba( + &frame_buf, + &mut zoom_buf, + width, + height, + x0, + y0, + cw, + ch, + &mut x_resample_lut, + ); + &mut zoom_buf + } else { + &mut frame_buf + }; + + if let Some(dt) = impact_dt { + if dt < 0.38 { + apply_impact_fx_in_place(active_buf, width, height, dt, &mut ca_row_buf); + } + } + active_buf + } else { + &frame_buf + }; + // Stream the composited frame into ffmpeg's stdin. enc_in - .write_all(&frame_buf) + .write_all(out_buf) .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("encoder write failed: {e}")))?; } @@ -201,14 +371,60 @@ fn render_video_rs( }) } -/// Alpha-blends a full-canvas RGBA overlay onto `base` in place. -fn blend_full_in_place(base: &mut [u8], overlay: &[u8], opacity: f32) { - if opacity <= 0.0 { - return; +/// Collects contiguous byte ranges `[start, end)` in `rgba` where `alpha > 0`. +fn build_non_transparent_spans(rgba: &[u8]) -> Vec<(usize, usize)> { + let mut spans = Vec::new(); + let mut in_span = false; + let mut start = 0usize; + for (idx, px) in rgba.chunks_exact(4).enumerate() { + let non_zero = px[3] > 0; + if non_zero && !in_span { + start = idx * 4; + in_span = true; + } else if !non_zero && in_span { + spans.push((start, idx * 4)); + in_span = false; + } + } + if in_span { + spans.push((start, rgba.len() - (rgba.len() % 4))); + } + spans +} + +/// Alpha-blends precomputed non-transparent byte spans of `overlay` onto `base` in place. +fn blend_spans_in_place(base: &mut [u8], overlay: &[u8], spans: &[(usize, usize)]) { + for &(start, end) in spans { + for (bg, fg) in base[start..end].chunks_exact_mut(4).zip(overlay[start..end].chunks_exact(4)) { + blend_pixel_u8(bg, fg); + } } - for (bg, fg) in base.chunks_exact_mut(4).zip(overlay.chunks_exact(4)) { - blend_pixel(bg, fg, opacity); +} + +/// Computes the clipped destination/source bounds for a positioned overlay rectangle. +/// Returns `(start_x, start_y, end_y, row_bytes, ox_start)` or `None` if completely off-screen. +#[inline] +fn clip_rect( + canvas_w: usize, + canvas_h: usize, + x: i32, + y: i32, + ov_w: usize, + ov_h: usize, +) -> Option<(usize, usize, usize, usize, usize)> { + if ov_w == 0 || ov_h == 0 { + return None; } + let start_y = y.max(0) as usize; + let end_y = (y + ov_h as i32).min(canvas_h as i32).max(0) as usize; + let start_x = x.max(0) as usize; + let end_x = (x + ov_w as i32).min(canvas_w as i32).max(0) as usize; + if start_x >= end_x || start_y >= end_y { + return None; + } + let row_bytes = (end_x - start_x) * 4; + let ox_start = (start_x as i32 - x) as usize; + Some((start_x, start_y, end_y, row_bytes, ox_start)) } /// Alpha-blends a positioned rectangular RGBA overlay onto `base` in place, clipped to canvas bounds. @@ -222,47 +438,400 @@ fn blend_rect_in_place( y: i32, ov_w: usize, ov_h: usize, - opacity: f32, + op_u8: u32, ) { - if opacity <= 0.0 || ov_w == 0 || ov_h == 0 { + if op_u8 == 0 { return; } - let start_y = y.max(0) as usize; - let end_y = (y + ov_h as i32).min(canvas_h as i32).max(0) as usize; - let start_x = x.max(0) as usize; - let end_x = (x + ov_w as i32).min(canvas_w as i32).max(0) as usize; + let Some((start_x, start_y, end_y, row_bytes, ox_start)) = clip_rect(canvas_w, canvas_h, x, y, ov_w, ov_h) + else { + return; + }; for cy in start_y..end_y { let oy = (cy as i32 - y) as usize; - for cx in start_x..end_x { - let ox = (cx as i32 - x) as usize; - let bg_idx = (cy * canvas_w + cx) * 4; - let fg_idx = (oy * ov_w + ox) * 4; - if fg_idx + 4 <= overlay.len() && bg_idx + 4 <= base.len() { - blend_pixel(&mut base[bg_idx..bg_idx + 4], &overlay[fg_idx..fg_idx + 4], opacity); + let bg_start = (cy * canvas_w + start_x) * 4; + let fg_start = (oy * ov_w + ox_start) * 4; + if fg_start + row_bytes > overlay.len() || bg_start + row_bytes > base.len() { + continue; + } + let bg_row = &mut base[bg_start..bg_start + row_bytes]; + let fg_row = &overlay[fg_start..fg_start + row_bytes]; + if op_u8 == 255 { + for (bg, fg) in bg_row.chunks_exact_mut(4).zip(fg_row.chunks_exact(4)) { + blend_pixel_u8(bg, fg); + } + } else { + for (bg, fg) in bg_row.chunks_exact_mut(4).zip(fg_row.chunks_exact(4)) { + blend_pixel_scaled(bg, fg, op_u8); + } + } + } +} + +/// Linearly interpolates `base_ov + (fade_q8 / 256) * (black_ov - base_ov)` and alpha-blends +/// the resulting RGBA pixels onto `canvas` at `(x, y)` in place. +#[allow(clippy::too_many_arguments)] +fn blend_lerp_rect_in_place( + canvas: &mut [u8], + canvas_w: usize, + canvas_h: usize, + base_ov: &[u8], + black_ov: &[u8], + x: i32, + y: i32, + ov_w: usize, + ov_h: usize, + fade_q8: i32, +) { + let Some((start_x, start_y, end_y, row_bytes, ox_start)) = clip_rect(canvas_w, canvas_h, x, y, ov_w, ov_h) + else { + return; + }; + + for cy in start_y..end_y { + let oy = (cy as i32 - y) as usize; + let dst_start = (cy * canvas_w + start_x) * 4; + let src_start = (oy * ov_w + ox_start) * 4; + if src_start + row_bytes > base_ov.len() + || src_start + row_bytes > black_ov.len() + || dst_start + row_bytes > canvas.len() + { + continue; + } + let dst_row = &mut canvas[dst_start..dst_start + row_bytes]; + let base_row = &base_ov[src_start..src_start + row_bytes]; + let black_row = &black_ov[src_start..src_start + row_bytes]; + for ((dst, b), k) in dst_row + .chunks_exact_mut(4) + .zip(base_row.chunks_exact(4)) + .zip(black_row.chunks_exact(4)) + { + let fg = [ + (b[0] as i32 + (((k[0] as i32 - b[0] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + (b[1] as i32 + (((k[1] as i32 - b[1] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + (b[2] as i32 + (((k[2] as i32 - b[2] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + (b[3] as i32 + (((k[3] as i32 - b[3] as i32) * fade_q8 + 128) >> 8)).clamp(0, 255) as u8, + ]; + blend_pixel_u8(dst, &fg); + } + } +} + +#[inline] +fn smootherstep(u: f32) -> f32 { + u * u * u * (u * (u * 6.0 - 15.0) + 10.0) +} + +/// Computes the camera zoom crop `(cw, ch, x0, y0)` at time `t` using quintic smootherstep. +fn compute_zoom_crop(zp: ZoomParams, canvas_w: f32, canvas_h: f32, t: f32, total_dur: f32) -> (f32, f32, f32, f32) { + let (target_cx, target_cy, z_scale, z_start, z_dur, z_out_enabled, z_out_dur) = zp; + if z_scale <= 1.0 || t <= z_start { + return (canvas_w, canvas_h, 0.0, 0.0); + } + + let final_cw = canvas_w / z_scale; + let final_ch = canvas_h / z_scale; + let final_x0 = (target_cx - final_cw * 0.5).clamp(0.0, (canvas_w - final_cw).max(0.0)); + let final_y0 = (target_cy - final_ch * 0.5).clamp(0.0, (canvas_h - final_ch).max(0.0)); + + let ease = if z_dur > 0.0 && t < z_start + z_dur { + smootherstep((t - z_start) / z_dur) + } else if z_out_enabled && z_out_dur > 0.0 && total_dur > (z_start + z_dur + 0.05) { + let out_start = (z_start + z_dur).max(total_dur - z_out_dur); + let out_dur = (total_dur - out_start).max(0.05); + if t >= total_dur { + 0.0 + } else if t > out_start { + 1.0 - smootherstep((t - out_start) / out_dur) + } else { + 1.0 + } + } else { + 1.0 + }; + + if ease <= 0.0 { + return (canvas_w, canvas_h, 0.0, 0.0); + } + + let cw = canvas_w + (final_cw - canvas_w) * ease; + let ch = canvas_h + (final_ch - canvas_h) * ease; + let x0 = final_x0 * ease; + let y0 = final_y0 * ease; + (cw, ch, x0, y0) +} + +/// Fast 8-bit fixed-point bilinear resample of the crop `[x0, x0+cw] x [y0, y0+ch]` from `src` into `dst`. +#[allow(clippy::too_many_arguments)] +fn bilinear_resample_rgba( + src: &[u8], + dst: &mut [u8], + width: usize, + height: usize, + x0: f32, + y0: f32, + cw: f32, + ch: f32, + x_lut: &mut Vec<(usize, usize, u32, u32)>, +) { + if width == 0 || height == 0 { + return; + } + let scale_x = cw / width as f32; + let scale_y = ch / height as f32; + let max_x = (width - 1) as f32; + let max_y = (height - 1) as f32; + + x_lut.clear(); + for dx in 0..width { + let sx = (x0 + (dx as f32 + 0.5) * scale_x - 0.5).clamp(0.0, max_x); + let ix0 = (sx as usize).min(width - 1); + let ix1 = (ix0 + 1).min(width - 1); + let wx1 = ((sx - ix0 as f32) * 256.0).round().clamp(0.0, 256.0) as u32; + let wx0 = 256 - wx1; + x_lut.push((ix0 * 4, ix1 * 4, wx0, wx1)); + } + + let row_stride = width * 4; + for dy in 0..height { + let sy = (y0 + (dy as f32 + 0.5) * scale_y - 0.5).clamp(0.0, max_y); + let iy0 = (sy as usize).min(height - 1); + let iy1 = (iy0 + 1).min(height - 1); + let wy1 = ((sy - iy0 as f32) * 256.0).round().clamp(0.0, 256.0) as u32; + let wy0 = 256 - wy1; + + let row0 = &src[iy0 * row_stride..(iy0 + 1) * row_stride]; + let row1 = &src[iy1 * row_stride..(iy1 + 1) * row_stride]; + let dst_row = &mut dst[dy * row_stride..(dy + 1) * row_stride]; + + for (dst_px, &(ox0, ox1, wx0, wx1)) in dst_row.chunks_exact_mut(4).zip(x_lut.iter()) { + let p00 = &row0[ox0..ox0 + 4]; + let p10 = &row0[ox1..ox1 + 4]; + let p01 = &row1[ox0..ox0 + 4]; + let p11 = &row1[ox1..ox1 + 4]; + + for c in 0..3 { + let top = p00[c] as u32 * wx0 + p10[c] as u32 * wx1; + let bot = p01[c] as u32 * wx0 + p11[c] as u32 * wx1; + dst_px[c] = ((top * wy0 + bot * wy1 + 32768) >> 16) as u8; + } + dst_px[3] = 255; + } + } +} + +/// Applies RGB chromatic aberration, horizontal glitch band rolls, and flash brightness boost in place. +fn apply_impact_fx_in_place(buf: &mut [u8], width: usize, height: usize, dt: f32, row_buf: &mut [u8]) { + if width == 0 || height == 0 { + return; + } + let glitch_env = (-dt * 7.5).exp(); + let sign = if (dt * 105.0).sin() >= 0.0 { 1.0 } else { -1.0 }; + let ca_shift = (10.0 * glitch_env * sign).round() as i32; + let row_stride = width * 4; + + if ca_shift > 0 && (ca_shift as usize) < width { + let s = ca_shift as usize; + for row in buf.chunks_exact_mut(row_stride) { + row_buf.copy_from_slice(row); + for x in s..width { + row[x * 4] = row_buf[(x - s) * 4]; + } + for x in 0..(width - s) { + row[x * 4 + 2] = row_buf[(x + s) * 4 + 2]; + } + } + } else if ca_shift < 0 && ((-ca_shift) as usize) < width { + let s = (-ca_shift) as usize; + for row in buf.chunks_exact_mut(row_stride) { + row_buf.copy_from_slice(row); + for x in 0..(width - s) { + row[x * 4] = row_buf[(x + s) * 4]; + } + for x in s..width { + row[x * 4 + 2] = row_buf[(x - s) * 4 + 2]; + } + } + } + + if glitch_env > 0.20 { + let step = (dt * 50.0) as usize; + let band_h = (height / 65).max(8); + let dx = ((18.0 * glitch_env).round() as usize).max(4) % width; + if dx > 0 { + let byte_shift = dx * 4; + for (b_idx, frac) in [0.38_f32, 0.56_f32].iter().enumerate() { + let offset = ((step * 53 + b_idx * 97) % 140) as i32 - 70; + let by0 = (((height as f32 * frac) as i32 + offset).max(0) as usize) + .min(height.saturating_sub(band_h)); + let by1 = (by0 + band_h).min(height); + let roll_right = (step + b_idx) % 2 == 0; + for y in by0..by1 { + let row = &mut buf[y * row_stride..(y + 1) * row_stride]; + if roll_right { + row.rotate_right(byte_shift); + } else { + row.rotate_left(byte_shift); + } + } + } + } + } + + if dt < 0.14 { + let boost = (18.0 * (1.0 - dt / 0.14)).round() as i32; + if boost > 0 { + let b = boost.min(255) as u8; + for px in buf.chunks_exact_mut(4) { + px[0] = px[0].saturating_add(b); + px[1] = px[1].saturating_add(b); + px[2] = px[2].saturating_add(b); } } } } #[inline(always)] -fn blend_pixel(bg: &mut [u8], fg: &[u8], opacity: f32) { - let fg_a = (fg[3] as f32 / 255.0) * opacity; - if fg_a <= 0.0 { +fn blend_pixel_u8(bg: &mut [u8], fg: &[u8]) { + let a = fg[3] as u32; + if a == 0 { return; } - if fg_a >= 1.0 { + if a == 255 { bg.copy_from_slice(fg); return; } - let inv_a = 1.0 - fg_a; - bg[0] = (fg[0] as f32 * fg_a + bg[0] as f32 * inv_a) as u8; - bg[1] = (fg[1] as f32 * fg_a + bg[1] as f32 * inv_a) as u8; - bg[2] = (fg[2] as f32 * fg_a + bg[2] as f32 * inv_a) as u8; + let inv_a = 255 - a; + bg[0] = (((fg[0] as u32 * a + bg[0] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[1] = (((fg[1] as u32 * a + bg[1] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[2] = (((fg[2] as u32 * a + bg[2] as u32 * inv_a + 128) * 257) >> 16) as u8; +} + +#[inline(always)] +fn blend_pixel_scaled(bg: &mut [u8], fg: &[u8], op_u8: u32) { + let raw_a = fg[3] as u32; + if raw_a == 0 { + return; + } + let a = ((raw_a * op_u8 + 128) * 257) >> 16; + if a == 0 { + return; + } + let inv_a = 255 - a; + bg[0] = (((fg[0] as u32 * a + bg[0] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[1] = (((fg[1] as u32 * a + bg[1] as u32 * inv_a + 128) * 257) >> 16) as u8; + bg[2] = (((fg[2] as u32 * a + bg[2] as u32 * inv_a + 128) * 257) >> 16) as u8; +} + +/// Copies `base_rgba` and paints pixels at `flat_indices` (native-endian `u32` bytes) +/// using `region_ids` (native-endian `u16` bytes) into `lut_rgba` where `use_mask[rid] != 0`. +#[pyfunction] +fn paint_regions_rs( + py: Python<'_>, + base_rgba: &[u8], + flat_indices: &[u8], + region_ids: &[u8], + lut_rgba: &[u8], + use_mask: &[u8], +) -> PyResult> { + if base_rgba.len() % 4 != 0 { + return Err(PyValueError::new_err("base_rgba length must be a multiple of 4")); + } + if flat_indices.len() % 4 != 0 { + return Err(PyValueError::new_err("flat_indices byte length must be a multiple of 4 (u32)")); + } + if region_ids.len() % 2 != 0 { + return Err(PyValueError::new_err("region_ids byte length must be a multiple of 2 (u16)")); + } + let count = flat_indices.len() / 4; + if region_ids.len() / 2 != count { + return Err(PyValueError::new_err(format!( + "flat_indices count ({count}) != region_ids count ({})", + region_ids.len() / 2 + ))); + } + let num_regions = use_mask.len(); + if lut_rgba.len() < num_regions * 4 { + return Err(PyValueError::new_err(format!( + "lut_rgba length ({}) is smaller than use_mask.len() * 4 ({})", + lut_rgba.len(), + num_regions * 4 + ))); + } + let num_pixels = base_rgba.len() / 4; + + let bytes = PyBytes::new_with(py, base_rgba.len(), |out| { + out.copy_from_slice(base_rgba); + for (idx_b, id_b) in flat_indices.chunks_exact(4).zip(region_ids.chunks_exact(2)) { + let rid = u16::from_ne_bytes([id_b[0], id_b[1]]) as usize; + if rid < num_regions && use_mask[rid] != 0 { + let pix_idx = u32::from_ne_bytes([idx_b[0], idx_b[1], idx_b[2], idx_b[3]]) as usize; + if pix_idx < num_pixels { + let dst = pix_idx * 4; + let src = rid * 4; + out[dst..dst + 4].copy_from_slice(&lut_rgba[src..src + 4]); + } + } + } + Ok(()) + })?; + Ok(bytes.unbind()) +} + +/// Fast integer Porter-Duff "over" compositing for straight RGBA buffers of equal length. +#[pyfunction] +fn alpha_composite_rs( + py: Python<'_>, + base_rgba: &[u8], + overlay_rgba: &[u8], +) -> PyResult> { + if base_rgba.len() != overlay_rgba.len() || base_rgba.len() % 4 != 0 { + return Err(PyValueError::new_err(format!( + "base_rgba ({}) and overlay_rgba ({}) must have equal length divisible by 4", + base_rgba.len(), + overlay_rgba.len() + ))); + } + + let bytes = PyBytes::new_with(py, base_rgba.len(), |out| { + out.copy_from_slice(base_rgba); + for (dst, src) in out.chunks_exact_mut(4).zip(overlay_rgba.chunks_exact(4)) { + let sa = src[3] as u32; + if sa == 0 { + continue; + } + if sa == 255 || dst[3] == 0 { + dst.copy_from_slice(src); + continue; + } + let da = dst[3] as u32; + if da == 255 { + let inv_sa = 255 - sa; + dst[0] = (((src[0] as u32 * sa + dst[0] as u32 * inv_sa + 128) * 257) >> 16) as u8; + dst[1] = (((src[1] as u32 * sa + dst[1] as u32 * inv_sa + 128) * 257) >> 16) as u8; + dst[2] = (((src[2] as u32 * sa + dst[2] as u32 * inv_sa + 128) * 257) >> 16) as u8; + // dst[3] remains 255 + } else { + let sa_255 = sa * 255; + let da_inv = da * (255 - sa); + let out_a_255 = sa_255 + da_inv; + let half = out_a_255 >> 1; + dst[0] = ((src[0] as u32 * sa_255 + dst[0] as u32 * da_inv + half) / out_a_255) as u8; + dst[1] = ((src[1] as u32 * sa_255 + dst[1] as u32 * da_inv + half) / out_a_255) as u8; + dst[2] = ((src[2] as u32 * sa_255 + dst[2] as u32 * da_inv + half) / out_a_255) as u8; + dst[3] = (((out_a_255 + 128) * 257) >> 16) as u8; + } + } + Ok(()) + })?; + Ok(bytes.unbind()) } #[pymodule] fn automap_rs(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(render_video_rs, m)?)?; + m.add_function(wrap_pyfunction!(paint_regions_rs, m)?)?; + m.add_function(wrap_pyfunction!(alpha_composite_rs, m)?)?; Ok(()) } diff --git a/docker-compose.yml b/docker-compose.yml index fa2ddde..0b2d68c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,6 +28,7 @@ services: WEB_SECRET_KEY: "${WEB_SECRET_KEY:-}" GEMINI_API_KEY: "${GEMINI_API_KEY:-}" DEEPSEEK_API_KEY: "${DEEPSEEK_API_KEY:-}" + YOUTUBE_REDIRECT_URI: "${YOUTUBE_REDIRECT_URI:-}" YTDLP_URL: http://yt-dlp-worker:8080 volumes: - automap-session:/app/instance diff --git a/example.env b/example.env index d40e20e..6da399c 100644 --- a/example.env +++ b/example.env @@ -19,3 +19,6 @@ WEB_LOGIN=deltaaa WEB_PASSWORD=deltaaa00! # Optional stable session signing secret; otherwise generated in instance/. # WEB_SECRET_KEY=replace-with-a-long-random-secret + +# Optional external HTTPS callback URL when AutoMap runs behind a reverse proxy. +# YOUTUBE_REDIRECT_URI=https://automap.example.com/api/youtube/callback diff --git a/main.py b/main.py index 1205907..bd1cdf8 100644 --- a/main.py +++ b/main.py @@ -22,6 +22,7 @@ import base64 import io +import math import os import re import threading @@ -54,12 +55,12 @@ _resolve_theme_name, _to_rgba_tuple, ) -from map.constants import europe_coords, world_coords +from map.constants import europe_coords, world_coords, _PALETTE_THEMES from cli import AVAILABLE_MODELS from map.functions import ( - _ALLOWED_MAP_TYPES, AIServiceError, configured_api_key, list_deepseek_models, - parse_ideas_content, provider_for_model, provider_key_name, slugify_prompt, - validate_temperature, + _ALLOWED_MAP_TYPES, AIServiceError, configured_api_key, generate_map_idea, + list_deepseek_models, parse_ideas_content, provider_for_model, + provider_key_name, slugify_prompt, validate_temperature, ) from flask import Flask, request, jsonify, send_file, render_template, Response, session @@ -128,6 +129,10 @@ def _available_fonts(): init_web_auth(app, dotenv_values(env) if env.is_file() else {}) +from youtube_upload import YouTubeUploads + +youtube_uploads = YouTubeUploads(app, WORKER_URL, requests) + @app.before_request def validate_api_json_body(): @@ -623,14 +628,25 @@ def generate(): command += f" --temperature {temperature_options['temperature']:g}" show_legend = bool(data.get("show_legend", False)) + highlight_extrema = bool(data.get("highlight_extrema", False)) if show_legend: command += " --legend" + if highlight_extrema: + command += " --highlight-extrema" progress_id = str(data.get("progress_id") or "").strip()[:64] if progress_id: _set_map_progress(progress_id, 1, "Querying AI model...") - style_kwargs: dict[str, object] = {"show_legend": show_legend} + style_kwargs: dict[str, object] = { + "show_legend": show_legend, + "highlight_extrema": highlight_extrema, + } + if highlight_extrema: + if "highlight_high_color" in data: + style_kwargs["highlight_high_color"] = str(data.get("highlight_high_color") or "#00e5ff") + if "highlight_low_color" in data: + style_kwargs["highlight_low_color"] = str(data.get("highlight_low_color") or "#ff2daa") if progress_id: style_kwargs["progress_callback"] = lambda stage, label: _set_map_progress(progress_id, stage, label) for style_key, kw_name in ( @@ -696,6 +712,8 @@ def generate(): "ai_cached": ai_cache_hit, } render_meta = getattr(buffer, "map_meta", None) + if isinstance(render_meta, dict) and render_meta.get("rust_warning"): + resp_payload["warning"] = render_meta["rust_warning"] ai_vals = render_meta.get("ai_answer") if isinstance(render_meta, dict) else None if isinstance(ai_vals, dict) and ai_vals: resp_payload["map_values"] = render_meta.get("raw_ai_answer", ai_vals) @@ -710,6 +728,46 @@ def generate(): return jsonify(resp_payload) +@app.route('/api/generate_idea', methods=['POST']) +def api_generate_idea(): + """Generate a map topic idea (and optionally matching parameters) using the selected AI model.""" + data = request.get_json(silent=True) or {} + try: + provider = _request_provider(data) + api_key = _request_api_key(data, provider) + except ValueError as error: + return jsonify(status='error', error=str(error)), 400 + + model = str(data.get("model") or ('deepseek-flash' if provider == 'deepseek' else AVAILABLE_MODELS[0])).strip() + if provider_for_model(model) != provider: + return jsonify(status='error', error=f"Model '{model}' does not match provider '{provider}'."), 400 + + with_params = str(data.get("with_params") or "").strip().lower() in ("1", "true", "yes", "on") or data.get("with_params") is True + + temperature = None + if "temperature" in data and str(data["temperature"]).strip() != "": + try: + temperature = validate_temperature(data["temperature"]) + except ValueError as err: + return jsonify(status='error', error=str(err)), 400 + + try: + result = generate_map_idea( + model, + api_key=api_key, + with_params=with_params, + available_themes=list(_PALETTE_THEMES.keys()), + available_fonts=_available_fonts(), + temperature=temperature, + ) + except AIServiceError as error: + return jsonify(status='error', error=str(error)), error.status_code + except Exception as exc: # noqa: BLE001 + return jsonify(status='error', error=str(exc)), 500 + + return jsonify({"status": "success", **result}), 200 + + @app.route('/api/models', methods=['POST']) def list_available_models(): """Return models available for the selected provider's API key.""" @@ -1056,6 +1114,9 @@ def api_restyle_map(): palette_theme=palette_theme, ai_answer_override=map_values, show_legend=bool(data.get("show_legend", False)), + highlight_extrema=bool(data.get("highlight_extrema", False)), + highlight_high_color=str(data.get("highlight_high_color") or "#00e5ff"), + highlight_low_color=str(data.get("highlight_low_color") or "#ff2daa"), ) except Exception as e: # noqa: BLE001 return jsonify({"status": "error", "error": str(e)}), 500 @@ -1295,6 +1356,299 @@ def _render_video_request_data(): return data +_ZOOM_REF_DIMENSIONS: dict[str, tuple[float, float]] = { + "europe": (3900.0, 4104.0), + "world": (3424.0, 2027.0), +} +_ZOOM_OUTLINE_CACHE: dict[tuple[str, str], bytes] = {} +_REVEAL_MASK_CACHE: dict[tuple[str, str, int, int], str] = {} +_ZOOM_CACHE_LOCK = threading.Lock() + + +def _zoom_country_entries( + coords: dict[str, list[tuple[int, int]]], + ref_w: float, + ref_h: float, +) -> list[dict[str, object]]: + """Build normalized (0..1) center coordinate entries for a country map.""" + return [ + { + "key": k, + "name": k.replace("_", " ").title(), + "x": round(pts[0][0] / ref_w, 4), + "y": round(pts[0][1] / ref_h, 4), + } + for k, pts in coords.items() + if pts + ] + + +def _region_mask_from_index( + map_path: Path, + coords: dict[str, list[tuple[int, int]]], + key: str, +) -> Image.Image | None: + """Extract a full-resolution L-mode binary mask using ``_region_index``.""" + import numpy as np + from map.auto_map import _load_rgba, _region_index + + if key not in coords: + return None + region_idx = list(coords.keys()).index(key) + 1 + base = _load_rgba(map_path) + w, h = base.size + flat, ids = _region_index(map_path, base, coords) + pix_mask = np.zeros(w * h, dtype=np.uint8) + pix_mask[flat[ids == region_idx]] = 255 + if not pix_mask.any(): + return None + return Image.fromarray(pix_mask.reshape((h, w)), mode="L") + + +def _world_country_floodfill_mask(seeds: list[tuple[int, int]]) -> Image.Image | None: + """Extract a full-resolution L-mode binary mask on ``world_countries_map.png``.""" + import numpy as np + from map.auto_map import _floodfill_bool_mask, _load_rgba + + if not seeds: + return None + maps_dir = BASE_DIR / "resources" / "maps" + map_path = maps_dir / "world_countries_map.png" + base = _load_rgba(map_path) + w, h = base.size + base_arr = np.asarray(base) + wc_base_alpha = base_arr[..., 3] + wc_dark = (wc_base_alpha >= 128) & (base_arr[..., :3].max(axis=2) <= 12) + wc_interior_crisp = (wc_base_alpha >= 128) & ~wc_dark + wc_interior = wc_interior_crisp + + wc_border_alpha = None + borders_path = maps_dir / "world_countries_map_blured.png" + if borders_path.is_file(): + borders = _load_rgba(borders_path) + if borders.size == (w, h): + wc_border_alpha = np.asarray(borders)[..., 3] + # Only trust blurred border alpha to bridge inland black flag bands + # when the border asset actually covers the crisp borders. + if not wc_dark.any() or float(np.mean(wc_border_alpha[wc_dark] >= 20)) >= 0.8: + wc_interior = wc_interior_crisp | ((wc_base_alpha >= 128) & (wc_border_alpha < 44)) + + max_px = int(0.08 * w * h) + filled = _floodfill_bool_mask(wc_interior, seeds, max_px) + if (filled is None or not filled.any()) and wc_border_alpha is not None: + for thr in (45, 65): + interior = (wc_base_alpha >= 128) & (wc_border_alpha < thr) + filled = _floodfill_bool_mask(interior, seeds, max_px) + if filled is not None and filled.any(): + break + if filled is None or not filled.any(): + return None + return Image.fromarray((filled.astype(np.uint8) * 255), mode="L") + + +def _extract_country_mask_image( + map_kind: str, + key: str, + *, + allow_world_continent_fallback: bool = False, +) -> Image.Image | None: + """Return a full-resolution L-mode binary mask for ``key`` on ``europe`` or ``world``.""" + from map.constants import europe_coords, world_coords + from map.world_countries_coords import world_countries_coords + + maps_dir = BASE_DIR / "resources" / "maps" + if map_kind == "europe": + return _region_mask_from_index(maps_dir / "default_map.png", europe_coords, key) + if map_kind == "world": + if key in world_countries_coords: + return _world_country_floodfill_mask(world_countries_coords[key]) + if allow_world_continent_fallback and key in world_coords: + return _region_mask_from_index(maps_dir / "world_map.png", world_coords, key) + return None + + +def _resolve_reveal_country_key( + coords: dict[str, list[tuple[int, int]]], + ref_w: float, + ref_h: float, + zoom_country_key: str, + zoom_x: float, + zoom_y: float, +) -> str: + """Resolve target country key by exact match or nearest seed within 0.18 distance.""" + candidate = str(zoom_country_key or "").strip().lower() + if candidate and candidate in coords and coords[candidate]: + return candidate + if isinstance(zoom_x, bool) or isinstance(zoom_y, bool): + return "" + try: + zx = float(zoom_x) + zy = float(zoom_y) + except (TypeError, ValueError): + return "" + if not (math.isfinite(zx) and math.isfinite(zy)): + return "" + best_key = "" + best_dist_sq = 0.18 * 0.18 + for k, pts in coords.items(): + if not pts: + continue + dx = (pts[0][0] / ref_w) - zx + dy = (pts[0][1] / ref_h) - zy + dist_sq = dx * dx + dy * dy + if dist_sq <= best_dist_sq: + best_dist_sq = dist_sq + best_key = k + return best_key + + +def _extract_country_reveal_mask( + map_w: int, + map_h: int, + zoom_country_key: str, + zoom_x: float, + zoom_y: float, +) -> str: + """Extract a country reveal mask as a base64 L-mode PNG resized to ``(map_w, map_h)``.""" + map_w = int(map_w) + map_h = int(map_h) + if map_w <= 0 or map_h <= 0: + return "" + + from map.constants import europe_coords + from map.world_countries_coords import world_countries_coords + + map_kind = "europe" if (map_w / max(1, map_h)) < 1.25 else "world" + coords = europe_coords if map_kind == "europe" else world_countries_coords + ref_w, ref_h = _ZOOM_REF_DIMENSIONS[map_kind] + + key = _resolve_reveal_country_key( + coords, ref_w, ref_h, zoom_country_key, zoom_x, zoom_y + ) + if not key: + return "" + + cache_key = (map_kind, key, map_w, map_h) + with _ZOOM_CACHE_LOCK: + cached = _REVEAL_MASK_CACHE.get(cache_key) + if cached is not None: + return cached + + mask = _extract_country_mask_image(map_kind, key, allow_world_continent_fallback=False) + if mask is None: + return "" + if mask.size != (map_w, map_h): + mask = mask.resize((map_w, map_h), Image.Resampling.BILINEAR) + if mask.mode != "L": + mask = mask.convert("L") + from PIL import ImageFilter + mask = mask.filter(ImageFilter.MaxFilter(5)).point(lambda p: 255 if p > 64 else 0) + if mask.getbbox() is None: + return "" + + buf = io.BytesIO() + mask.save(buf, format="PNG") + b64_mask = base64.b64encode(buf.getvalue()).decode("ascii") + with _ZOOM_CACHE_LOCK: + _REVEAL_MASK_CACHE[cache_key] = b64_mask + return b64_mask + + +def _parse_finite_coord(value: object, default: float) -> float: + """Parse a finite float coordinate, falling back to ``default`` when invalid.""" + if value is None or isinstance(value, bool) or value == "": + return default + try: + parsed = float(value) + except (TypeError, ValueError): + return default + return parsed if math.isfinite(parsed) else default + + +def _decode_image_size(image_data: object) -> tuple[int, int] | None: + """Decode a base64 or data-URL image payload and return its ``(width, height)``.""" + if not isinstance(image_data, str) or not image_data.strip(): + return None + raw_b64 = image_data.strip() + if "," in raw_b64 and raw_b64.lower().startswith("data:"): + _, raw_b64 = raw_b64.split(",", 1) + b64_part = "".join(raw_b64.split()) + if not b64_part: + return None + try: + decoded = base64.b64decode(b64_part, validate=True) + except (ValueError, TypeError): + return None + if not decoded: + return None + try: + with Image.open(io.BytesIO(decoded)) as opened: + return opened.size + except (UnidentifiedImageError, OSError, Image.DecompressionBombError, ValueError): + return None + + +@app.get('/api/zoom_countries') +def api_zoom_countries(): + """Return normalized (0..1) country center coordinates for Europe and World maps.""" + from map.constants import europe_coords, world_coords + from map.world_countries_coords import world_countries_coords + + europe = _zoom_country_entries(europe_coords, *_ZOOM_REF_DIMENSIONS["europe"]) + world_source = world_countries_coords if world_countries_coords else world_coords + world = _zoom_country_entries(world_source, *_ZOOM_REF_DIMENSIONS["world"]) + return jsonify({"europe": europe, "world": world}) + + +@app.get('/api/zoom_country_outline') +def api_zoom_country_outline(): + """Return a small transparent PNG highlighting the hovered country's outline.""" + from PIL import ImageChops, ImageFilter + + map_kind = str(request.args.get('map') or 'europe').strip().lower() + key = str(request.args.get('key') or '').strip().lower() + solid = str(request.args.get('solid') or '').strip() in ('1', 'true', 'yes') + if not key or map_kind not in ('europe', 'world'): + return ('', 404) + + cache_key = (map_kind, key, solid) + with _ZOOM_CACHE_LOCK: + cached = _ZOOM_OUTLINE_CACHE.get(cache_key) + if cached is not None: + resp = Response(cached, mimetype='image/png') + resp.headers['Cache-Control'] = 'public, max-age=86400' + return resp + + mask = _extract_country_mask_image( + map_kind, key, allow_world_continent_fallback=True + ) + if mask is None: + return ('', 404) + + w, h = mask.size + pw = 720 if solid else 360 + ph = max(1, int(round(h * (pw / w)))) + small_mask = mask.resize((pw, ph), Image.Resampling.BILINEAR) + if solid: + alpha = small_mask.filter(ImageFilter.MaxFilter(5)).point(lambda p: 255 if p > 64 else 0) + out = Image.new('RGBA', (pw, ph), (0, 0, 0, 255)) + else: + edge = ImageChops.subtract(small_mask.filter(ImageFilter.MaxFilter(5)), small_mask.filter(ImageFilter.MinFilter(3))) + fill_alpha = small_mask.point(lambda p: 45 if p > 128 else 0) + alpha = ImageChops.lighter(fill_alpha, edge.point(lambda p: min(255, int(p * 1.2)))) + out = Image.new('RGBA', (pw, ph), (252, 211, 77, 255)) + out.putalpha(alpha) + buf = io.BytesIO() + out.save(buf, format='PNG') + png_bytes = buf.getvalue() + with _ZOOM_CACHE_LOCK: + _ZOOM_OUTLINE_CACHE[cache_key] = png_bytes + + resp = Response(png_bytes, mimetype='image/png') + resp.headers['Cache-Control'] = 'public, max-age=86400' + return resp + + @app.route('/api/render_video', methods=['POST']) @app.route('/api/render_video/', methods=['POST']) def make_video() -> tuple[object, int]: @@ -1318,6 +1672,15 @@ def make_video() -> tuple[object, int]: if data is None: return jsonify(status='error', error='Invalid multipart payload field.'), 400 + youtube_body = None + if data.get('youtube') is not None: + if not youtube_uploads.valid_csrf(): + return jsonify(error='Invalid YouTube request token. Reload the page.'), 403 + try: + youtube_body = youtube_uploads.check_ready(data['youtube']) + except ValueError as error: + return jsonify(status='error', error=str(error)), 400 + # The frontend sends base64 strings; keep them as-is (default to empty string). map_b64 = data.get('map_file') or '' background_b64 = data.get('background_video') or '' @@ -1326,6 +1689,32 @@ def make_video() -> tuple[object, int]: codec = str(data.get('codec') or 'libx264').strip() duration = data.get('duration') + raw_country_key = data.get('zoom_country_key') + zoom_country_key = raw_country_key.strip() if isinstance(raw_country_key, str) else '' + raw_reveal = data.get('reveal_enabled', False) + reveal_enabled = ( + raw_reveal.strip().lower() in _TRUTHY + if isinstance(raw_reveal, str) + else bool(raw_reveal) + ) + raw_zoom = data.get('zoom_enabled', False) + zoom_enabled = raw_zoom.strip().lower() in _TRUTHY if isinstance(raw_zoom, str) else bool(raw_zoom) + reveal_enabled = zoom_enabled and reveal_enabled + reveal_time = data.get('reveal_time', None) + reveal_mask = '' + if reveal_enabled and map_b64: + map_size = _decode_image_size(map_b64) + if map_size is not None: + zoom_x = _parse_finite_coord(data.get('zoom_x'), 0.80) + zoom_y = _parse_finite_coord(data.get('zoom_y'), 0.35) + reveal_mask = _extract_country_reveal_mask( + map_size[0], + map_size[1], + zoom_country_key, + zoom_x, + zoom_y, + ) + try: response = requests.post( f"{WORKER_URL}/api/render_video/", @@ -1359,6 +1748,19 @@ def make_video() -> tuple[object, int]: "subscribe_text": data.get('subscribe_text', 'Subscribe!'), "subscribe_delay": data.get('subscribe_delay', 2.5), "intro_fade": data.get('intro_fade', False), + "zoom_enabled": zoom_enabled, + "zoom_x": data.get('zoom_x', 0.80), + "zoom_y": data.get('zoom_y', 0.35), + "zoom_scale": data.get('zoom_scale', 2.0), + "zoom_start": data.get('zoom_start', 1.5), + "zoom_duration": data.get('zoom_duration', 2.5), + "zoom_out_enabled": data.get('zoom_out_enabled', False), + "zoom_out_duration": data.get('zoom_out_duration', 2.0), + "zoom_country_key": zoom_country_key, + "reveal_enabled": reveal_enabled, + "reveal_time": reveal_time, + "reveal_color": str(data.get('reveal_color') or '#000000').strip(), + "reveal_mask": reveal_mask, **({'render_id': data['render_id']} if data.get('render_id') is not None else {}), }, # Video rendering (moviepy/ffmpeg) can take a while - allow more time. @@ -1375,7 +1777,15 @@ def make_video() -> tuple[object, int]: return jsonify({"status": "error", "error": "Video service returned a non-JSON response."}), 502 - # Pass the downstream payload/status straight through. + if response.ok and isinstance(payload, dict) and payload.get('status') == 'success': + path = payload.get('file_path') or payload.get('path') or payload.get('file') + if isinstance(path, str) and path: + payload['upload_token'] = youtube_uploads.render_token(path) + if youtube_body is not None: + try: + payload['youtube_job_id'] = youtube_uploads.start(payload['upload_token'], youtube_body) + except (ValueError, ImportError): + payload['youtube_error'] = 'Video rendered, but YouTube upload could not start. Check your connection and try Upload to YouTube.' return jsonify(payload), response.status_code diff --git a/map/auto_map.py b/map/auto_map.py index 39222fd..de2edf9 100644 --- a/map/auto_map.py +++ b/map/auto_map.py @@ -14,6 +14,7 @@ import ast import hashlib +import logging import os import random import io @@ -28,210 +29,11 @@ import numpy as np from PIL import Image, ImageDraw, ImageFont -from .constants import europe_coords, world_coords +from . import constants + from .functions import ai_request, load_filling, _warning as showwarning, _error as showerror from . import log -FONTS_DIR = Path(__file__).resolve().parent.parent / "resources" / "fonts" - -_AUTO_PALETTE: tuple[tuple[int, int, int, int], ...] = ( - (56, 189, 248, 255), # #38bdf8 Sky - (99, 102, 241, 255), # #6366f1 Indigo - (16, 185, 129, 255), # #10b981 Emerald - (245, 158, 11, 255), # #f59e0b Amber - (244, 63, 94, 255), # #f43f5e Rose - (168, 85, 247, 255), # #a855f7 Purple - (20, 184, 166, 255), # #14b8a6 Teal - (236, 72, 153, 255), # #ec4899 Pink - (234, 179, 8, 255), # #eab308 Gold - (249, 115, 22, 255), # #f97316 Orange -) - -_PALETTE_THEMES: dict[str, tuple[tuple[int, int, int, int], ...]] = { - "auto": _AUTO_PALETTE, - "viridis": ( - (68, 1, 84, 255), (59, 82, 139, 255), (33, 145, 140, 255), - (94, 201, 98, 255), (253, 231, 37, 255), - ), - "sunset": ( - (124, 45, 18, 255), (194, 65, 12, 255), (234, 88, 12, 255), - (245, 158, 11, 255), (253, 224, 71, 255), - ), - "ocean": ( - (12, 74, 110, 255), (3, 105, 161, 255), (2, 132, 199, 255), - (56, 189, 248, 255), (125, 211, 252, 255), - ), - "festive": ( - (220, 38, 38, 255), (22, 163, 74, 255), (234, 179, 8, 255), - (37, 99, 235, 255), (147, 51, 234, 255), - ), - "emerald": ( - (6, 78, 59, 255), (4, 120, 87, 255), (16, 185, 129, 255), - (52, 211, 153, 255), (167, 243, 208, 255), - ), - "neon": ( - (236, 72, 153, 255), (139, 92, 246, 255), (6, 182, 212, 255), - (16, 185, 129, 255), (250, 204, 21, 255), - ), - "pastel": ( - (147, 197, 253, 255), (196, 181, 253, 255), (167, 243, 208, 255), - (253, 230, 138, 255), (253, 164, 175, 255), - ), - "monochrome": ( - (51, 65, 85, 255), (71, 85, 105, 255), (100, 116, 139, 255), - (148, 163, 184, 255), (203, 213, 225, 255), - ), - "heatmap": ( - (37, 99, 235, 255), (16, 185, 129, 255), (245, 158, 11, 255), - (239, 68, 68, 255), (185, 28, 28, 255), - ), - "emerald_gold": ( - (244, 63, 94, 255), (245, 158, 11, 255), (234, 179, 8, 255), - (16, 185, 129, 255), (5, 150, 105, 255), - ), - "oceanic": ( - (56, 189, 248, 255), (14, 165, 233, 255), (37, 99, 235, 255), - (99, 102, 241, 255), (139, 92, 246, 255), - ), - "categorical": _AUTO_PALETTE + ( - (14, 165, 233, 255), (132, 204, 22, 255), - ), - "greens": ( - (187, 247, 208, 255), (134, 239, 172, 255), (74, 222, 128, 255), - (22, 163, 74, 255), (20, 83, 45, 255), - ), - "blues": ( - (191, 219, 254, 255), (147, 197, 253, 255), (96, 165, 250, 255), - (37, 99, 235, 255), (30, 58, 138, 255), - ), - "reds": ( - (254, 202, 202, 255), (252, 165, 165, 255), (248, 113, 113, 255), - (220, 38, 38, 255), (127, 29, 29, 255), - ), - "oranges": ( - (254, 215, 170, 255), (253, 186, 116, 255), (251, 146, 60, 255), - (234, 88, 12, 255), (124, 45, 18, 255), - ), - "yellows": ( - (254, 240, 138, 255), (253, 224, 71, 255), (250, 204, 21, 255), - (202, 138, 4, 255), (133, 77, 14, 255), - ), - "purples": ( - (233, 213, 255, 255), (216, 180, 254, 255), (192, 132, 252, 255), - (147, 51, 234, 255), (88, 28, 135, 255), - ), - "teals": ( - (153, 246, 228, 255), (94, 234, 212, 255), (45, 212, 191, 255), - (13, 148, 136, 255), (19, 78, 74, 255), - ), - "pinks": ( - (251, 207, 232, 255), (249, 168, 212, 255), (244, 114, 182, 255), - (219, 39, 119, 255), (131, 24, 67, 255), - ), - "earth_tones": ( - (231, 229, 176, 255), (194, 178, 128, 255), (163, 137, 87, 255), - (120, 113, 62, 255), (75, 85, 45, 255), - ), -} - -_SEMANTIC_COLORS: dict[str, tuple[int, int, int, int]] = { - "yes": (46, 204, 113, 255), "так": (46, 204, 113, 255), "true": (46, 204, 113, 255), - "no": (231, 76, 60, 255), "ні": (231, 76, 60, 255), "false": (231, 76, 60, 255), - "tea": (16, 185, 129, 255), "coffee": (245, 158, 11, 255), "coffe": (245, 158, 11, 255), - "beer": (234, 179, 8, 255), "wine": (225, 29, 72, 255), -} - -_DEFAULT_UI_TXT_KEYS = {"yes", "no", "tea", "coffee"} -_DEFAULT_UI_NUM_BOUNDS = {(0, 100), (100, 1000), (1000, 10000), (10000, 100000000)} -_RELIEF_ALPHA_LUT: list[int] = [int(p * 0.3) for p in range(256)] - -_EUROPE_LABEL_SIZES: dict[str, int] = { - **{k: 70 for k in ( - "cyprus", "kosovo", "montenegro", "slovenia", "latvia", "lithuania", - "estonia", "switzerland", "austria", "slovakia", "hungary", "croatia", - "netherlands", "belgium", "czechia", "moldova", "bosnia_and_herzegovina", - "serbia", "bulgaria", "albania", "greece", "ireland", "iceland", - "norway", "finland", "sweden", "denmark", "portugal", - )}, - **{k: 100 for k in ("sweden", "norway", "finland")}, - **{k: 125 for k in ("north_macedonia", "bosnia")}, - **{k: 175 for k in ( - "ukraine", "poland", "france", "spain", "turkey", - "romania", "italy", "belarus", "united_kingdom", "germany", - )}, - **{k: 250 for k in ("russia", "usa")}, -} - -_WORLD_LABEL_SIZES: dict[str, int] = { - "asia": 200, - "africa": 100, - "europe": 110, - "australia": 50, - "south_america": 100, - "north_america": 120, -} - -# Map types whose regions are painted from the cached region-ID map. -# Flag-filled maps (``flag``, ``world_countries``) keep their underlying flag artwork. -_PAINTED_MAP_TYPES: frozenset[str] = frozenset({"default", "world"}) - -# Smallest base label size (before the global size modifier) still drawn on the -# world countries map; smaller countries stay unlabeled to keep the map readable. -_WORLD_COUNTRIES_MIN_LABEL = 1 - -# Common alternative AI spellings mapped to canonical snake_case country keys. -# Applied only when the alias target exists in the coordinates dictionary. -_WORLD_COUNTRY_ALIASES: dict[str, tuple[str, ...]] = { - "usa": ("united_states", "united_states_of_america"), - "us": ("united_states", "united_states_of_america"), - "united_states_of_america": ("united_states",), - "america": ("united_states", "united_states_of_america"), - "uk": ("united_kingdom",), - "great_britain": ("united_kingdom",), - "britain": ("united_kingdom",), - "russian_federation": ("russia",), - "czech_republic": ("czechia",), - "turkiye": ("turkey",), - "ivory_coast": ("cote_d_ivoire", "cote_divoire"), - "cote_d_ivoire": ("ivory_coast",), - "cote_divoire": ("ivory_coast", "cote_d_ivoire"), - "drc": ("democratic_republic_of_the_congo", "dr_congo"), - "dr_congo": ("democratic_republic_of_the_congo",), - "congo_kinshasa": ("democratic_republic_of_the_congo", "dr_congo"), - "democratic_republic_of_congo": ("democratic_republic_of_the_congo", "dr_congo"), - "congo_brazzaville": ("republic_of_the_congo", "congo"), - "republic_of_congo": ("republic_of_the_congo", "congo"), - "south_korea": ("korea_south", "republic_of_korea"), - "korea": ("south_korea",), - "korea_south": ("south_korea",), - "republic_of_korea": ("south_korea",), - "north_korea": ("korea_north", "dprk"), - "korea_north": ("north_korea",), - "dprk": ("north_korea",), - "burma": ("myanmar",), - "swaziland": ("eswatini",), - "eswatini": ("swaziland",), - "macedonia": ("north_macedonia",), - "holland": ("netherlands",), - "the_netherlands": ("netherlands",), - "uae": ("united_arab_emirates",), - "east_timor": ("timor_leste",), - "timor_leste": ("east_timor",), - "cabo_verde": ("cape_verde",), - "cape_verde": ("cabo_verde",), - "vatican_city": ("vatican",), - "bosnia": ("bosnia_and_herzegovina",), - "the_gambia": ("gambia",), - "the_bahamas": ("bahamas",), - "united_republic_of_tanzania": ("tanzania",), - "republic_of_serbia": ("serbia",), - "state_of_palestine": ("palestine",), - "brunei_darussalam": ("brunei",), - "viet_nam": ("vietnam",), - "lao_pdr": ("laos",), -} - - def _country_key(name: object) -> str: """Normalize a country name to snake_case ASCII ("Côte d'Ivoire" -> "cote_d_ivoire").""" text = unicodedata.normalize("NFKD", str(name)).encode("ascii", "ignore").decode("ascii") @@ -244,7 +46,7 @@ def _world_countries_answer_norm(ai_answer: dict[str, object], keys: object) -> for k, v in (ai_answer or {}).items(): norm.setdefault(_country_key(k), v) known = {_country_key(k) for k in keys} - for alias, targets in _WORLD_COUNTRY_ALIASES.items(): + for alias, targets in constants._WORLD_COUNTRY_ALIASES.items(): if alias not in norm: continue for target in targets: @@ -310,7 +112,7 @@ def _prepared_relief(path: Path, size: tuple[int, int]) -> Image.Image: relief = _load_rgba(path) relief = relief.resize(size) if relief.size != tuple(size) else relief.copy() _, _, _, a = relief.split() - relief.putalpha(a.point(_RELIEF_ALPHA_LUT)) + relief.putalpha(a.point(constants._RELIEF_ALPHA_LUT)) if ckey is not None: with _CACHE_LOCK: _RELIEF_CACHE[ckey] = relief @@ -409,6 +211,51 @@ def _region_index(map_path: Path, base: Image.Image, coords: dict) -> tuple[np.n return result +_RUST_WARNED = False +_LAST_RUST_WARNING: str | None = None + + +def _record_rust_warning(msg: str) -> None: + global _RUST_WARNED, _LAST_RUST_WARNING + _LAST_RUST_WARNING = msg + if not _RUST_WARNED: + _RUST_WARNED = True + log.warning(msg) + logging.warning(msg) + + +def _get_automap_rs(): + """Return the native ``automap_rs`` module when available, else ``None``.""" + global _LAST_RUST_WARNING + try: + import automap_rs + if hasattr(automap_rs, "paint_regions_rs") and hasattr(automap_rs, "alpha_composite_rs"): + _LAST_RUST_WARNING = None + return automap_rs + raise ImportError("automap_rs map functions not built") + except Exception as exc: + _record_rust_warning( + f"Rust map acceleration unavailable ({type(exc).__name__}: {exc}); falling back to Python/PIL." + ) + return None + + +def _alpha_composite(base: Image.Image, overlay: Image.Image) -> Image.Image: + """Alpha-composite ``overlay`` over ``base`` using Rust when available.""" + rs = _get_automap_rs() + if rs is not None and base.size == overlay.size: + try: + base_rgba = base if base.mode == "RGBA" else base.convert("RGBA") + overlay_rgba = overlay if overlay.mode == "RGBA" else overlay.convert("RGBA") + out_bytes = rs.alpha_composite_rs(base_rgba.tobytes(), overlay_rgba.tobytes()) + return Image.frombytes("RGBA", base.size, out_bytes) + except Exception as exc: + _record_rust_warning( + f"Rust alpha_composite_rs failed ({type(exc).__name__}: {exc}); falling back to PIL." + ) + return Image.alpha_composite(base, overlay) + + def _paint_regions(img: Image.Image, flat: np.ndarray, ids: np.ndarray, colors: dict[int, tuple[int, int, int, int]]) -> Image.Image: """Return a copy of ``img`` with region ``i`` painted ``colors[i]``.""" @@ -418,13 +265,29 @@ def _paint_regions(img: Image.Image, flat: np.ndarray, ids: np.ndarray, if ids.size: n = max(n, int(ids.max()) + 1) lut = np.zeros((n, 4), dtype=np.uint8) - use = np.zeros(n, dtype=bool) + use = np.zeros(n, dtype=np.uint8) for i, c in colors.items(): lut[i] = c - use[i] = True + use[i] = 1 + rs = _get_automap_rs() + if rs is not None: + try: + base_rgba = img if img.mode == "RGBA" else img.convert("RGBA") + out_bytes = rs.paint_regions_rs( + base_rgba.tobytes(), + np.ascontiguousarray(flat, dtype=np.uint32).tobytes(), + np.ascontiguousarray(ids, dtype=np.uint16).tobytes(), + lut.tobytes(), + use.tobytes(), + ) + return Image.frombytes("RGBA", img.size, out_bytes) + except Exception as exc: + _record_rust_warning( + f"Rust paint_regions_rs failed ({type(exc).__name__}: {exc}); falling back to NumPy." + ) arr = np.array(img, dtype=np.uint8) pix = arr.reshape(-1, 4) - sel = use[ids] + sel = use.astype(bool, copy=False)[ids] pix[flat[sel]] = lut[ids[sel]] return Image.fromarray(arr) @@ -432,7 +295,7 @@ def _paint_regions(img: Image.Image, flat: np.ndarray, ids: np.ndarray, def _resolve_theme_name(palette_theme: str = "auto", prompt: str = "", mode: str = "text") -> str: """Pick a palette theme name from an explicit choice, prompt keywords, or mode.""" theme = (palette_theme or "auto").strip().lower() - if theme in _PALETTE_THEMES and theme != "auto": + if theme in constants._PALETTE_THEMES and theme != "auto": return theme low = (prompt or "").lower() if any(w in low for w in ("nicholas", "christmas", "santa", "holiday", "xmas")): @@ -596,7 +459,7 @@ def _auto_fill_from_ai( auto_txt: dict[str, tuple[int, int, int, int]] = {} auto_num: dict[tuple[float, float], tuple[int, int, int, int]] = {} resolved = _resolve_theme_name(palette_theme, prompt=prompt, mode=mode) - palette = _PALETTE_THEMES.get(resolved, _AUTO_PALETTE) + palette = constants._PALETTE_THEMES.get(resolved, constants._AUTO_PALETTE) use_semantic = (palette_theme or "auto").strip().lower() == "auto" if mode == "number": @@ -645,7 +508,7 @@ def _auto_fill_from_ai( b_idx = sum(1 for t in thresholds if num > t) auto_txt[lbl] = palette[b_idx % len(palette)] else: - auto_txt.setdefault(lbl, _SEMANTIC_COLORS.get(lbl.lower(), palette[-1])) + auto_txt.setdefault(lbl, constants._SEMANTIC_COLORS.get(lbl.lower(), palette[-1])) else: canonical: dict[str, str] = {} for lbl in labels: @@ -653,8 +516,8 @@ def _auto_fill_from_ai( idx = 0 for low_lbl, _ in Counter(lbl.lower() for lbl in labels).most_common(): orig = canonical[low_lbl] - if use_semantic and low_lbl in _SEMANTIC_COLORS: - auto_txt[orig] = _SEMANTIC_COLORS[low_lbl] + if use_semantic and low_lbl in constants._SEMANTIC_COLORS: + auto_txt[orig] = constants._SEMANTIC_COLORS[low_lbl] else: auto_txt[orig] = palette[idx % len(palette)] idx += 1 @@ -783,6 +646,156 @@ def _draw_legend_overlay( return layer +_RESERVED_HIGHLIGHT_COLORS: tuple[tuple[int, int, int], ...] = ( + (0, 229, 255), # Electric cyan (highest) + (255, 45, 170), # Neon magenta (lowest) +) + + +def _random_region_color() -> tuple[int, int, int, int]: + """Pick a random bright RGBA color that stays distinct from reserved highlight colors.""" + for _ in range(16): + c = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255)) + if all(sum((c[i] - r[i]) ** 2 for i in range(3)) >= 90 ** 2 for r in _RESERVED_HIGHLIGHT_COLORS): + return (*c, 255) + return (120, 180, 120, 255) + + +def _floodfill_bool_mask(interior: np.ndarray, seeds: list, max_pixels: int) -> np.ndarray | None: + """4-connected BFS flood fill on a boolean ``(H, W)`` interior mask, aborting if it exceeds ``max_pixels``.""" + from collections import deque + + h, w = interior.shape + visited = np.zeros((h, w), dtype=bool) + q: deque[tuple[int, int]] = deque() + for coord in seeds: + cx, cy = int(round(coord[0])), int(round(coord[1])) + seed = None + for dy in (0, -2, 2, -4, 4, -8, 8): + for dx in (0, -2, 2, -4, 4, -8, 8): + nx, ny = cx + dx, cy + dy + if 0 <= nx < w and 0 <= ny < h and interior[ny, nx]: + seed = (nx, ny) + break + if seed is not None: + break + if seed is not None and not visited[seed[1], seed[0]]: + visited[seed[1], seed[0]] = True + q.append(seed) + + if not q: + return None + + count = 0 + while q: + x, y = q.popleft() + count += 1 + if count > max_pixels: + return None + if x > 0 and interior[y, x - 1] and not visited[y, x - 1]: + visited[y, x - 1] = True + q.append((x - 1, y)) + if x + 1 < w and interior[y, x + 1] and not visited[y, x + 1]: + visited[y, x + 1] = True + q.append((x + 1, y)) + if y > 0 and interior[y - 1, x] and not visited[y - 1, x]: + visited[y - 1, x] = True + q.append((x, y - 1)) + if y + 1 < h and interior[y + 1, x] and not visited[y + 1, x]: + visited[y + 1, x] = True + q.append((x, y + 1)) + + return visited + + +def _build_extrema_highlight_layer( + size: tuple[int, int], + highest_idx: int | None, + lowest_idx: int | None, + map_type: str, + dict_: dict, + flat: np.ndarray | None, + ids: np.ndarray | None, + borders: Image.Image | None, + base_map: Image.Image | None = None, + high_rgb: tuple[int, int, int] = _RESERVED_HIGHLIGHT_COLORS[0], + low_rgb: tuple[int, int, int] = _RESERVED_HIGHLIGHT_COLORS[1], +) -> Image.Image | None: + """Create a soft tint + inner glow highlight layer for the highest and lowest regions.""" + from PIL import ImageChops, ImageFilter + + targets: list[tuple[int, tuple[int, int, int]]] = [] + if highest_idx is not None: + targets.append((highest_idx, high_rgb)) + if lowest_idx is not None and lowest_idx != highest_idx: + targets.append((lowest_idx, low_rgb)) + if not targets: + return None + + w, h = size + layer = Image.new("RGBA", size, (0, 0, 0, 0)) + coords_list = list(dict_.values()) + + if map_type == "flag" and (flat is None or ids is None): + mask_path = Path(__file__).parent.parent / "resources" / "maps" / "default_map.png" + flat, ids = _region_index(mask_path, _load_rgba(mask_path), dict_) + + inner_size = 37 if w >= 3000 else 21 + outer_size = 25 if w >= 3000 else 15 + wc_interior_crisp: np.ndarray | None = None + wc_base_alpha: np.ndarray | None = None + wc_border_alpha: np.ndarray | None = None + if map_type == "world_countries" and base_map is not None: + base_arr = np.asarray(base_map) + wc_base_alpha = base_arr[..., 3] + # Crisp dark country borders on world_countries_map.png cleanly separate adjacent nations. + wc_interior_crisp = (wc_base_alpha >= 128) & (base_arr[..., :3].max(axis=2) > 12) + if borders is not None: + wc_border_alpha = np.asarray(borders)[..., 3] + + for region_idx, rgb in targets: + mask: Image.Image | None = None + if flat is not None and ids is not None: + pix_mask = np.zeros(w * h, dtype=np.uint8) + pix_mask[flat[ids == region_idx]] = 255 + if pix_mask.any(): + mask = Image.fromarray(pix_mask.reshape((h, w)), mode="L") + elif wc_interior_crisp is not None and 1 <= region_idx <= len(coords_list): + max_px = int(0.08 * w * h) + filled = _floodfill_bool_mask(wc_interior_crisp, coords_list[region_idx - 1], max_px) + if (filled is None or not filled.any()) and wc_base_alpha is not None and wc_border_alpha is not None: + for thr in (45, 65): + interior = (wc_base_alpha >= 128) & (wc_border_alpha < thr) + filled = _floodfill_bool_mask(interior, coords_list[region_idx - 1], max_px) + if filled is not None and filled.any(): + break + if filled is not None and filled.any(): + mask = Image.fromarray((filled.astype(np.uint8) * 255), mode="L") + + if mask is None: + continue + + # Downscale the binary mask before morphological filters so MinFilter/MaxFilter + # run in milliseconds instead of O(k^2) over 16M full-res pixels. + ds = 4 if w >= 2400 else 2 + small_size = (max(1, w // ds), max(1, h // ds)) + small_mask = mask.resize(small_size, Image.Resampling.BILINEAR) + small_inner = small_mask.filter(ImageFilter.MinFilter(9)) + small_outer = small_mask.filter(ImageFilter.MaxFilter(7)) + inner_ring = ImageChops.subtract(small_mask, small_inner).filter(ImageFilter.GaussianBlur(2)) + outer_halo = ImageChops.subtract(small_outer, small_mask).filter(ImageFilter.GaussianBlur(2.5)) + glow_small = ImageChops.lighter(inner_ring, outer_halo.point(lambda p: min(255, int(p * 0.95)))) + glow_alpha = glow_small.resize((w, h), Image.Resampling.BILINEAR) + tint_alpha = mask.point(lambda p: 95 if p else 0) + combined_alpha = ImageChops.lighter(tint_alpha, glow_alpha) + + overlay = Image.new("RGBA", size, (*rgb, 255)) + overlay.putalpha(combined_alpha) + layer = Image.alpha_composite(layer, overlay) + + return layer + + def auto_map(prompt: str, mode: str, map_type: str, size_mod: int, optional_feature: str, model: str, font_name: str, show_result: bool = True, io_res = False, api_key: str | None = None, @@ -797,6 +810,9 @@ def auto_map(prompt: str, mode: str, map_type: str, size_mod: int, web_search: bool = False, max_search_requests: int = 5, show_legend: bool = False, + highlight_extrema: bool = False, + highlight_high_color: str = "#00e5ff", + highlight_low_color: str = "#ff2daa", progress_callback=None): """Create a map from an AI query and save it as ``result.png``. @@ -819,7 +835,7 @@ def auto_map(prompt: str, mode: str, map_type: str, size_mod: int, def get_font(size): key = (font_name, size) if key not in _font_cache: - font_path = FONTS_DIR / font_name + font_path = constants.FONTS_DIR / font_name _font_cache[key] = ImageFont.truetype(str(font_path), size) return _font_cache[key] @@ -896,13 +912,13 @@ def _parse_optional_features(value: object) -> set[str]: wc_label_sizes: dict[str, int] = {} if map_type == "default": path = Path(__file__).parent.parent / "./resources/maps/default_map.png" - dict_ = europe_coords + dict_ = constants.europe_coords elif map_type == 'flag': path = Path(__file__).parent.parent / "./resources/maps/flag_map.png" - dict_ = europe_coords + dict_ = constants.europe_coords elif map_type == 'world': path = Path(__file__).parent.parent / "./resources/maps/world_map.png" - dict_ = world_coords + dict_ = constants.world_coords elif map_type == 'world_countries': path = Path(__file__).parent.parent / "./resources/maps/world_countries_map.png" dict_, wc_label_sizes = _load_world_countries() @@ -958,7 +974,7 @@ def _report(stage: int, label: str) -> None: if mode == "text": merged_txt = dict(auto_txt) req_keys_low = {k.strip().lower() for k in req_txt} - if req_txt and (not theme_requested or req_keys_low != _DEFAULT_UI_TXT_KEYS): + if req_txt and (not theme_requested or req_keys_low != constants._DEFAULT_UI_TXT_KEYS): ci_to_orig = {k.strip().lower(): k for k in merged_txt} for rk, rv in req_txt.items(): short_rk = str(_format_short_number(rk)).strip() if has_short_form else rk @@ -967,7 +983,7 @@ def _report(stage: int, label: str) -> None: filling_txt = merged_txt filling_txt_ci = {str(k).strip().lower(): v for k, v in filling_txt.items()} elif mode == "number": - if req_num and set(req_num.keys()) != _DEFAULT_UI_NUM_BOUNDS and not theme_requested: + if req_num and set(req_num.keys()) != constants._DEFAULT_UI_NUM_BOUNDS and not theme_requested: filling_num = dict(req_num) elif auto_num: filling_num = dict(auto_num) @@ -1044,6 +1060,7 @@ def _report(stage: int, label: str) -> None: raw_ai_answer_norm["australia"] = raw_ai_answer_norm["oceania"] region_colors: dict[int, tuple[int, int, int, int]] = {} + numeric_region_values: dict[int, float] = {} for index, (name, points) in enumerate(dict_.items(), start=1): name_key = ( @@ -1055,13 +1072,15 @@ def _report(stage: int, label: str) -> None: if mode == 'number': try: info = ai_answer_norm[name_key] - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() num_value = _parse_short_number(info) raw_num_value = _parse_short_number(raw_ai_answer_norm.get(name_key)) if num_value is None: log.warning(f"Non-numeric value for {name}: {info!r}; using random color") if num_value is not None: + if highlight_extrema: + numeric_region_values[index] = float(raw_num_value if raw_num_value is not None else num_value) # Pick the colour of the first matching range. Ranges are # treated as (low < value <= high) per the docs. matched_bounds = None @@ -1084,7 +1103,7 @@ def _report(stage: int, label: str) -> None: except KeyError as e: info = "" log.warning(f"No data / color for {e}; using random color") - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() random_colors[name] = color elif mode == 'text': @@ -1099,16 +1118,16 @@ def _report(stage: int, label: str) -> None: # so "Yes", "yes" and " yes " all find the same colour. color = filling_txt_ci[info.lower()] except KeyError: - if map_type in _PAINTED_MAP_TYPES: + if map_type in constants._PAINTED_MAP_TYPES: log.info(f"No filling color for '{info}'; using random") # Repeated answers share a color so categories remain recognizable. try: color = random_colors[info] except KeyError: - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() random_colors[info] = color else: - color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255) + color = _random_region_color() used_txt_rules.setdefault(info, color) else: showerror("Error", f"Unknown mode: {mode}") @@ -1119,7 +1138,7 @@ def _report(stage: int, label: str) -> None: # Flag maps retain their original artwork. Other maps use every seed point # to fill disconnected pieces of a region, such as islands. # Painting is applied after the loop from a cached region-ID map. - if map_type in _PAINTED_MAP_TYPES: + if map_type in constants._PAINTED_MAP_TYPES: region_colors[index] = tuple(int(c) for c in color) if not points: @@ -1137,7 +1156,7 @@ def _report(stage: int, label: str) -> None: elif len(info) >= 2: x -= 30 - size = _EUROPE_LABEL_SIZES.get(name, 125) + size = constants._EUROPE_LABEL_SIZES.get(name, 125) if name in ('russia', 'usa'): y -= 10 elif name in ('north_macedonia', 'bosnia'): @@ -1162,7 +1181,7 @@ def _report(stage: int, label: str) -> None: stroke_fill=label_stroke_fill) elif map_type == 'world': # text size for World map - size = _WORLD_LABEL_SIZES.get(name, 100) + size = constants._WORLD_LABEL_SIZES.get(name, 100) if label_auto_fit and len(info) >= 6: size = max(40, int(size * max(0.55, 5.0 / len(info)))) @@ -1180,7 +1199,7 @@ def _report(stage: int, label: str) -> None: base_size = wc_label_sizes.get(name) if base_size is None: base_size = wc_label_sizes.get(name_key, 0) - if base_size and base_size >= _WORLD_COUNTRIES_MIN_LABEL: + if base_size and base_size >= constants._WORLD_COUNTRIES_MIN_LABEL: size = base_size if label_auto_fit and len(info) >= 6: size = max(14, int(size * max(0.55, 5.0 / len(info)))) @@ -1227,10 +1246,16 @@ def _report(stage: int, label: str) -> None: }, } - if map_type in _PAINTED_MAP_TYPES: + flat = ids = None + if map_type in constants._PAINTED_MAP_TYPES: flat, ids = _region_index(path, img, dict_) img = _paint_regions(img, flat, ids, region_colors) + highest_idx = lowest_idx = None + if highlight_extrema and mode == "number" and numeric_region_values: + highest_idx = max(numeric_region_values, key=numeric_region_values.get) + lowest_idx = min(numeric_region_values, key=numeric_region_values.get) + # adding relief map _report(3, "Adding relief, borders & overlays...") log.step("Compositing layers") @@ -1246,17 +1271,26 @@ def _report(stage: int, label: str) -> None: # Relief is resized and its opacity reduced once per process. maps_dir = Path(__file__).parent.parent / "resources" / "maps" relief = _prepared_relief(maps_dir / relief_name, img.size) - result = Image.alpha_composite(img, relief) + result = _alpha_composite(img, relief) # Restore borders above the relief, then put readable labels on top. borders = _load_rgba(maps_dir / borders_name) - result = Image.alpha_composite(result, borders) - result = Image.alpha_composite(result, text_layer) + if highest_idx is not None: + high_rgb = _hex_to_rgba(highlight_high_color, (*_RESERVED_HIGHLIGHT_COLORS[0], 255))[:3] + low_rgb = _hex_to_rgba(highlight_low_color, (*_RESERVED_HIGHLIGHT_COLORS[1], 255))[:3] + hl_layer = _build_extrema_highlight_layer( + img.size, highest_idx, lowest_idx, map_type, dict_, flat, ids, borders, + base_map=img, high_rgb=high_rgb, low_rgb=low_rgb, + ) + if hl_layer is not None: + result = _alpha_composite(result, hl_layer) + result = _alpha_composite(result, borders) + result = _alpha_composite(result, text_layer) if has_most_least and map_type != "world" and most_least is not None: - result = Image.alpha_composite(result, most_least) + result = _alpha_composite(result, most_least) else: - result = Image.alpha_composite(img, text_layer) + result = _alpha_composite(img, text_layer) if show_legend: if mode == "number": @@ -1284,15 +1318,17 @@ def _report(stage: int, label: str) -> None: has_ml, ) if legend_layer is not None: - result = Image.alpha_composite(result, legend_layer) + result = _alpha_composite(result, legend_layer) _report(4, "Encoding final PNG...") + if _LAST_RUST_WARNING: + render_meta["rust_warning"] = _LAST_RUST_WARNING if io_res: # Return an in-memory PNG for the web API instead of writing result.png. buffer = io.BytesIO() - result.save(buffer, format='PNG') + result.save(buffer, format='PNG', compress_level=1) # Consumers should be able to read the PNG from its first byte. buffer.seek(0) buffer.map_meta = render_meta @@ -1302,7 +1338,7 @@ def _report(stage: int, label: str) -> None: out_path = Path(__file__).parent.parent / "result.png" log.step(f"Saving result to {out_path}") - result.save(out_path) + result.save(out_path, compress_level=1) if show_result: result.show("Map") diff --git a/map/constants.py b/map/constants.py index a9942a8..f1cc378 100644 --- a/map/constants.py +++ b/map/constants.py @@ -14,6 +14,9 @@ # Pixel coordinates in the bundled map artwork, rather than geographic coordinates. # The first point anchors the label; additional points fill disconnected land areas. +from pathlib import Path + + europe_coords = { "ukraine": [(3144, 2440), (3565, 2805)], "poland": [(2370, 2338)], @@ -130,3 +133,201 @@ "africa": }""" +FONTS_DIR = Path(__file__).resolve().parent.parent / "resources" / "fonts" + +_AUTO_PALETTE: tuple[tuple[int, int, int, int], ...] = ( + (56, 189, 248, 255), # #38bdf8 Sky + (99, 102, 241, 255), # #6366f1 Indigo + (16, 185, 129, 255), # #10b981 Emerald + (245, 158, 11, 255), # #f59e0b Amber + (244, 63, 94, 255), # #f43f5e Rose + (168, 85, 247, 255), # #a855f7 Purple + (20, 184, 166, 255), # #14b8a6 Teal + (236, 72, 153, 255), # #ec4899 Pink + (234, 179, 8, 255), # #eab308 Gold + (249, 115, 22, 255), # #f97316 Orange +) + +_PALETTE_THEMES: dict[str, tuple[tuple[int, int, int, int], ...]] = { + "auto": _AUTO_PALETTE, + "viridis": ( + (68, 1, 84, 255), (59, 82, 139, 255), (33, 145, 140, 255), + (94, 201, 98, 255), (253, 231, 37, 255), + ), + "sunset": ( + (124, 45, 18, 255), (194, 65, 12, 255), (234, 88, 12, 255), + (245, 158, 11, 255), (253, 224, 71, 255), + ), + "ocean": ( + (12, 74, 110, 255), (3, 105, 161, 255), (2, 132, 199, 255), + (56, 189, 248, 255), (125, 211, 252, 255), + ), + "festive": ( + (220, 38, 38, 255), (22, 163, 74, 255), (234, 179, 8, 255), + (37, 99, 235, 255), (147, 51, 234, 255), + ), + "emerald": ( + (6, 78, 59, 255), (4, 120, 87, 255), (16, 185, 129, 255), + (52, 211, 153, 255), (167, 243, 208, 255), + ), + "neon": ( + (236, 72, 153, 255), (139, 92, 246, 255), (6, 182, 212, 255), + (16, 185, 129, 255), (250, 204, 21, 255), + ), + "pastel": ( + (147, 197, 253, 255), (196, 181, 253, 255), (167, 243, 208, 255), + (253, 230, 138, 255), (253, 164, 175, 255), + ), + "monochrome": ( + (51, 65, 85, 255), (71, 85, 105, 255), (100, 116, 139, 255), + (148, 163, 184, 255), (203, 213, 225, 255), + ), + "heatmap": ( + (37, 99, 235, 255), (16, 185, 129, 255), (245, 158, 11, 255), + (239, 68, 68, 255), (185, 28, 28, 255), + ), + "emerald_gold": ( + (244, 63, 94, 255), (245, 158, 11, 255), (234, 179, 8, 255), + (16, 185, 129, 255), (5, 150, 105, 255), + ), + "oceanic": ( + (56, 189, 248, 255), (14, 165, 233, 255), (37, 99, 235, 255), + (99, 102, 241, 255), (139, 92, 246, 255), + ), + "categorical": _AUTO_PALETTE + ( + (14, 165, 233, 255), (132, 204, 22, 255), + ), + "greens": ( + (187, 247, 208, 255), (134, 239, 172, 255), (74, 222, 128, 255), + (22, 163, 74, 255), (20, 83, 45, 255), + ), + "blues": ( + (191, 219, 254, 255), (147, 197, 253, 255), (96, 165, 250, 255), + (37, 99, 235, 255), (30, 58, 138, 255), + ), + "reds": ( + (254, 202, 202, 255), (252, 165, 165, 255), (248, 113, 113, 255), + (220, 38, 38, 255), (127, 29, 29, 255), + ), + "oranges": ( + (254, 215, 170, 255), (253, 186, 116, 255), (251, 146, 60, 255), + (234, 88, 12, 255), (124, 45, 18, 255), + ), + "yellows": ( + (254, 240, 138, 255), (253, 224, 71, 255), (250, 204, 21, 255), + (202, 138, 4, 255), (133, 77, 14, 255), + ), + "purples": ( + (233, 213, 255, 255), (216, 180, 254, 255), (192, 132, 252, 255), + (147, 51, 234, 255), (88, 28, 135, 255), + ), + "teals": ( + (153, 246, 228, 255), (94, 234, 212, 255), (45, 212, 191, 255), + (13, 148, 136, 255), (19, 78, 74, 255), + ), + "pinks": ( + (251, 207, 232, 255), (249, 168, 212, 255), (244, 114, 182, 255), + (219, 39, 119, 255), (131, 24, 67, 255), + ), + "earth_tones": ( + (231, 229, 176, 255), (194, 178, 128, 255), (163, 137, 87, 255), + (120, 113, 62, 255), (75, 85, 45, 255), + ), +} + +_SEMANTIC_COLORS: dict[str, tuple[int, int, int, int]] = { + "yes": (46, 204, 113, 255), "так": (46, 204, 113, 255), "true": (46, 204, 113, 255), + "no": (231, 76, 60, 255), "ні": (231, 76, 60, 255), "false": (231, 76, 60, 255), + "tea": (16, 185, 129, 255), "coffee": (245, 158, 11, 255), "coffe": (245, 158, 11, 255), + "beer": (234, 179, 8, 255), "wine": (225, 29, 72, 255), +} + +_DEFAULT_UI_TXT_KEYS = {"yes", "no", "tea", "coffee"} +_DEFAULT_UI_NUM_BOUNDS = {(0, 100), (100, 1000), (1000, 10000), (10000, 100000000)} +_RELIEF_ALPHA_LUT: list[int] = [int(p * 0.3) for p in range(256)] + +_EUROPE_LABEL_SIZES: dict[str, int] = { + **{k: 70 for k in ( + "cyprus", "kosovo", "montenegro", "slovenia", "latvia", "lithuania", + "estonia", "switzerland", "austria", "slovakia", "hungary", "croatia", + "netherlands", "belgium", "czechia", "moldova", "bosnia_and_herzegovina", + "serbia", "bulgaria", "albania", "greece", "ireland", "iceland", + "norway", "finland", "sweden", "denmark", "portugal", + )}, + **{k: 100 for k in ("sweden", "norway", "finland")}, + **{k: 125 for k in ("north_macedonia", "bosnia")}, + **{k: 175 for k in ( + "ukraine", "poland", "france", "spain", "turkey", + "romania", "italy", "belarus", "united_kingdom", "germany", + )}, + **{k: 250 for k in ("russia", "usa")}, +} + +_WORLD_LABEL_SIZES: dict[str, int] = { + "asia": 200, + "africa": 100, + "europe": 110, + "australia": 50, + "south_america": 100, + "north_america": 120, +} + +# Map types whose regions are painted from the cached region-ID map. +# Flag-filled maps (``flag``, ``world_countries``) keep their underlying flag artwork. +_PAINTED_MAP_TYPES: frozenset[str] = frozenset({"default", "world"}) + +# Smallest base label size (before the global size modifier) still drawn on the +# world countries map; smaller countries stay unlabeled to keep the map readable. +_WORLD_COUNTRIES_MIN_LABEL = 1 + +# Common alternative AI spellings mapped to canonical snake_case country keys. +# Applied only when the alias target exists in the coordinates dictionary. +_WORLD_COUNTRY_ALIASES: dict[str, tuple[str, ...]] = { + "usa": ("united_states", "united_states_of_america"), + "us": ("united_states", "united_states_of_america"), + "united_states_of_america": ("united_states",), + "america": ("united_states", "united_states_of_america"), + "uk": ("united_kingdom",), + "great_britain": ("united_kingdom",), + "britain": ("united_kingdom",), + "russian_federation": ("russia",), + "czech_republic": ("czechia",), + "turkiye": ("turkey",), + "ivory_coast": ("cote_d_ivoire", "cote_divoire"), + "cote_d_ivoire": ("ivory_coast",), + "cote_divoire": ("ivory_coast", "cote_d_ivoire"), + "drc": ("democratic_republic_of_the_congo", "dr_congo"), + "dr_congo": ("democratic_republic_of_the_congo",), + "congo_kinshasa": ("democratic_republic_of_the_congo", "dr_congo"), + "democratic_republic_of_congo": ("democratic_republic_of_the_congo", "dr_congo"), + "congo_brazzaville": ("republic_of_the_congo", "congo"), + "republic_of_congo": ("republic_of_the_congo", "congo"), + "south_korea": ("korea_south", "republic_of_korea"), + "korea": ("south_korea",), + "korea_south": ("south_korea",), + "republic_of_korea": ("south_korea",), + "north_korea": ("korea_north", "dprk"), + "korea_north": ("north_korea",), + "dprk": ("north_korea",), + "burma": ("myanmar",), + "swaziland": ("eswatini",), + "eswatini": ("swaziland",), + "macedonia": ("north_macedonia",), + "holland": ("netherlands",), + "the_netherlands": ("netherlands",), + "uae": ("united_arab_emirates",), + "east_timor": ("timor_leste",), + "timor_leste": ("east_timor",), + "cabo_verde": ("cape_verde",), + "cape_verde": ("cabo_verde",), + "vatican_city": ("vatican",), + "bosnia": ("bosnia_and_herzegovina",), + "the_gambia": ("gambia",), + "the_bahamas": ("bahamas",), + "united_republic_of_tanzania": ("tanzania",), + "republic_of_serbia": ("serbia",), + "state_of_palestine": ("palestine",), + "brunei_darussalam": ("brunei",), + "viet_nam": ("vietnam",), + "lao_pdr": ("laos",), +} \ No newline at end of file diff --git a/map/functions.py b/map/functions.py index f765f77..a09dbc0 100644 --- a/map/functions.py +++ b/map/functions.py @@ -387,6 +387,202 @@ def ai_request(prompt: str, mode: str, ai_model: str, api_key: str | None = None return country_dict +IDEA_EXAMPLES = ( + "How many bears are there in your country?", + "How many school years children must study in your country?", + "What is the most popular drink in your country?", + "What is the biggest city in your country?", + "How many McDonald's restaurants are there in your country?", + "What is the most popular car brand in your country?", + "How many UNESCO World Heritage sites are there in your country?", + "What is the minimum driving age in your country?", + "What is the most popular sport in your country?", + "How many hours do people work per week in your country?", +) + + +def _call_model_text( + system_msg: str, + user_prompt: str, + ai_model: str, + api_key: str | None = None, + *, + temperature: float | None = None, + json_mode: bool = False, +) -> str: + """Send a lightweight prompt to the selected Gemini or DeepSeek model and return raw text.""" + if provider_for_model(ai_model) == 'deepseek': + payload: dict[str, object] = { + 'model': ai_model, + 'messages': [ + {'role': 'system', 'content': system_msg}, + {'role': 'user', 'content': user_prompt}, + ], + 'thinking': {'type': 'disabled'}, + 'max_tokens': 512, + 'stream': False, + } + if json_mode: + payload['response_format'] = {'type': 'json_object'} + if temperature is not None: + payload['temperature'] = validate_temperature(temperature) + key = api_key or configured_api_key('deepseek') + result = _deepseek_json('chat/completions', key, payload=payload) + try: + content = result['choices'][0]['message']['content'] + except (KeyError, IndexError, TypeError) as error: + raise AIServiceError('DeepSeek returned no idea. Please try again.', 502) from error + if not isinstance(content, str) or not content.strip(): + raise AIServiceError('DeepSeek returned an empty idea. Please try again.', 502) + return content.strip() + + try: + options: dict[str, object] = { + 'http_options': types.HttpOptions( + timeout=AI_TIMEOUT_MS, + retry_options=types.HttpRetryOptions(attempts=1), + ), + } + if api_key: + options['api_key'] = api_key + client = genai.Client(**options) + cfg_kwargs: dict[str, object] = {} + if temperature is not None: + cfg_kwargs['temperature'] = validate_temperature(temperature) + if json_mode: + cfg_kwargs['response_mime_type'] = 'application/json' + config = {'config': types.GenerateContentConfig(**cfg_kwargs)} if cfg_kwargs else {} + response = client.models.generate_content( + model=ai_model, + contents=f"{system_msg}\n\n{user_prompt}", + **config, + ) + except genai_errors.APIError as error: + if error.code in (500, 502, 503, 504): + raise AIServiceError( + f'The selected model ({ai_model}) is overloaded or temporarily unavailable. ' + 'Please try again shortly or select another model.', 503, + ) from error + if error.code == 429: + raise AIServiceError( + 'The AI request limit or quota has been reached. Please try again later ' + 'or check the quota for your API key.', 429, + ) from error + if error.code in (400, 401, 403, 404): + raise AIServiceError( + f'The selected model ({ai_model}) could not be used. ' + 'Refresh the model list and check your API key and model access.', 400, + ) from error + raise AIServiceError('The AI service could not complete this request. Please try again.') from error + except (httpx.TimeoutException, TimeoutError) as error: + raise AIServiceError( + 'The AI model did not respond within 45 seconds. ' + 'Please try again or select a faster model.', 504, + ) from error + + text = getattr(response, 'text', None) + if not isinstance(text, str) or not text.strip(): + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + return text.strip() + + +def generate_map_idea( + ai_model: str, + api_key: str | None = None, + *, + with_params: bool = False, + available_themes: list[str] | tuple[str, ...] | None = None, + available_fonts: list[str] | tuple[str, ...] | None = None, + temperature: float | None = None, +) -> dict[str, object]: + """Generate a single map idea (and optionally matching map parameters) via the selected AI model.""" + examples_block = "\n".join(f'- "{ex}"' for ex in IDEA_EXAMPLES) + + if not with_params: + system_msg = ( + "You generate short, engaging, curiosity-sparking map topic questions in English. " + "Return ONLY the idea itself as a single plain-text sentence/question, with no quotes, " + "no numbering, no markdown, and no explanation." + ) + user_prompt = ( + "Generate 1 new creative map topic idea in the exact same style and format as these examples:\n" + f"{examples_block}\n\n" + "Return only the idea text." + ) + raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=temperature, json_mode=False) + idea = raw.strip().splitlines()[0].strip().strip('"\'` ') + if not idea: + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + return {"idea": idea} + + raw_themes = [str(t) for t in (available_themes or list(constants._PALETTE_THEMES.keys()))] + themes = [t for t in raw_themes if t not in ("auto", "ocean", "emerald")] or raw_themes + fonts = [str(f) for f in (available_fonts or ["Bips.ttf", "DIN Condensed.ttf", "kodchasan.ttf", "arialroundedmtbold.ttf"])] + allowed_map_types = ("default", "flag", "world", "world_countries") + allowed_modes = ("text", "number") + allowed_extras = ("none", "show_most_least", "show_short_form") + + system_msg = ( + "You generate short, engaging map topic questions in English along with the best map rendering parameters. " + "Return ONLY a valid JSON object (no markdown fences, no commentary)." + ) + user_prompt = ( + "Generate 1 new creative map topic idea in the same style as these examples:\n" + f"{examples_block}\n\n" + "Return a JSON object with these exact keys:\n" + '- "idea": string (the single map question/topic, no surrounding quotes)\n' + f'- "mode": one of {list(allowed_modes)} ("number" for numeric counts/amounts/years, "text" for names/words/categories)\n' + f'- "map_type": one of {list(allowed_map_types)} ("default" = Europe painted, "flag" = Europe flags, "world" = continents, "world_countries" = all world countries)\n' + f'- "palette_theme": one of {themes}\n' + f'- "font": one of {fonts}\n' + f'- "extra_option": one of {list(allowed_extras)} ("show_most_least" or "show_short_form" only when mode is "number" and map_type is not "world", otherwise "none")\n' + '- "show_legend": boolean (true if a legend helps explain the map, false otherwise)' + ) + raw = _call_model_text(system_msg, user_prompt, ai_model, api_key, temperature=temperature, json_mode=True) + cleaned = raw.strip() + if cleaned.startswith("```"): + cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.IGNORECASE | re.DOTALL).strip() + try: + parsed = json.loads(cleaned) + except json.JSONDecodeError as error: + raise AIServiceError('AI returned invalid JSON for the map idea. Please try again.', 502) from error + if not isinstance(parsed, dict): + raise AIServiceError('AI returned an unexpected format for the map idea.', 502) + + idea = str(parsed.get("idea") or "").strip().strip('"\'` ') + if not idea: + raise AIServiceError('The AI model returned an empty idea. Please try again.', 502) + + mode = str(parsed.get("mode") or "text").strip().lower() + if mode not in allowed_modes: + mode = "text" + map_type = str(parsed.get("map_type") or "default").strip().lower() + if map_type not in allowed_map_types: + map_type = "default" + palette_theme = str(parsed.get("palette_theme") or "auto").strip() + if palette_theme not in themes: + palette_theme = "auto" if "auto" in themes else themes[0] + font = str(parsed.get("font") or fonts[0]).strip() + if font not in fonts: + font = fonts[0] + extra_option = str(parsed.get("extra_option") or "none").strip().lower() + if extra_option not in allowed_extras or mode != "number" or map_type == "world": + extra_option = "none" + show_legend = bool(parsed.get("show_legend", False)) + + return { + "idea": idea, + "params": { + "mode": mode, + "map_type": map_type, + "palette_theme": palette_theme, + "font": font, + "extra_option": extra_option, + "show_legend": show_legend, + }, + } + + diff --git a/pyproject.toml b/pyproject.toml index 457aac7..12857e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,10 @@ dependencies = [ "pillow>=9.2.0,<12.0.0", "click>=8.0.0", "google-genai>=1.56.0", + "cryptography>=43.0.0", + "google-api-python-client>=2.150.0,<3.0.0", + "google-auth-oauthlib>=1.2.0,<2.0.0", + "google-auth-httplib2>=0.2.0,<1.0.0", "python-dotenv>=1.0.0", "rich>=13.0.0", "flask>=3.1.0", diff --git a/readme.md b/readme.md index 2effc8e..e5746d7 100644 --- a/readme.md +++ b/readme.md @@ -196,6 +196,45 @@ Maps, background footage, audio, and custom overlay materials have a **10 MiB pe Worker files older than approximately **30 minutes** are cleaned up when relevant operations run. Download completed videos promptly. Browser-restored inline audio can keep a selected track usable after worker files have expired, subject to browser storage availability. +### Upload rendered videos to YouTube + +1. Install the updated `requirements.txt` (or rebuild the Docker containers). +2. In Google Cloud Console, enable **YouTube Data API v3**, configure the OAuth consent screen and, while the app is in testing, add your Google account as a test user. Download an **OAuth client secret JSON** file. +3. Open **Video Studio → YouTube upload**, choose the JSON file, and click **Connect Google / YouTube**. Approve access to the desired channel. +4. Set a YouTube title (or leave it empty to use the video headline), description, comma-separated tags, visibility, and the made-for-kids setting. +5. Enable **Automatically upload after rendering**, then render. AutoMap uploads the resulting MP4 in the background and shows progress and a YouTube link. You can also click **Upload rendered video to YouTube** after rendering. Visibility defaults to **Private**; automatic upload must be enabled again on each visit. + +For `localhost`, either a **Desktop app** or **Web application** client works. +For a hosted server, use a **Web application** client and register the exact +redirect URI displayed in the panel under **Authorized redirect URIs** in Google +Cloud Console. The hosted URL must use HTTPS. Behind a reverse proxy, set +`YOUTUBE_REDIRECT_URI=https://your-host/api/youtube/callback` in the server +environment (or Docker Compose `.env`) to match the public URL. Google setup and +upload behavior are described in the [official upload guide](https://developers.google.com/youtube/data/guides/uploading_a_video). + +Each browser profile has its own YouTube connection. Two people using separate +browsers or profiles can supply different client files, authorize different +channels, and upload concurrently. Credentials and pending OAuth secrets are +stored **encrypted** in `instance/youtube/`, with private file permissions; +Google tokens and client secrets are never sent back to the browser, saved in +localStorage, or forwarded to the media worker. A signed browser session selects +its own credentials and upload jobs. Sharing a browser profile shares this +connection; clearing cookies, logging out, or changing the web login requires +connecting again. **Disconnect** deletes that browser's saved credentials; it +does not cancel an upload already started or revoke the grant in Google Account. + +For persistent server storage, retain the `automap-session` Docker volume (it +already mounts `/app/instance`). For native deployment, back up `instance/` and +retain its session secret, or configure a stable `WEB_SECRET_KEY`. Encryption +uses a separate key derived from that secret; replacing it makes existing +credentials unreadable. Run a single web process, as in the supplied Waitress +configuration. Up to two background uploads run at once. Upload status and +in-progress transfers live in that process; a server restart preserves the saved +Google connection but interrupts active transfers. Check YouTube Studio before +starting a new upload after an interruption. Upload errors leave the rendered +MP4 available for download. The same render cannot be uploaded twice in the +running process, and worker file expiry still applies. + ## Command-line usage Run commands from the repository root: diff --git a/requirements.txt b/requirements.txt index db259f9..1219c23 100644 --- a/requirements.txt +++ b/requirements.txt @@ -25,3 +25,9 @@ yt-dlp>=2024.12.0 pydub>=0.25.1 moviepy>=2.0.0 proglog>=0.1.10,<1.0.0 + +# YouTube Data API uploads and OAuth authorization. +google-api-python-client>=2.150.0,<3.0.0 +google-auth-oauthlib>=1.2.0,<2.0.0 +google-auth-httplib2>=0.2.0,<1.0.0 +cryptography>=43.0.0 diff --git a/static/youtube-upload.js b/static/youtube-upload.js new file mode 100644 index 0000000..6534c69 --- /dev/null +++ b/static/youtube-upload.js @@ -0,0 +1,129 @@ +/* Google credentials and OAuth tokens are never stored in browser storage. */ +let youtubeCsrf = ''; +let youtubeConnected = false; +let youtubePolling = 0; +const youtubeFields = ['youtubeTitle', 'youtubeDescription', 'youtubeTags', 'youtubePrivacy', 'youtubeKids']; +const ytElement = id => document.getElementById(id); + +function youtubeSettings() { + const settings = { + title: ytElement('youtubeTitle').value.trim() || ytElement('videoTitleInput').value.trim(), + description: ytElement('youtubeDescription').value, + tags: ytElement('youtubeTags').value, + privacy: ytElement('youtubePrivacy').value, + made_for_kids: ytElement('youtubeKids').checked, + }; + if (!settings.title || settings.title.length > 100 || /[<>]/.test(settings.title)) throw new Error('YouTube title must contain 1–100 characters and no < or >.'); + if (new TextEncoder().encode(settings.description).length > 5000 || /[<>]/.test(settings.description)) throw new Error('YouTube description must be at most 5000 UTF-8 bytes and contain no < or >.'); + return settings; +} + +async function youtubeRequest(url, options = {}) { + const response = await fetch(url, {...options, headers: {...options.headers, 'X-YouTube-CSRF': youtubeCsrf}, cache: 'no-store'}); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || 'YouTube request failed.'); + return result; +} + +async function loadYouTubeConnection() { + try { + const result = await youtubeRequest('/api/youtube/status'); + youtubeCsrf = result.csrf_token; + youtubeConnected = result.connected; + ytElement('youtubeConnection').textContent = result.connected ? 'YouTube account connected.' : 'YouTube account not connected.'; + ytElement('youtubeRedirect').textContent = result.redirect_uri; + } catch (error) { + ytElement('youtubeConnection').textContent = error.message; + } +} + +async function connectYouTube() { + const file = ytElement('youtubeSecret').files[0]; + if (!file) { showToast('Choose the client secret JSON file first.', 'warn'); return; } + ytElement('youtubeConnect').disabled = true; + try { + const form = new FormData(); + form.append('client_secret', file); + const result = await youtubeRequest('/api/youtube/connect', {method: 'POST', body: form}); + window.location.assign(result.authorization_url); + } catch (error) { + ytElement('youtubeConnection').textContent = error.message; + showToast(error.message, 'error'); + } finally { ytElement('youtubeConnect').disabled = false; } +} + +async function disconnectYouTube() { + try { + await youtubeRequest('/api/youtube/disconnect', {method: 'POST'}); + ytElement('youtubeAuto').checked = false; + await loadYouTubeConnection(); + } catch (error) { showToast(error.message, 'error'); } +} + +function watchYouTubeUpload(jobId) { + const generation = ++youtubePolling; + ytElement('youtubeUpload').disabled = true; + ytElement('youtubeVideoLink').classList.add('hidden'); + try { sessionStorage.setItem('automap-youtube-job', jobId); } catch {} + const poll = async () => { + if (generation !== youtubePolling) return; + try { + const job = await youtubeRequest(`/api/youtube/jobs/${encodeURIComponent(jobId)}`); + if (generation !== youtubePolling) return; + ytElement('youtubeUploadStatus').textContent = job.error || `${job.phase} (${job.progress}%)`; + if (job.status === 'complete') { + const link = ytElement('youtubeVideoLink'); + link.href = job.url; + link.classList.remove('hidden'); + showToast('Video uploaded to YouTube.', 'success'); + } + if (job.status !== 'uploading') { + try { sessionStorage.removeItem('automap-youtube-job'); } catch {} + return; + } + } catch (error) { + ytElement('youtubeUploadStatus').textContent = `${error.message} Check YouTube Studio before starting another upload.`; + return; + } + setTimeout(poll, 1500); + }; + poll(); +} + +async function uploadToYouTube() { + if (!renderResultData?.upload_token) { showToast('Render a video first.', 'warn'); return; } + ytElement('youtubeUpload').disabled = true; + try { + const result = await youtubeRequest('/api/youtube/upload', {method: 'POST', headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({upload_token: renderResultData.upload_token, youtube: youtubeSettings()})}); + watchYouTubeUpload(result.job_id); + } catch (error) { + ytElement('youtubeUpload').disabled = false; + ytElement('youtubeUploadStatus').textContent = error.message; + showToast(error.message, 'error'); + } +} + +document.addEventListener('DOMContentLoaded', () => { + try { + const saved = JSON.parse(localStorage.getItem('automap-youtube-settings') || '{}'); + for (const id of youtubeFields) { + if (id === 'youtubeKids') ytElement(id).checked = saved[id] === true; + else if (typeof saved[id] === 'string') ytElement(id).value = saved[id]; + } + const job = sessionStorage.getItem('automap-youtube-job'); + if (job) watchYouTubeUpload(job); + } catch {} + for (const id of youtubeFields) ytElement(id).addEventListener('input', () => { + const settings = Object.fromEntries(youtubeFields.map(key => [key, key === 'youtubeKids' ? ytElement(key).checked : ytElement(key).value])); + try { localStorage.setItem('automap-youtube-settings', JSON.stringify(settings)); } catch {} + }); + // Automatic upload is an explicit choice for each visit. + const outcome = new URLSearchParams(location.search).get('youtube'); + if (outcome) { + ytElement('youtubePanel').open = true; + if (outcome !== 'connected') showToast(outcome === 'denied' ? 'Google authorization cancelled.' : 'Google authorization failed. Check the redirect URI and try connecting again.', 'error'); + history.replaceState(null, '', location.pathname); + } + loadYouTubeConnection(); +}); diff --git a/templates/index.html b/templates/index.html index 014db8c..b07c850 100644 --- a/templates/index.html +++ b/templates/index.html @@ -397,14 +397,26 @@

+
+
+ + +
-
- - - -
@@ -653,6 +665,29 @@

+ + @@ -1606,6 +1641,87 @@

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

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

let topicPreviewTimer; function scheduleTopicPreview(event) { clearTimeout(topicPreviewTimer); - if (event.isComposing) return; + if (event && event.isComposing) return; topicPreviewTimer = setTimeout(flushTopicPreview, 250); } @@ -2189,8 +2308,11 @@

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

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

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

if (response.ok && result.status === 'success') { if (result.command) logToConsole(`[Server] ${result.command}`, 'info'); + if (result.warning) { + logToConsole(`[Warning] ${result.warning}`, 'warn'); + showToast(result.warning, 'warn'); + } logToConsole(`[Success] Map generated and loaded (${describeDataUrl(result.image_url)})`, 'success'); if (result.map_values) { @@ -3164,6 +3291,33 @@

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

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

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

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

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

setSelectedExtraOption('none'); const legendToggle = document.getElementById('showLegendToggle'); if (legendToggle) legendToggle.checked = false; + const hlToggle = document.getElementById('highlightExtremaToggle'); + if (hlToggle) hlToggle.checked = false; + const hlHigh = document.getElementById('highlightHighColor'); + if (hlHigh) hlHigh.value = '#00e5ff'; + const hlLow = document.getElementById('highlightLowColor'); + if (hlLow) hlLow.value = '#ff2daa'; changeAiProvider('gemini', fallbackModels.find(model => modelProvider(model) === 'gemini')); document.getElementById('fontSelect').selectedIndex = 0; document.getElementById('topicInput').value = ''; diff --git a/templates/video.html b/templates/video.html index a4b5466..a478cd8 100644 --- a/templates/video.html +++ b/templates/video.html @@ -253,10 +253,12 @@ } .codec-card:disabled { opacity: .4; cursor: not-allowed; } #stageMapArea { + position: relative; display: flex; flex: 1; min-height: 0; - width: 100%; + width: 1080px; + margin-inline: -20px; align-items: center; justify-content: center; } @@ -870,6 +872,84 @@

Frame Com Smooth intro fade-in from black (0.0s → 0.8s) + +
@@ -1272,6 +1352,7 @@

+
@@ -1285,12 +1366,67 @@

+ + +
+ + +
+
+ + +
+ 00:00.0 / 00:08.0 +
+
+ YouTube upload +
+

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

+ +

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

+
+ + +
+

Checking connection…

+ + + + + + + +

+ +
+
+