Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1880 lines (1631 loc) · 71.5 KB
/
Copy pathmain.py
File metadata and controls
1880 lines (1631 loc) · 71.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2025-2026 deltaaa00
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Flask web interface for AutoMap.
Serves the single-page UI in ``templates/index.html`` and exposes a small JSON
API used by that UI. Gemini and DeepSeek use separate keys from the environment
or ``.env``. If the selected provider has no configured key, ``/api/status``
reports it and the UI uses that provider's browser-saved key for the request.
"""
import base64
import io
import math
import os
import re
import threading
import time
from pathlib import Path
from PIL import Image, UnidentifiedImageError
import requests as _requests_module
# auto_map() loads fonts/maps via *relative* paths ("resources/fonts", ...),
# so the process must run from the AutoMap-cli project directory. Anchor the
# working directory here to make the web API independent of how it is launched.
BASE_DIR = Path(__file__).parent
os.chdir(BASE_DIR)
STORAGE_DIR = "/tmp/automap_storage"
DOWNLOADS = os.path.join(STORAGE_DIR, "downloads")
CUT_DIR = os.path.join(STORAGE_DIR, "cut")
os.makedirs(STORAGE_DIR, exist_ok=True)
os.makedirs(CUT_DIR, exist_ok=True)
from dotenv import dotenv_values
from map.auto_map import (
auto_map,
_auto_fill_from_ai,
_format_short_number,
_parse_short_number,
_parse_filling_overrides,
_resolve_theme_name,
_to_rgba_tuple,
)
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, 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
from web_ai_cache import ai_cache
FONTS_DIR = BASE_DIR / "resources" / "fonts"
env = BASE_DIR / ".env"
key = (os.environ.get("GEMINI_API_KEY") or "").strip()
if not key and env.is_file():
key = (dotenv_values(env).get("GEMINI_API_KEY") or "").strip()
needs_api_key = not key or key.startswith("your_")
class _PooledRequests:
"""``requests``-compatible facade that reuses one pooled Session.
Keeps keep-alive connections to the worker instead of opening a new TCP
connection per proxied call. Attribute access (exceptions, etc.) falls
through to the ``requests`` module, and tests can still patch
``main.requests.get``/``post``.
"""
def __init__(self):
self._session = _requests_module.Session()
self._orig_get = _requests_module.get
self._orig_post = _requests_module.post
def get(self, *args, **kwargs):
if _requests_module.get is not self._orig_get:
return _requests_module.get(*args, **kwargs)
return self._session.get(*args, **kwargs)
def post(self, *args, **kwargs):
if _requests_module.post is not self._orig_post:
return _requests_module.post(*args, **kwargs)
return self._session.post(*args, **kwargs)
def __getattr__(self, name):
return getattr(_requests_module, name)
requests = _PooledRequests()
WORKER_URL = (os.environ.get("YTDLP_URL") or "http://127.0.0.1:8080").rstrip('/')
def _available_fonts():
"""Return the list of usable font files from resources/fonts.
Mirrors ``cli._available_fonts`` so the API and the CLI agree on what is
selectable. Discovery is filename-based: only ``.ttf`` / ``.otf`` files
(case-insensitive extension) are returned, sorted for stable output.
"""
if not FONTS_DIR.is_dir():
return []
return sorted(
p.name for p in FONTS_DIR.iterdir() if p.suffix.lower() in (".ttf", ".otf")
)
app = Flask(__name__)
# Three 10 MiB materials (map, background and music) grow by 4/3 in JSON.
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024
from web_auth import init_web_auth
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():
"""Reject malformed or non-object JSON before endpoint field access."""
if request.path.startswith('/api/') and request.is_json:
data = request.get_json(silent=True)
if not isinstance(data, dict):
return jsonify(status='error', error='Request body must be a valid JSON object.'), 400
for name in ('api_key', 'url', 'provider', 'model'):
if data.get(name) is not None and not isinstance(data[name], str):
return jsonify(status='error', error=f'{name} must be a string.'), 400
@app.errorhandler(413)
def request_too_large(error):
return jsonify(status='error', error='Upload exceeds the total request size limit.'), 413
@app.route('/')
def main():
"""Serve the main single-page map generator UI."""
return render_template("index.html")
@app.route('/studio')
def studio():
"""Serve the dedicated Video Studio page (music downloader)."""
# Establish identity before the page starts parallel API requests.
youtube_uploads.owner()
youtube_uploads.csrf()
return render_template("video.html", title_fonts=_available_fonts())
@app.route('/api/video_title_preview', methods=['POST'])
def video_title_preview():
"""Proxy title/watermark/sticker preview requests to the yt-dlp render worker."""
data = request.get_json(silent=True) or {}
allowed_keys = (
'video_title',
'title_font',
'title_font_size',
'title_first_line_color',
'title_other_lines_color',
'title_uppercase',
'visual_effects',
'preview_kind',
'watermark_text',
'watermark_color',
'watermark_font',
'subscribe_text',
'sticker_kind',
'sticker_side',
'allow_remote_stickers',
)
try:
# Preview and final rendering share the worker's title styling options.
response = requests.post(
f'{WORKER_URL}/api/video_title_preview',
json={key: data[key] for key in allowed_keys if key in data},
timeout=15,
)
except requests.RequestException:
return jsonify(error='Title preview is unavailable. Please try again.'), 502
# Preserve the worker's image content type for successful preview responses.
return Response(response.content, status=response.status_code,
content_type=response.headers.get('Content-Type', 'application/json'))
@app.route('/api/fonts/')
@app.route('/api/fonts')
def api_fonts():
"""Expose the fonts discovered in resources/fonts.
Response:
{ "fonts": ["Bips.ttf", "DIN Condensed.ttf", ...], "count": 4 }
"""
fonts = _available_fonts()
return jsonify({"fonts": fonts, "count": len(fonts)})
@app.route('/api/codecs')
def api_codecs():
"""Ask the render worker which encoders its FFmpeg and hardware can use."""
try:
response = requests.get(f'{WORKER_URL}/api/codecs', timeout=20)
return jsonify(response.json()), response.status_code
except (requests.RequestException, ValueError):
return jsonify(error='Could not check render worker codecs. Use libx264 (CPU).'), 502
@app.route('/api/status')
def api_status():
"""Report whether the selected provider already has a server-side key.
Response:
{ "needs_api_key": true } -> the UI must ask the user for a key
"""
provider = request.args.get('provider', 'gemini')
if provider not in ('gemini', 'deepseek'):
return jsonify(status='error', error='Unknown AI provider.'), 400
required = needs_api_key if provider == 'gemini' else not _server_api_key(provider)
return jsonify({"needs_api_key": required})
def _server_api_key(provider):
"""Return the server-configured API key for ``provider``, if any."""
return configured_api_key(provider, dotenv_values(env) if env.is_file() else {})
def _request_provider(data):
"""Resolve and validate the AI provider from ``provider`` or ``model``."""
inferred = provider_for_model(data.get('model') or '')
provider = data.get('provider') or inferred
if provider not in ('gemini', 'deepseek'):
raise ValueError('Unknown AI provider.')
if data.get('model') and inferred != provider:
raise ValueError('The selected model belongs to a different AI provider.')
return provider
def _request_api_key(data, provider):
"""Resolve the API key for ``provider`` from server config or the request payload."""
supplied = str(data.get('api_key') or '').strip() or None
if provider == 'deepseek':
resolved = _server_api_key(provider) or supplied
else:
resolved = supplied
if not needs_api_key:
return resolved
if not resolved:
raise ValueError(f'API key required. Provide {provider_key_name(provider)} via .env or the web form.')
return resolved
_TRUTHY = {'1', 'true', 'yes', 'on'}
def _wants_refresh(data) -> bool:
"""Return True if the request asks to bypass the AI response cache."""
value = data.get('refresh_ai', data.get('refresh', False))
return value is True or str(value).strip().lower() in _TRUTHY
def _auto_map_with_ai_cache(*, refresh: bool, provider: str, api_key, **kwargs):
"""Call auto_map, reusing a cached AI answer for identical data requests.
Only request-affecting inputs form the key, so font/style/palette changes
reuse the answer. API keys only contribute a hash to the user scope.
Returns (buffer, cache_hit).
"""
temperature = kwargs.get('temperature')
identity = ''
try:
identity = str(session.get('web_identity', '') or '')
except RuntimeError:
identity = ''
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 ''),
map_type=str(kwargs.get('map_type') or ''),
model=str(kwargs.get('model') or ''),
provider=provider,
temperature=temperature,
web_search=bool(kwargs.get('web_search', False)),
max_search_requests=kwargs.get('max_search_requests', 5),
)
cache_key = ai_cache.make_key(scope, short_form=short_form, **base_fields)
cached = None if refresh else ai_cache.get(cache_key)
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 = 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('raw_ai_answer', meta.get('ai_answer')) if isinstance(meta, dict) else None
if isinstance(answer, dict):
if short_form:
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
def _build_analysis_from_ai(
ai_answer: dict[str, object],
mode: str = "auto",
palette_theme: str = "auto",
topic: str = "",
render_meta: dict[str, object] | None = None,
) -> dict[str, object]:
"""Build UI-friendly color rules and stats from AI map values or render metadata."""
vals = [v for v in ai_answer.values() if v is not None and str(v).strip() != ""]
num_vals: list[float] = []
for v in vals:
parsed = _parse_short_number(v)
if parsed is not None:
num_vals.append(parsed)
resolved_mode = mode if mode in ("number", "text") else (
"number" if vals and len(num_vals) >= max(1, int(len(vals) * 0.6)) else "text"
)
resolved_theme = (
str(render_meta.get("resolved_theme"))
if isinstance(render_meta, dict) and render_meta.get("resolved_theme")
else _resolve_theme_name(palette_theme, prompt=topic, mode=resolved_mode)
)
txt_dict: dict[str, tuple[int, int, int, int]] = {}
num_dict: dict[tuple[int, int], tuple[int, int, int, int]] = {}
if isinstance(render_meta, dict):
raw_txt = render_meta.get("used_txt") or render_meta.get("filling_txt")
if isinstance(raw_txt, dict) and raw_txt:
for k, v in raw_txt.items():
rgba = _to_rgba_tuple(v)
if rgba is not None:
txt_dict[str(k)] = rgba
raw_num = render_meta.get("used_num") or render_meta.get("filling_num")
if isinstance(raw_num, dict) and raw_num:
_, num_dict = _parse_filling_overrides(None, raw_num)
if not txt_dict and not num_dict:
txt_dict, num_dict = _auto_fill_from_ai(
ai_answer,
resolved_mode,
palette_theme=palette_theme,
prompt=topic,
)
ui_txt_rules = [
{"key": str(k), "hex": f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}", "alpha": c[3]}
for k, c in txt_dict.items()
]
ui_num_rules = [
{"low": lo, "high": hi, "hex": f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}", "alpha": c[3]}
for (lo, hi), c in num_dict.items()
]
default_label_style = {
"text_color": "#ffffff",
"stroke_color": "#090d16",
"stroke_width": 15,
"auto_fit": True,
"recommended_font": "Bips.ttf" if resolved_mode == "number" else "DIN Condensed.ttf",
"recommended_gsm": 15,
}
if isinstance(render_meta, dict) and isinstance(render_meta.get("label_style"), dict):
default_label_style.update(render_meta["label_style"])
return {
"detected_type": resolved_mode,
"resolved_mode": resolved_mode,
"resolved_theme": resolved_theme,
"filling_txt": {str(k): list(c) for k, c in txt_dict.items()},
"filling_num": {f"({lo}, {hi})": list(c) for (lo, hi), c in num_dict.items()},
"ui_txt_rules": ui_txt_rules,
"ui_num_rules": ui_num_rules,
"label_style": default_label_style,
"stats": {
"total_regions": len(vals),
"unique_values": len({str(v).strip().lower() for v in vals}),
"min_value": min(num_vals) if num_vals else None,
"max_value": max(num_vals) if num_vals else None,
"sample_values": [str(v) for v in vals[:8]],
},
}
def _inspect_uploaded_map_image(
image_data: object,
map_type: str = "default",
palette_theme: str = "auto",
) -> dict[str, object]:
"""Decode an uploaded map image and extract its sampled region color palette."""
if not isinstance(image_data, str) or not image_data.strip():
raise ValueError("Empty image data.")
raw_b64 = image_data.strip()
if "," in raw_b64 and raw_b64.lower().startswith("data:"):
header, raw_b64 = raw_b64.split(",", 1)
if not header.lower().startswith("data:image/"):
raise ValueError("Unsupported data URL media type.")
try:
decoded = base64.b64decode(raw_b64, validate=True)
except Exception as exc:
raise ValueError("Invalid base64 image payload.") from exc
if not decoded:
raise ValueError("Decoded image payload is empty.")
try:
with Image.open(io.BytesIO(decoded)) as opened:
img = opened.convert("RGBA")
except (UnidentifiedImageError, OSError, ValueError) as exc:
raise ValueError("Uploaded file is not a valid image.") from exc
width, height = img.size
if width < 8 or height < 8:
raise ValueError("Uploaded map image is too small to inspect.")
if map_type == "world":
ref_coords = world_coords
base_name = "world_map.png"
elif map_type == "world_countries":
from map.world_countries_coords import world_countries_coords
ref_coords = world_countries_coords
base_name = "world_countries_map.png"
else:
ref_coords = europe_coords
base_name = "default_map.png"
base_path = BASE_DIR / "resources" / "maps" / base_name
ref_w, ref_h = (2200, 1800)
if base_path.is_file():
try:
with Image.open(base_path) as ref_img:
ref_w, ref_h = ref_img.size
except OSError:
pass
px = img.load()
clusters: list[tuple[int, int, int, int]] = []
rule_colors: dict[str, tuple[int, int, int, int]] = {}
sampled_regions = 0
scale_x = width / max(1, ref_w)
scale_y = height / max(1, ref_h)
for points in ref_coords.values():
if not points:
continue
sampled_regions += 1
px_x, px_y = points[0]
sx = max(0, min(width - 1, int(round(px_x * scale_x))))
sy = max(0, min(height - 1, int(round(px_y * scale_y))))
samples: list[tuple[int, int, int, int]] = []
for dx in (-6, 0, 6):
cx = max(0, min(width - 1, sx + dx))
for dy in (-6, 0, 6):
cy = max(0, min(height - 1, sy + dy))
r, g, b, a = px[cx, cy]
if a >= 32 and (r + g + b) > 35:
samples.append((r, g, b, 255))
if not samples:
r, g, b, a = px[sx, sy]
samples.append((r, g, b, 255 if a >= 32 else a))
avg = (
int(round(sum(p[0] for p in samples) / len(samples))),
int(round(sum(p[1] for p in samples) / len(samples))),
int(round(sum(p[2] for p in samples) / len(samples))),
255,
)
matched: tuple[int, int, int, int] | None = None
for existing in clusters:
dist = abs(avg[0] - existing[0]) + abs(avg[1] - existing[1]) + abs(avg[2] - existing[2])
if dist <= 36:
matched = existing
break
if matched is None:
clusters.append(avg)
matched = avg
hex_label = f"#{matched[0]:02x}{matched[1]:02x}{matched[2]:02x}"
rule_colors.setdefault(hex_label, matched)
ui_txt_rules = [
{"key": k, "hex": k, "alpha": c[3]}
for k, c in rule_colors.items()
]
return {
"detected_type": "palette",
"resolved_mode": "palette",
"resolved_theme": palette_theme if palette_theme and palette_theme != "auto" else "sampled",
"inspection_only": True,
"filling_txt": {k: list(c) for k, c in rule_colors.items()},
"filling_num": {},
"ui_txt_rules": ui_txt_rules,
"ui_num_rules": [],
"label_style": {
"text_color": "#ffffff",
"stroke_color": "#090d16",
"stroke_width": 15,
"auto_fit": True,
"recommended_font": "Bips.ttf",
"recommended_gsm": 15,
},
"stats": {
"total_regions": sampled_regions,
"unique_values": len(rule_colors),
"min_value": None,
"max_value": None,
"sample_values": [],
},
}
def _parse_render_params(data: dict[str, object]) -> tuple[str, str | None, int]:
"""Validate font, normalize extra_option, and parse gsm safely."""
font_name = data.get("font")
if font_name not in _available_fonts():
font_name = "Bips.ttf"
extra_option = data.get("extra_option")
if extra_option in ("none", "", None):
extra_option = None
else:
extra_option = str(extra_option)
try:
gsm = int(data.get("gsm", 15))
except (TypeError, ValueError, OverflowError):
gsm = 15
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():
"""Generate a map from the JSON body and return it as a data URL.
Request JSON:
{ "topic", "mode", "map_type", "gsm", "extra_option", "model", "font", "temperature" }
Response JSON:
{ "status": "success", "command": "...", "image_url": "data:image/png;base64,..." }
"""
data = request.get_json(silent=True) or {}
# Optional user-supplied key (used only when .env has none).
try:
provider = _request_provider(data)
api_key = _request_api_key(data, provider)
except ValueError as error:
return jsonify(status='error', error=str(error)), 400
# Validate the requested font against what is actually on disk, otherwise
# auto_map would raise FileNotFoundError when loading the TrueType file.
font_name, extra_option, gsm = _parse_render_params(data)
temperature_options = {}
if 'temperature' in data:
try:
temperature_options['temperature'] = validate_temperature(data['temperature'])
except ValueError as error:
return jsonify(status='error', error=str(error)), 400
if "map_type" in data:
req_map_type = str(data["map_type"] or "").strip().lower()
if req_map_type not in _ALLOWED_MAP_TYPES:
return jsonify(
status='error',
error=f"Invalid map_type '{req_map_type}'. Allowed: {', '.join(sorted(_ALLOWED_MAP_TYPES))}.",
), 400
data["map_type"] = req_map_type
# Rebuild the equivalent CLI command for display only; it is never executed.
command = (
f"python cli.py make \"{data.get('topic', '')}\" "
f"-m {data.get('mode', 'text')} -mp {data.get('map_type', 'default')} "
f"-gsm {gsm} -eop {data.get('extra_option', 'none')} "
f"--model {data.get('model', AVAILABLE_MODELS[0])} --font \"{font_name}\""
)
if temperature_options:
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,
"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 (
("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:
style_kwargs[kw_name] = data[style_key]
try:
buffer, ai_cache_hit = _auto_map_with_ai_cache(
refresh=_wants_refresh(data),
provider=provider,
prompt=data['topic'],
mode=data['mode'],
map_type=data['map_type'],
size_mod=gsm,
optional_feature=extra_option,
model=data['model'],
font_name=font_name,
show_result=False,
io_res=True,
api_key=api_key,
**temperature_options,
**({"web_search": True, "max_search_requests": max(1, min(10, int(data.get("max_search_requests") or 5)))} if str(data.get("web_search") or "").strip().lower() in ("1", "true", "yes", "on") else {}),
**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')
resp_payload: dict[str, object] = {
"status": "success",
"command": command,
"image_url": f"data:image/png;base64,{encoded}",
"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)
resp_payload["analysis"] = _build_analysis_from_ai(
ai_vals,
mode=str(data.get("mode") or "auto"),
palette_theme=str(data.get("palette_theme") or "auto"),
topic=str(data.get("topic") or ""),
render_meta=render_meta,
)
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
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,
api_key=api_key,
with_params=with_params,
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
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."""
data = request.get_json(silent=True) or {}
try:
provider = _request_provider(data)
except ValueError as error:
return jsonify(status='error', error=str(error), models=[]), 400
if provider == 'deepseek':
try:
models = list_deepseek_models(_request_api_key(data, provider))
return jsonify(status='success', models=models)
except ValueError as error:
return jsonify(status='error', error=str(error), models=[]), 400
except AIServiceError as error:
return jsonify(status='error', error=str(error), models=[]), error.status_code
req_key = str(data.get("api_key") or "").strip()
env_key = _server_api_key('gemini') or ''
key = req_key or env_key
if not key:
return jsonify({"status": "error", "error": "API key required.", "models": []}), 400
try:
from google import genai
from google.genai import types
client = genai.Client(api_key=key, http_options=types.HttpOptions(
timeout=15_000, retry_options=types.HttpRetryOptions(attempts=1),
))
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",
"image", "nano-banana", "omni", "transcribe", "live", "native-audio", "decision",
)):
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/download_batch_zip', methods=['POST'])
def download_batch_zip():
"""Bundle generated batch maps into a single ZIP archive named by topic."""
import zipfile
data = request.get_json(silent=True) or {}
items = data.get("items") or []
if not isinstance(items, list) or not items:
return jsonify({"status": "error", "error": "No maps provided."}), 400
buf = io.BytesIO()
used_names: set[str] = set()
added = 0
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for idx, item in enumerate(items, start=1):
if not isinstance(item, dict):
continue
image_url = str(item.get("image_url") or "").strip()
prompt = str(item.get("prompt") or "").strip()
if not image_url.startswith('data:image/png;base64,'):
continue
try:
image_bytes = base64.b64decode(image_url.split(',', 1)[1], validate=True)
with Image.open(io.BytesIO(image_bytes)) as image:
if image.format != 'PNG':
continue
image.verify()
except (ValueError, OSError):
continue
base = re.sub(r"[^\w\-]+", "_", prompt.strip().replace(" ", "_")).strip("_") if prompt else f"map_{idx:02d}"
if not base:
base = f"map_{idx:02d}"
count = 1
arc_name = f"{base}.png"
while arc_name in used_names:
count += 1
arc_name = f"{base}_{count}.png"
used_names.add(arc_name)
zf.writestr(arc_name, image_bytes)
added += 1
if added == 0:
return jsonify({"status": "error", "error": "No valid map files found to archive."}), 404
buf.seek(0)
return send_file(
buf,
mimetype="application/zip",
as_attachment=True,
download_name="automap_batch.zip",
)
@app.route('/api/parse_batch_csv', methods=['POST'])
def parse_batch_csv():
"""Parse an uploaded .csv ideas file and return the normalized idea rows."""
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")
else:
data = request.get_json(silent=True) or {}
filename = str(data.get("filename") or "")
ideas_text = str(data.get("ideas_text") or "")
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
return jsonify({"status": "success", "ideas": ideas, "total": len(ideas)})
@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 "")
try:
provider = _request_provider(data)
api_key = _request_api_key(data, provider)
except ValueError as error:
return jsonify(status='error', error=str(error)), 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").strip().lower()
if default_map_type not in _ALLOWED_MAP_TYPES:
return jsonify({
"status": "error",
"error": f"Invalid map_type '{default_map_type}'. Allowed: {', '.join(sorted(_ALLOWED_MAP_TYPES))}.",
}), 400
default_model = str(data.get("model") or ('deepseek-flash' if provider == 'deepseek' else AVAILABLE_MODELS[0]))
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:
item_provider = provider_for_model(item_model)