diff --git a/batch_template.csv b/batch_template.csv
new file mode 100644
index 0000000..af9301c
--- /dev/null
+++ b/batch_template.csv
@@ -0,0 +1,2 @@
+prompt,mode,map_type,gsm,extra_option,model,font,palette_theme,output
+"Population density by country in Europe",number,default,15,none,gemini-3.8-flash,Bips.ttf,auto,europe_population.png
diff --git a/cli.py b/cli.py
index 563c705..99a4b84 100644
--- a/cli.py
+++ b/cli.py
@@ -141,6 +141,122 @@ def make(prompt, mode, map_type, size_mod, optional_feature, model, font_name, s
raise click.ClickException("Map generation failed. See errors above.")
+@main.command()
+@click.argument("ideas_file", type=click.Path(exists=True, dir_okay=False, path_type=Path))
+@click.option("-o", "--output-dir",
+ "output_dir",
+ type=click.Path(file_okay=False, path_type=Path),
+ default=Path("output_maps"),
+ show_default=True,
+ help="Directory where generated PNG maps will be saved.")
+@click.option("-m", "--mode",
+ type=click.Choice(["text", "number"], case_sensitive=False),
+ default="text",
+ show_default=True,
+ help="Default data mode: text (default) or number.")
+@click.option("-mp", "--map-type",
+ "map_type",
+ type=click.Choice(["default", "flag", "world"], case_sensitive=False),
+ default="default",
+ show_default=True,
+ help="Default map type: default, flag or world.")
+@click.option("-gsm", "--global-size-modifier",
+ "size_mod",
+ type=int,
+ default=15,
+ show_default=True,
+ help="Default 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),
+ default="none",
+ show_default=True,
+ help="Default extra option: none, show_most_least or short_form.")
+@click.option("--model",
+ type=click.Choice(AVAILABLE_MODELS, case_sensitive=False),
+ default=AVAILABLE_MODELS[0],
+ show_default=True,
+ help="Default AI model to use.")
+@click.option("--font",
+ "font_name",
+ type=click.Choice(_available_fonts(), case_sensitive=True),
+ default="Bips.ttf",
+ show_default=True,
+ help="Default font file name from resources/fonts.")
+@click.option("-v", "--verbose",
+ is_flag=True,
+ default=False,
+ help="Print detailed progress output.")
+@click.option("--key",
+ "api_key",
+ default=None,
+ help="Gemini API key for this run (overrides GEMINI_API_KEY env var).")
+def batch(ideas_file, output_dir, mode, map_type, size_mod, optional_feature, model, font_name, verbose, api_key):
+ """Generate multiple maps from ideas listed in a .csv IDEAS_FILE."""
+ from map import log
+ from map.auto_map import auto_map
+ from map.functions import load_ideas_from_file, slugify_prompt
+
+ log.set_verbose(verbose)
+ if api_key:
+ os.environ["GEMINI_API_KEY"] = api_key
+
+ try:
+ ideas = load_ideas_from_file(ideas_file)
+ except ValueError as err:
+ raise click.ClickException(str(err)) from err
+
+ if not ideas:
+ raise click.ClickException(f"No valid map ideas found in {ideas_file}.")
+
+ output_dir.mkdir(parents=True, exist_ok=True)
+ available_fonts = set(_available_fonts())
+ succeeded = 0
+
+ for idx, idea in enumerate(ideas, start=1):
+ prompt = str(idea["prompt"])
+ item_mode = str(idea.get("mode") or mode).lower()
+ item_map_type = str(idea.get("map_type") or map_type).lower()
+ item_size_mod = int(idea.get("gsm", size_mod))
+ raw_eop = str(idea.get("extra_option") or optional_feature).lower()
+ item_feature = None if raw_eop == "none" else raw_eop
+ item_model = str(idea.get("model") or model)
+ item_font = str(idea.get("font") or font_name)
+ if item_font not in available_fonts:
+ item_font = font_name
+
+ log.step(f"[{idx}/{len(ideas)}] Generating map: {prompt}")
+ buffer = auto_map(
+ prompt=prompt,
+ mode=item_mode,
+ map_type=item_map_type,
+ size_mod=item_size_mod,
+ optional_feature=item_feature,
+ model=item_model,
+ font_name=item_font,
+ show_result=False,
+ io_res=True,
+ api_key=api_key,
+ )
+ if buffer is None:
+ log.warning(f"[{idx}/{len(ideas)}] Failed to generate map for: {prompt}")
+ continue
+
+ custom_out = str(idea.get("output") or "").strip()
+ filename = Path(custom_out).name if custom_out else f"{idx:02d}_{slugify_prompt(prompt)}.png"
+ if not filename.lower().endswith(".png"):
+ filename += ".png"
+ target = output_dir / filename
+ target.write_bytes(buffer.getvalue())
+ succeeded += 1
+ log.success(f"Saved {target}")
+
+ if succeeded == 0:
+ raise click.ClickException("All batch map generations failed.")
+
+ log.finished(f"Generated {succeeded}/{len(ideas)} maps in {output_dir}")
+
+
if __name__ == "__main__":
main()
diff --git a/main.py b/main.py
index 7167a28..ba71d1c 100644
--- a/main.py
+++ b/main.py
@@ -54,7 +54,7 @@
_to_rgba_tuple,
)
from map.constants import europe_coords, world_coords
-from map.functions import validate_temperature
+from map.functions import parse_ideas_content, slugify_prompt, validate_temperature
from flask import Flask, request, jsonify, send_file, render_template, Response
@@ -82,6 +82,7 @@ def _available_fonts():
app = Flask(__name__)
+app.config["MAX_CONTENT_LENGTH"] = 32 * 1024 * 1024
@app.route('/')
def main():
@@ -494,6 +495,202 @@ def generate():
return jsonify(resp_payload)
+@app.route('/api/models', methods=['POST'])
+def list_available_models():
+ """Return Gemini/Gemma models available for the active API key."""
+ data = request.get_json(silent=True) or {}
+ req_key = str(data.get("api_key") or "").strip()
+ env_key = (os.getenv("GEMINI_API_KEY") or "").strip()
+ key = req_key or env_key
+ if not key:
+ return jsonify({"status": "error", "error": "API key required.", "models": []}), 400
+ try:
+ from google import genai
+ client = genai.Client(api_key=key)
+ models: list[str] = []
+ for m in client.models.list():
+ name = getattr(m, "name", "") or ""
+ if name.startswith("models/"):
+ name = name[len("models/"):]
+ actions = getattr(m, "supported_actions", None) or []
+ if actions and "generateContent" not in actions:
+ continue
+ low = name.lower()
+ if not (low.startswith("gemini") or low.startswith("gemma")):
+ continue
+ if any(skip in low for skip in ("embedding", "imagen", "veo", "tts", "aqa", "robotics", "computer-use")):
+ continue
+ models.append(name)
+ return jsonify({"status": "success", "models": sorted(set(models), reverse=True)})
+ except Exception as err: # noqa: BLE001
+ return jsonify({"status": "error", "error": str(err), "models": []}), 500
+
+
+@app.route('/api/batch-template', methods=['GET'])
+def download_batch_template():
+ """Serve the downloadable batch CSV template."""
+ template_path = Path(__file__).resolve().parent / "batch_template.csv"
+ if not template_path.is_file():
+ return jsonify({"status": "error", "error": "batch_template.csv not found."}), 404
+ return send_file(
+ template_path,
+ mimetype="text/csv",
+ as_attachment=True,
+ download_name="batch_template.csv",
+ )
+
+
+@app.route('/api/generate_batch/', methods=['POST'])
+@app.route('/api/generate_batch', methods=['POST'])
+def generate_batch():
+ """Generate multiple maps from an uploaded .csv ideas file."""
+ if request.files and "file" in request.files:
+ uploaded = request.files["file"]
+ filename = uploaded.filename or ""
+ ideas_text = uploaded.read().decode("utf-8", errors="replace")
+ data: dict[str, object] = dict(request.form)
+ else:
+ data = request.get_json(silent=True) or {}
+ filename = str(data.get("filename") or "")
+ ideas_text = str(data.get("ideas_text") or "")
+
+ api_key = str(data.get("api_key") or "").strip() or None
+ if needs_api_key and not api_key:
+ return jsonify({
+ "status": "error",
+ "error": "API key required. Provide GEMINI_API_KEY via .env or the web form.",
+ }), 400
+
+ try:
+ ideas = parse_ideas_content(ideas_text, filename=filename)
+ except ValueError as err:
+ return jsonify({"status": "error", "error": str(err)}), 400
+
+ if not ideas:
+ return jsonify({"status": "error", "error": "No valid map ideas found in the uploaded file."}), 400
+
+ default_font, default_eop, default_gsm = _parse_render_params(data)
+ default_mode = str(data.get("mode") or "text").lower()
+ default_map_type = str(data.get("map_type") or "default").lower()
+ default_model = str(data.get("model") or "gemini-2.5-flash")
+ available_fonts = set(_available_fonts())
+
+ temperature_options: dict[str, object] = {}
+ if "temperature" in data and str(data["temperature"]).strip() != "":
+ try:
+ temperature_options["temperature"] = validate_temperature(data["temperature"])
+ except ValueError as err:
+ return jsonify({"status": "error", "error": str(err)}), 400
+
+ base_style_kwargs: dict[str, object] = {}
+ for style_key, kw_name in (
+ ("filling_txt", "filling_txt_override"),
+ ("filling_num", "filling_num_override"),
+ ("label_style", "label_style"),
+ ("auto_style", "auto_style"),
+ ("palette_theme", "palette_theme"),
+ ):
+ if style_key in data:
+ base_style_kwargs[kw_name] = data[style_key]
+
+ results: list[dict[str, object]] = []
+ succeeded = 0
+
+ for idx, idea in enumerate(ideas, start=1):
+ prompt = str(idea["prompt"])
+ item_mode = str(idea.get("mode") or default_mode).lower()
+ item_map_type = str(idea.get("map_type") or default_map_type).lower()
+ item_gsm = int(idea.get("gsm", default_gsm))
+ raw_eop = str(idea.get("extra_option") or default_eop or "none").lower()
+ item_eop = None if raw_eop in ("none", "") else raw_eop
+ item_model = str(idea.get("model") or default_model)
+ item_font = str(idea.get("font") or default_font)
+ if item_font not in available_fonts:
+ item_font = default_font
+
+ item_style_kwargs = dict(base_style_kwargs)
+ if "palette_theme" in idea:
+ item_style_kwargs["palette_theme"] = idea["palette_theme"]
+
+ custom_out = str(idea.get("output") or "").strip()
+ out_filename = Path(custom_out).name if custom_out else f"{idx:02d}_{slugify_prompt(prompt)}.png"
+ if not out_filename.lower().endswith(".png"):
+ out_filename += ".png"
+
+ try:
+ buffer = auto_map(
+ prompt=prompt,
+ mode=item_mode,
+ map_type=item_map_type,
+ size_mod=item_gsm,
+ optional_feature=item_eop,
+ model=item_model,
+ font_name=item_font,
+ show_result=False,
+ io_res=True,
+ api_key=api_key,
+ **temperature_options,
+ **item_style_kwargs,
+ )
+ except Exception as err: # noqa: BLE001
+ results.append({
+ "index": idx,
+ "prompt": prompt,
+ "filename": out_filename,
+ "status": "error",
+ "error": str(err),
+ })
+ continue
+
+ if buffer is None:
+ results.append({
+ "index": idx,
+ "prompt": prompt,
+ "filename": out_filename,
+ "status": "error",
+ "error": "Map generation failed.",
+ })
+ continue
+
+ encoded = base64.b64encode(buffer.getvalue()).decode("ascii")
+ item_payload: dict[str, object] = {
+ "index": idx,
+ "prompt": prompt,
+ "filename": out_filename,
+ "status": "success",
+ "image_url": f"data:image/png;base64,{encoded}",
+ "mode": item_mode,
+ "map_type": item_map_type,
+ "gsm": item_gsm,
+ "extra_option": item_eop or "none",
+ "model": item_model,
+ "font": item_font,
+ "palette_theme": item_style_kwargs.get("palette_theme", "auto"),
+ }
+ if temperature_options:
+ item_payload["temperature"] = temperature_options["temperature"]
+ 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["analysis"] = _build_analysis_from_ai(
+ ai_vals,
+ mode=item_mode,
+ palette_theme=str(item_style_kwargs.get("palette_theme") or "auto"),
+ topic=prompt,
+ render_meta=render_meta,
+ )
+ results.append(item_payload)
+ succeeded += 1
+
+ return jsonify({
+ "status": "success" if succeeded > 0 else "error",
+ "total": len(ideas),
+ "succeeded": succeeded,
+ "results": results,
+ }), (200 if succeeded > 0 else 500)
+
+
@app.route('/api/restyle_map/', methods=['POST'])
@app.route('/api/restyle_map', methods=['POST'])
def api_restyle_map():
@@ -864,4 +1061,4 @@ def _generate():
if __name__ == "__main__":
- app.run(host='0.0.0.0',debug=True)
+ app.run(host='0.0.0.0', debug=True)
diff --git a/map/auto_map.py b/map/auto_map.py
index 3abc873..1fdde10 100644
--- a/map/auto_map.py
+++ b/map/auto_map.py
@@ -160,8 +160,8 @@
"africa": 100,
"europe": 110,
"australia": 50,
- "south_America": 100,
- "north_America": 120,
+ "south_america": 100,
+ "north_america": 120,
}
@@ -534,11 +534,19 @@ def get_font(size):
used_txt_rules: dict[str, tuple[int, int, int, int]] = {}
used_num_rules: dict[tuple[int, int], tuple[int, int, int, int]] = {}
+ ai_answer_norm = {
+ str(k).strip().lower().replace(" ", "_").replace("-", "_"): v
+ for k, v in (ai_answer or {}).items()
+ }
+ if "oceania" in ai_answer_norm and "australia" not in ai_answer_norm:
+ ai_answer_norm["australia"] = ai_answer_norm["oceania"]
+
for index, (name, points) in enumerate(dict_.items(), start=1):
+ name_key = str(name).strip().lower().replace(" ", "_").replace("-", "_")
'''Number mode'''
if mode == 'number':
try:
- info = ai_answer[name]
+ info = ai_answer_norm[name_key]
color = (random.randint(80, 255), random.randint(80, 255), random.randint(80, 255), 255)
parsed_value = _parse_short_number(info)
num_value = int(round(parsed_value)) if parsed_value is not None else None
@@ -570,7 +578,7 @@ def get_font(size):
elif mode == 'text':
'''Text mode'''
- raw_info = ai_answer.get(name)
+ raw_info = ai_answer_norm.get(name_key)
info = "" if raw_info is None else str(raw_info).strip()
if not info:
log.info(f"No information for {name}, skipping")
@@ -602,7 +610,7 @@ def get_font(size):
if map_type == 'default' or map_type == 'world':
for coord in points:
# Tolerances are tuned to the shading in the source map images.
- if name == "south_America":
+ if name == "south_america":
thresh = 15
elif name == "asia":
thresh = 20
@@ -717,9 +725,20 @@ def get_font(size):
# merging layers
elif map_type == 'world':
+ log.info("Adding world relief + borders overlay")
+ relief = Image.open(Path(__file__).parent.parent / "./resources/maps/world_map_relief.png").convert("RGBA")
+ if relief.size != img.size:
+ relief = relief.resize(img.size)
+
+ # Reduce relief opacity to preserve the generated region colors beneath it.
+ _, _, _, a = relief.split()
+ relief.putalpha(a.point(_RELIEF_ALPHA_LUT))
+
+ result = Image.alpha_composite(img, relief)
+
borders = Image.open(Path(__file__).parent.parent / "./resources/maps/world_map_blured.png").convert("RGBA")
- result = Image.alpha_composite(img, borders)
+ result = Image.alpha_composite(result, borders)
result = Image.alpha_composite(result, text_layer)
else:
result = Image.alpha_composite(img, text_layer)
diff --git a/map/constants.py b/map/constants.py
index 1a102d2..a9942a8 100644
--- a/map/constants.py
+++ b/map/constants.py
@@ -66,8 +66,8 @@
(1783, 258),(2069, 477), (1663, 1038), (1663, 1062), (1708, 1092), (1698, 1089), (1776, 1091),(1663,853),(1875,1003),(1971,635),(1718,622)],
"australia": [(2683, 1633), (2838,1829), (3033,1859), (3086,1794)],
"africa": [(1637,1255), (1979, 1602)],
- "south_America": [(1017,1521),(1000, 1986)],
- "north_America": [(640,993), (613,1189), (632,1215), (893,1366), (892,1239), (929,1257), (975,1271), (1042,1003),
+ "south_america": [(1017,1521),(1000, 1986)],
+ "north_america": [(640,993), (613,1189), (632,1215), (893,1366), (892,1239), (929,1257), (975,1271), (1042,1003),
(1028,1016), (1057,1001), (1106,960), (864,711), (991,657), (787,497), (740,517), (653,566),
(545,502), (610,425), (735,414), (818,438), (634,328), (715,310), (762,323), (807,254),
(922,238), (1237,386), (1128,597), (227,853), (273,836),(273,836),(203,864),(185,876),(302,788)]
diff --git a/map/functions.py b/map/functions.py
index 33592e5..d2068a9 100644
--- a/map/functions.py
+++ b/map/functions.py
@@ -1,5 +1,8 @@
+import csv
+import io
import json
import math
+import re
import sys
from dotenv import load_dotenv
from google import genai
@@ -162,4 +165,130 @@ def load_filling():
return filling_txt, filling_num
+_SLUG_RE = re.compile(r'[^a-zA-Z0-9]+')
+
+BATCH_CSV_REQUIRED_COLUMNS: tuple[str, ...] = ("prompt",)
+BATCH_CSV_OPTIONAL_COLUMNS: tuple[str, ...] = (
+ "mode",
+ "map_type",
+ "gsm",
+ "extra_option",
+ "model",
+ "font",
+ "palette_theme",
+ "output",
+)
+BATCH_CSV_ALL_COLUMNS: tuple[str, ...] = BATCH_CSV_REQUIRED_COLUMNS + BATCH_CSV_OPTIONAL_COLUMNS
+_ALLOWED_MODES = frozenset({"text", "number"})
+_ALLOWED_MAP_TYPES = frozenset({"default", "flag", "world"})
+_ALLOWED_EXTRA_OPTIONS = frozenset({"none", "show_most_least", "short_form"})
+
+
+def slugify_prompt(prompt: str, max_len: int = 48) -> str:
+ """Convert a map prompt into a safe, concise filename stem."""
+ slug = _SLUG_RE.sub('_', prompt.strip().lower()).strip('_')
+ return (slug[:max_len].strip('_') or 'map')
+
+
+def parse_ideas_content(content: str, filename: str = "") -> list[dict[str, object]]:
+ """Parse and validate map ideas from a .csv file."""
+ if filename and Path(filename).suffix.lower() != ".csv":
+ raise ValueError("Only .csv files are supported for batch ideas.")
+
+ text = (content or "").lstrip("\ufeff").strip()
+ if not text:
+ raise ValueError("CSV file is empty.")
+
+ reader = csv.DictReader(io.StringIO(text))
+ if not reader.fieldnames:
+ raise ValueError("CSV file is missing a header row.")
+
+ headers = [str(h).strip().lower() for h in reader.fieldnames]
+ if any(not h for h in headers):
+ raise ValueError("CSV header contains an empty column name.")
+
+ unknown_cols = [h for h in headers if h not in BATCH_CSV_ALL_COLUMNS]
+ if unknown_cols:
+ raise ValueError(
+ f"Unknown CSV column(s): {', '.join(unknown_cols)}. "
+ f"Allowed columns: {', '.join(BATCH_CSV_ALL_COLUMNS)}."
+ )
+
+ missing_cols = [c for c in BATCH_CSV_REQUIRED_COLUMNS if c not in headers]
+ if missing_cols:
+ raise ValueError(f"Missing required CSV column(s): {', '.join(missing_cols)}.")
+
+ reader.fieldnames = headers
+ ideas: list[dict[str, object]] = []
+ for row_num, row in enumerate(reader, start=2):
+ if None in row:
+ raise ValueError(f"Row {row_num}: malformed CSV row (unexpected extra columns).")
+
+ prompt = str(row.get("prompt") or "").strip()
+ if not prompt:
+ raise ValueError(f"Row {row_num}: 'prompt' is required and cannot be empty.")
+
+ entry: dict[str, object] = {"prompt": prompt}
+
+ mode_val = str(row.get("mode") or "").strip().lower()
+ if mode_val:
+ if mode_val not in _ALLOWED_MODES:
+ raise ValueError(
+ f"Row {row_num}: invalid mode '{mode_val}'. Allowed: {', '.join(sorted(_ALLOWED_MODES))}."
+ )
+ entry["mode"] = mode_val
+
+ map_type_val = str(row.get("map_type") or "").strip().lower()
+ if map_type_val:
+ if map_type_val not in _ALLOWED_MAP_TYPES:
+ raise ValueError(
+ f"Row {row_num}: invalid map_type '{map_type_val}'. Allowed: {', '.join(sorted(_ALLOWED_MAP_TYPES))}."
+ )
+ entry["map_type"] = map_type_val
+
+ extra_val = str(row.get("extra_option") or "").strip().lower()
+ if extra_val:
+ if extra_val not in _ALLOWED_EXTRA_OPTIONS:
+ raise ValueError(
+ f"Row {row_num}: invalid extra_option '{extra_val}'. Allowed: {', '.join(sorted(_ALLOWED_EXTRA_OPTIONS))}."
+ )
+ entry["extra_option"] = extra_val
+
+ gsm_raw = str(row.get("gsm") or "").strip()
+ if gsm_raw:
+ try:
+ gsm_val = int(gsm_raw)
+ except ValueError as exc:
+ raise ValueError(
+ f"Row {row_num}: invalid gsm '{gsm_raw}'. Must be an integer between 1 and 100."
+ ) from exc
+ if gsm_val < 1 or gsm_val > 100:
+ raise ValueError(
+ f"Row {row_num}: invalid gsm '{gsm_raw}'. Must be an integer between 1 and 100."
+ )
+ entry["gsm"] = gsm_val
+
+ for key in ("model", "font", "palette_theme", "output"):
+ val = str(row.get(key) or "").strip()
+ if val:
+ entry[key] = val
+
+ ideas.append(entry)
+
+ if not ideas:
+ raise ValueError("CSV file contains no data rows.")
+
+ return ideas
+
+
+def load_ideas_from_file(file_path: str | Path) -> list[dict[str, object]]:
+ """Read and parse map ideas from a .csv file."""
+ path = Path(file_path)
+ if path.suffix.lower() != ".csv":
+ raise ValueError("Only .csv files are supported for batch ideas.")
+ content = path.read_text(encoding="utf-8")
+ return parse_ideas_content(content, filename=path.name)
+
+
+
diff --git a/resources/maps/world_map_relief.png b/resources/maps/world_map_relief.png
new file mode 100644
index 0000000..84b842f
Binary files /dev/null and b/resources/maps/world_map_relief.png differ
diff --git a/templates/index.html b/templates/index.html
index 0117f6e..a75dea5 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -92,6 +92,15 @@
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
+ @keyframes checkPopIn {
+ 0% { transform: scale(0.25) rotate(-25deg); opacity: 0; }
+ 65% { transform: scale(1.25) rotate(6deg); opacity: 1; }
+ 100% { transform: scale(1) rotate(0deg); opacity: 1; }
+ }
+ .check-pop-in {
+ display: inline-block;
+ animation: checkPopIn 0.36s cubic-bezier(0.22, 1, 0.36, 1) forwards;
+ }
.aurora-blob-1 {
animation: auroraFloat 18s ease-in-out infinite;
}
@@ -347,6 +356,43 @@
+
+
+
+ Ideas from CSV (.csv)
+
+
+
+
+
+
+
+
+
+
+ 0 maps ready
+
+
+
+
+
@@ -514,6 +560,10 @@