Skip to content
Merged

Dev #20

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 39 additions & 14 deletions automap_rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use pyo3::exceptions::PyValueError;
use pyo3::exceptions::{PyRuntimeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyTuple};
use std::io::{Read, Write};
Expand Down Expand Up @@ -189,12 +189,19 @@ fn render_video_rs(
}
enc_args.extend(["-pix_fmt".into(), "yuv420p".into(), output_path.into()]);

let mut encoder = Command::new(&ffmpeg_bin)
let mut encoder = match Command::new(&ffmpeg_bin)
.args(&enc_args)
.stdin(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("ffmpeg encoder spawn failed: {e}")))?;
{
Ok(child) => child,
Err(error) => {
let _ = decoder.kill();
let _ = decoder.wait();
return Err(PyRuntimeError::new_err(format!("ffmpeg encoder spawn failed: {error}")));
}
};

let mut enc_in = encoder
.stdin
Expand All @@ -213,12 +220,22 @@ fn render_video_rs(
let mut ca_row_buf = if impact_fx_enabled { vec![0u8; width * 4] } else { Vec::new() };
let mut x_resample_lut = if need_zoom_buf { Vec::with_capacity(width) } else { Vec::new() };

let mut frame_read_error = None;
let mut frame_write_error = None;
let mut decoder_finished = false;
for frame_idx in 0..total_frames {
if dec_out.read_exact(&mut bg_buf).is_err() {
if frame_idx == 0 {
break;
if !decoder_finished {
// Keep a complete previous frame when the decoder ends early.
match dec_out.read_exact(&mut frame_buf) {
Ok(()) => std::mem::swap(&mut bg_buf, &mut frame_buf),
Err(error) if frame_idx > 0 && error.kind() == std::io::ErrorKind::UnexpectedEof => {
decoder_finished = true;
}
Err(error) => {
frame_read_error = Some(error);
break;
}
}
// Hold the last decoded background frame if the source ended slightly early.
}
frame_buf.copy_from_slice(&bg_buf);

Expand Down Expand Up @@ -350,17 +367,25 @@ fn render_video_rs(
};

// Stream the composited frame into ffmpeg's stdin.
enc_in
.write_all(out_buf)
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("encoder write failed: {e}")))?;
if let Err(error) = enc_in.write_all(out_buf) {
frame_write_error = Some(error);
break;
}
}

// Close stdin so ffmpeg flushes and finalizes the MP4 container.
// Close the decoder pipe before waiting. FFmpeg may still be writing frames
// past the requested count and would block on a full pipe.
drop(enc_in);
let status = encoder
.wait()
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("encoder wait failed: {e}")))?;
drop(dec_out);
let _ = decoder.wait();
let status = encoder.wait();
if let Some(error) = frame_read_error {
return Err(PyRuntimeError::new_err(format!("decoder read failed: {error}")));
}
if let Some(error) = frame_write_error {
return Err(PyRuntimeError::new_err(format!("encoder write failed: {error}")));
}
let status = status.map_err(|e| PyRuntimeError::new_err(format!("encoder wait failed: {e}")))?;

