Skip to content
Merged
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
7 changes: 5 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,8 @@ playwright-report/
instance/

# Rust build artifacts
target/
automap_rs/target/
/target/
**/target/
*.so
*.dylib
*.pyd
9 changes: 6 additions & 3 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ def main():
help="Global font size modifier (default 15).")
@click.option("-eop", "--extra-option",
"optional_feature",
type=click.Choice(["none", "show_most_least", "short_form"], case_sensitive=False),
type=click.Choice(["none", "show_most_least", "short_form", "show_most_least,short_form", "short_form,show_most_least"], case_sensitive=False),
default="none",
show_default=True,
help="One extra option: none (default), show_most_least or short_form.")
help="Extra options: none, show_most_least, short_form, or both separated by a comma.")
@click.option("--model",
type=click.Choice(AVAILABLE_MODELS, case_sensitive=False),
default=AVAILABLE_MODELS[0],
Expand All @@ -106,7 +106,8 @@ def main():
help="API key for the selected model provider (overrides its environment key).")
@click.option("--temperature", type=click.FloatRange(0, 2), default=None,
help="AI sampling randomness, from 0 to 2. Omit to use the model default.")
def make(prompt, mode, map_type, size_mod, optional_feature, model, font_name, show_result, verbose, api_key, temperature):
@click.option("--legend", "show_legend", is_flag=True, help="Draw a color legend on the map.")
def make(prompt, mode, map_type, size_mod, optional_feature, model, font_name, show_result, verbose, api_key, temperature, show_legend):
"""Generate a map from PROMPT and save it as result.png.

Example:
Expand All @@ -119,6 +120,8 @@ def make(prompt, mode, map_type, size_mod, optional_feature, model, font_name, s
from map.auto_map import auto_map

ai_options = {}
if show_legend:
ai_options["show_legend"] = True
if temperature is not None:
from map.functions import validate_temperature
try:
Expand Down
69 changes: 61 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io
import os
import re
import threading
import time

from pathlib import Path
Expand Down Expand Up @@ -280,7 +281,7 @@ def _auto_map_with_ai_cache(*, refresh: bool, provider: str, api_key, **kwargs):
identity = str(session.get('web_identity', '') or '')
except RuntimeError:
identity = ''
short_form = kwargs.get('optional_feature') == 'short_form'
short_form = 'short_form' in str(kwargs.get('optional_feature') or '')
scope = ai_cache.scope(identity, api_key)
base_fields = dict(
prompt=str(kwargs.get('prompt') or ''),
Expand All @@ -296,17 +297,16 @@ def _auto_map_with_ai_cache(*, refresh: bool, provider: str, api_key, **kwargs):
if cached is None and not refresh and short_form:
raw_cached = ai_cache.get(ai_cache.make_key(scope, short_form=False, **base_fields))
if raw_cached and any(_parse_short_number(v) is not None for v in raw_cached.values()):
cached = {k: _format_short_number(v) for k, v in raw_cached.items()}
cached = raw_cached
if cached is not None:
kwargs['ai_answer_override'] = cached
buffer = auto_map(api_key=api_key, **kwargs)
if buffer is not None:
meta = getattr(buffer, 'map_meta', None)
answer = meta.get('ai_answer') if isinstance(meta, dict) else None
answer = meta.get('raw_ai_answer', meta.get('ai_answer')) if isinstance(meta, dict) else None
if isinstance(answer, dict):
if short_form:
answer = {k: _format_short_number(v) for k, v in answer.items()}
meta['ai_answer'] = answer
meta['ai_answer'] = {k: _format_short_number(v) for k, v in answer.items()}
if not refresh:
ai_cache.put(cache_key, answer)
return buffer, cached is not None
Expand Down Expand Up @@ -541,6 +541,37 @@ def _parse_render_params(data: dict[str, object]) -> tuple[str, str | None, int]
return str(font_name), extra_option, gsm


_MAP_PROGRESS_LOCK = threading.Lock()
_MAP_PROGRESS: dict[str, dict[str, object]] = {}


def _set_map_progress(progress_id: str, stage: int, label: str, status: str = "running") -> None:
"""Record the active map generation stage for ``progress_id``."""
if not progress_id:
return
now = time.time()
with _MAP_PROGRESS_LOCK:
stale = [k for k, v in _MAP_PROGRESS.items() if now - float(v.get("updated_at", 0)) > 300]
for k in stale:
_MAP_PROGRESS.pop(k, None)
_MAP_PROGRESS[progress_id] = {
"stage": stage,
"label": label,
"status": status,
"updated_at": now,
}


@app.get('/api/generate_progress/<progress_id>')
def api_generate_progress(progress_id: str):
"""Return current map generation progress for ``progress_id``."""
with _MAP_PROGRESS_LOCK:
entry = dict(_MAP_PROGRESS.get(progress_id) or {"stage": 1, "label": "Querying AI model...", "status": "running"})
resp = jsonify(entry)
resp.headers["Cache-Control"] = "no-store"
return resp


@app.route('/api/generate/', methods=['POST'])
@app.route('/api/generate', methods=['POST'])
def generate():
Expand Down Expand Up @@ -591,7 +622,17 @@ def generate():
if temperature_options:
command += f" --temperature {temperature_options['temperature']:g}"

style_kwargs: dict[str, object] = {}
show_legend = bool(data.get("show_legend", False))
if show_legend:
command += " --legend"

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}
if progress_id:
style_kwargs["progress_callback"] = lambda stage, label: _set_map_progress(progress_id, stage, label)
for style_key, kw_name in (
("filling_txt", "filling_txt_override"),
("filling_num", "filling_num_override"),
Expand Down Expand Up @@ -621,19 +662,30 @@ def generate():
**style_kwargs,
)
except AIServiceError as error:
if progress_id:
_set_map_progress(progress_id, 1, str(error), status="error")
return jsonify(status='error', command=command, error=str(error)), error.status_code
except KeyError as e:
if progress_id:
_set_map_progress(progress_id, 1, f"Missing field: {e}", status="error")
return jsonify({"status": "error", "command": command,
"error": f"Missing field: {e}"}), 400
except Exception as e: # noqa: BLE001 - surface failures to the UI
if progress_id:
_set_map_progress(progress_id, 1, str(e), status="error")
return jsonify({"status": "error", "command": command,
"error": str(e)}), 500

# auto_map returns None on AI failure / unknown map type.
if buffer is None:
if progress_id:
_set_map_progress(progress_id, 1, "Map generation failed.", status="error")
return jsonify({"status": "error", "command": command,
"error": "Map generation failed. Check the server logs."}), 500

if progress_id:
_set_map_progress(progress_id, 4, "Finalizing map...", status="done")

# Encode the PNG buffer as a data URL the browser can load directly.
encoded = base64.b64encode(buffer.getvalue()).decode('ascii')

Expand All @@ -646,7 +698,7 @@ def generate():
render_meta = getattr(buffer, "map_meta", None)
ai_vals = render_meta.get("ai_answer") if isinstance(render_meta, dict) else None
if isinstance(ai_vals, dict) and ai_vals:
resp_payload["map_values"] = ai_vals
resp_payload["map_values"] = render_meta.get("raw_ai_answer", ai_vals)
resp_payload["analysis"] = _build_analysis_from_ai(
ai_vals,
mode=str(data.get("mode") or "auto"),
Expand Down Expand Up @@ -942,7 +994,7 @@ def generate_batch():
render_meta = getattr(buffer, "map_meta", None)
ai_vals = render_meta.get("ai_answer") if isinstance(render_meta, dict) else None
if isinstance(ai_vals, dict) and ai_vals:
item_payload["map_values"] = ai_vals
item_payload["map_values"] = render_meta.get("raw_ai_answer", ai_vals)
item_payload["analysis"] = _build_analysis_from_ai(
ai_vals,
mode=item_mode,
Expand Down Expand Up @@ -1003,6 +1055,7 @@ def api_restyle_map():
auto_style=auto_style,
palette_theme=palette_theme,
ai_answer_override=map_values,
show_legend=bool(data.get("show_legend", False)),
)
except Exception as e: # noqa: BLE001
return jsonify({"status": "error", "error": str(e)}), 500
Expand Down
Loading
Loading