if !status.success() {
return Err(pyo3::exceptions::PyRuntimeError::new_err(format!(
Expand Down
6 changes: 5 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def _available_fonts():

app = Flask(__name__)
# Three 10 MiB materials (map, background and music) grow by 4/3 in JSON.
app.config["MAX_CONTENT_LENGTH"] = 48 * 1024 * 1024
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024

from web_auth import init_web_auth

Expand Down Expand Up @@ -754,6 +754,9 @@ def api_generate_idea():
except ValueError as err:
return jsonify(status='error', error=str(err)), 400

raw_avoid = data.get("avoid_ideas")
avoid_ideas = [str(item).strip() for item in raw_avoid if str(item).strip()][:30] if isinstance(raw_avoid, list) else []

try:
result = generate_map_idea(
model,
Expand All @@ -762,6 +765,7 @@ def api_generate_idea():
available_themes=list(_PALETTE_THEMES.keys()),
available_fonts=_available_fonts(),
temperature=temperature,
avoid_ideas=avoid_ideas,
)
except AIServiceError as error:
return jsonify(status='error', error=str(error)), error.status_code
Expand Down
106 changes: 62 additions & 44 deletions map/auto_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,12 @@ def _numeric_extrema(values):
return max(numeric, key=numeric.get), min(numeric, key=numeric.get)


def _format_text_label(value: object) -> str:
"""Uppercase the first character while preserving acronyms and other casing."""
label = "" if value is None else str(value).strip()
return label[:1].upper() + label[1:]


def _format_legend_bound(val: float) -> str:
"""Format a numeric legend bound compactly so ranges fit in open sea space."""
abs_val = abs(val)
Expand Down Expand Up @@ -961,16 +967,24 @@ def _report(stage: int, label: str) -> None:

log.success(f"Got information from AI ({len(ai_answer)} entries)")

resolved_theme = _resolve_theme_name(palette_theme, prompt=prompt, mode=mode)
auto_txt, auto_num = _auto_fill_from_ai(
ai_answer,
mode,
palette_theme=palette_theme,
prompt=prompt,
)
is_painted_map = map_type in constants._PAINTED_MAP_TYPES
if is_painted_map:
resolved_theme = _resolve_theme_name(palette_theme, prompt=prompt, mode=mode)
auto_txt, auto_num = _auto_fill_from_ai(
ai_answer,
mode,
palette_theme=palette_theme,
prompt=prompt,
)
else:
resolved_theme = "flags"
auto_txt, auto_num = {}, {}
filling_txt = {}
filling_txt_ci = {}
filling_num = {}
theme_requested = (palette_theme or "auto").strip().lower() != "auto"

if auto_style is True:
if is_painted_map and auto_style is True:
if mode == "text":
merged_txt = dict(auto_txt)
req_keys_low = {k.strip().lower() for k in req_txt}
Expand Down Expand Up @@ -1072,63 +1086,67 @@ def _report(stage: int, label: str) -> None:
if mode == 'number':
try:
info = ai_answer_norm[name_key]
color = _random_region_color()
color = _random_region_color() if is_painted_map else (0, 0, 0, 0)
num_value = _parse_short_number(info)
raw_num_value = _parse_short_number(raw_ai_answer_norm.get(name_key))
if num_value is None:
if num_value is None and is_painted_map:
log.warning(f"Non-numeric value for {name}: {info!r}; using random color")

if num_value is not None:
if highlight_extrema:
numeric_region_values[index] = float(raw_num_value if raw_num_value is not None else num_value)
# Pick the colour of the first matching range. Ranges are
# treated as (low < value <= high) per the docs.
matched_bounds = None
for candidate in (num_value, raw_num_value):
if candidate is None or matched_bounds is not None:
continue
for (low_lim, high_lim), color_tup in filling_num.items():
if low_lim < candidate <= high_lim:
color = color_tup
matched_bounds = (low_lim, high_lim)
break
if matched_bounds is None and auto_style is True and auto_num:
for (low_lim, high_lim), color_tup in auto_num.items():
if low_lim < num_value <= high_lim:
color = color_tup
matched_bounds = (low_lim, high_lim)
break
if matched_bounds is not None:
used_num_rules[matched_bounds] = color
if is_painted_map:
# Pick the colour of the first matching range. Ranges are
# treated as (low < value <= high) per the docs.
matched_bounds = None
for candidate in (num_value, raw_num_value):
if candidate is None or matched_bounds is not None:
continue
for (low_lim, high_lim), color_tup in filling_num.items():
if low_lim < candidate <= high_lim:
color = color_tup
matched_bounds = (low_lim, high_lim)
break
if matched_bounds is None and auto_style is True and auto_num:
for (low_lim, high_lim), color_tup in auto_num.items():
if low_lim < num_value <= high_lim:
color = color_tup
matched_bounds = (low_lim, high_lim)
break
if matched_bounds is not None:
used_num_rules[matched_bounds] = color
except KeyError as e:
info = ""
log.warning(f"No data / color for {e}; using random color")
color = _random_region_color()
random_colors[name] = color
if is_painted_map:
log.warning(f"No data / color for {e}; using random color")
color = _random_region_color()
random_colors[name] = color
else:
color = (0, 0, 0, 0)

elif mode == 'text':
'''Text mode'''
raw_info = ai_answer_norm.get(name_key)
info = "" if raw_info is None else str(raw_info).strip()
info = _format_text_label(raw_info)
if not info:
log.info(f"No information for {name}, skipping")
continue
try:
# Match filling colours case-insensitively and ignoring whitespace,
# so "Yes", "yes" and " yes " all find the same colour.
color = filling_txt_ci[info.lower()]
except KeyError:
if map_type in constants._PAINTED_MAP_TYPES:
if is_painted_map:
try:
# Match filling colours case-insensitively and ignoring whitespace,
# so "Yes", "yes" and " yes " all find the same colour.
color = filling_txt_ci[info.lower()]
except KeyError:
log.info(f"No filling color for '{info}'; using random")
# Repeated answers share a color so categories remain recognizable.
try:
color = random_colors[info]
except KeyError:
color = _random_region_color()
random_colors[info] = color
else:
color = _random_region_color()
used_txt_rules.setdefault(info, color)
used_txt_rules.setdefault(info, color)
else:
color = (0, 0, 0, 0)
else:
showerror("Error", f"Unknown mode: {mode}")
return
Expand Down Expand Up @@ -1292,7 +1310,7 @@ def _report(stage: int, label: str) -> None:
else:
result = _alpha_composite(img, text_layer)

if show_legend:
if show_legend and is_painted_map:
if mode == "number":
legend_src = used_num_rules or effective_num
legend_entries = [
Expand All @@ -1302,7 +1320,7 @@ def _report(stage: int, label: str) -> None:
else:
legend_src = used_txt_rules or effective_txt
legend_entries = [
(tuple(c), str(label).strip())
(tuple(c), _format_text_label(label))
for label, c in legend_src.items()
if str(label).strip()
]
Expand Down
Loading
Loading