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
457 changes: 438 additions & 19 deletions main.py

Large diffs are not rendered by default.

465 changes: 409 additions & 56 deletions map/auto_map.py

Large diffs are not rendered by default.

21 changes: 11 additions & 10 deletions map/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,19 @@ def ai_request(prompt: str, mode: str, ai_model: str, api_key: str | None = None

try:
# Models may wrap otherwise valid JSON in a Markdown code fence.
json_style = request.strip().replace("```json", "").replace("```", "").strip()
json_style = (
request.strip()
.removeprefix("```json")
.removeprefix("```python")
.removeprefix("```")
.removesuffix("```")
.strip()
)
country_dict = json.loads(json_style)

except json.JSONDecodeError:
try:
json_style = request.strip().replace("```python", "").replace("```", "").strip()
country_dict = json.loads(json_style)

except json.JSONDecodeError:
_error(f"Failed to convert into dictionary. Result {json_style}")
print("Result:", json_style)
return None
_error(f"Failed to convert into dictionary. Result {json_style}")
print("Result:", json_style)
return None
except (AttributeError, TypeError) as e:
_error("AI response parsing error", str(e))
return None
Expand Down
9 changes: 3 additions & 6 deletions map/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,7 @@ def spinner(message: str = "Working..."):
and collapses into a success/failure line when the block finishes.
"""
with console.status(f"[bold cyan]{message}", spinner="dots") as status:
try:
# Keep the status active for the caller's block; errors propagate
# after the status context has had a chance to stop the animation.
yield status
except Exception:
raise
# Keep the status active for the caller's block; errors propagate
# after the status context has had a chance to stop the animation.
yield status

17 changes: 7 additions & 10 deletions resources/othr/white_pixels_cleaning.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
from PIL import Image

# Run from the asset directory: this utility overwrites map.png in place.
img = Image.open("map.png").convert("RGBA")

pixels = img.load()
for x in range(img.width):
for y in range(img.height):
r, g, b, a = pixels[x, y]
_OPAQUE_ALPHA_LUT: list[int] = [255 if a == 255 else 0 for a in range(256)]

# Remove partially transparent edge pixels while preserving opaque artwork.
if a < 255:
pixels[x, y] = (r, g, b, 0)
# Run from the asset directory: this utility overwrites map.png in place.
with Image.open("map.png") as opened:
img = opened.convert("RGBA")

# Remove partially transparent edge pixels in C via LUT while preserving opaque artwork.
r, g, b, a = img.split()
img = Image.merge("RGBA", (r, g, b, a.point(_OPAQUE_ALPHA_LUT)))
img.save("map.png")
553 changes: 478 additions & 75 deletions templates/index.html

Large diffs are not rendered by default.

1,116 changes: 1,102 additions & 14 deletions templates/video.html

Large diffs are not rendered by default.

145 changes: 145 additions & 0 deletions tests/test_auto_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,148 @@ def test_font_objects_are_cached_within_render(scene, monkeypatch):
monkeypatch.setattr(renderer.ImageFont, 'truetype', load_font)
render()
assert load_font.call_count == 1


def test_auto_fill_from_ai_detects_numbers_and_words():
txt_rules, num_rules = renderer._auto_fill_from_ai(
{'ukraine': 38, 'poland': 37, 'germany': 84, 'estonia': 1},
mode='number',
)
assert not txt_rules
assert len(num_rules) >= 2

txt_rules_w, num_rules_w = renderer._auto_fill_from_ai(
{'ukraine': '6 Dec', 'russia': '19 Dec', 'netherlands': '5 Dec'},
mode='text',
)
assert not num_rules_w
assert '6 Dec' in txt_rules_w
assert '19 Dec' in txt_rules_w
assert txt_rules_w['6 Dec'] != txt_rules_w['19 Dec']

# Short-form numeric strings in text mode should be grouped into gradient buckets,
# not assigned a distinct color per unique string.
short_txt, _ = renderer._auto_fill_from_ai(
{f'r{i}': f'{i}k' for i in range(1, 21)},
mode='text',
)
assert len(set(short_txt.values())) <= 5
assert short_txt['1k'] == short_txt['2k']
assert short_txt['1k'] != short_txt['20k']


def test_auto_map_applies_request_color_and_label_overrides(scene, monkeypatch):
answer, _, real_open = scene
answer.return_value = {'one': 'CustomLabel', 'two': 'OtherLabel', 'three': ''}
orig_text = ImageDraw.ImageDraw.text
text_calls = []

def spy_text(self, *args, **kwargs):
text_calls.append((args, kwargs))
return orig_text(self, *args, **kwargs)

monkeypatch.setattr(ImageDraw.ImageDraw, 'text', spy_text)

buf = render(
filling_txt_override={'CustomLabel': [12, 34, 56, 255], 'OtherLabel': [65, 43, 21, 255]},
label_style={'text_color': '#ff1122', 'stroke_color': '#010203', 'stroke_width': 9, 'auto_fit': True},
auto_style=False,
palette_theme='emerald',
)
image = real_open(buf)
assert image.getpixel((80, 600)) == (12, 34, 56, 255)
assert image.getpixel((290, 600)) == (65, 43, 21, 255)
assert len(text_calls) == 2
assert text_calls[0][1]['fill'] == (255, 17, 34, 255)
assert text_calls[0][1]['stroke_fill'] == (1, 2, 3, 255)
assert text_calls[0][1]['stroke_width'] == 9
assert buf.map_meta['label_style']['text_color'] == '#ff1122'
assert buf.map_meta['used_txt']['CustomLabel'] == [12, 34, 56, 255]


def test_numeric_auto_style_ignores_untouched_four_ui_defaults(scene):
answer, _, real_open = scene
answer.return_value = {'one': 1, 'two': 50, 'three': 99}
untouched_ui_num = {
'(0, 100)': [56, 189, 248, 255],
'(100, 1000)': [99, 102, 241, 255],
'(1000, 10000)': [168, 85, 247, 255],
'(10000, 100000000)': [244, 63, 94, 255],
}
buf = render(
mode='number',
filling_num_override=untouched_ui_num,
auto_style=True,
palette_theme='auto',
)
image = real_open(buf)
assert len(buf.map_meta['used_num']) == 3
assert image.getpixel((80, 600)) != image.getpixel((290, 600))
assert image.getpixel((290, 600)) != image.getpixel((500, 600))


def test_auto_map_restyle_override_skips_ai_request(scene):
answer, _, real_open = scene
buf = render(
ai_answer_override={'one': 'Alpha', 'two': 'Beta', 'three': 'Alpha'},
filling_txt_override={'Alpha': [10, 200, 100, 255], 'Beta': [200, 10, 100, 255]},
auto_style=False,
)
answer.assert_not_called()
image = real_open(buf)
assert image.getpixel((80, 600)) == (10, 200, 100, 255)
assert image.getpixel((290, 600)) == (200, 10, 100, 255)


@pytest.mark.parametrize('theme', ['auto', 'oceanic'])
def test_auto_style_preserves_explicit_text_rule_case_insensitively(scene, theme):
scene[0].return_value = {'one': 'Yes', 'two': 'Other', 'three': 'yes'}
output = render(auto_style=True, palette_theme=theme,
filling_txt_override={' YES ': '#123456'})
image = scene[2](output)
assert image.getpixel((80, 600)) == (18, 52, 86, 255)
assert image.getpixel((500, 600)) == (18, 52, 86, 255)
assert image.getpixel((290, 600)) != (18, 52, 86, 255)


def test_explicit_theme_replaces_untouched_default_text_rules(scene):
scene[0].return_value = {'one': 'Yes', 'two': 'No', 'three': 'Tea'}
defaults = {'yes': '#2ecc71', 'no': '#e74c3c', 'tea': '#10b981', 'coffee': '#f59e0b'}
output = render(auto_style=True, palette_theme='oceanic', filling_txt_override=defaults)
image = scene[2](output)
assert image.getpixel((80, 600)) == (56, 189, 248, 255)
assert image.getpixel((290, 600)) == (14, 165, 233, 255)


def test_numeric_auto_style_keeps_manual_range_and_fills_unmatched_values(scene):
scene[0].return_value = {'one': 1, 'two': 50, 'three': 99}
output = render(mode='number', auto_style=True,
filling_num_override={'(0, 10)': '#123456'})
image = scene[2](output)
assert image.getpixel((80, 600)) == (18, 52, 86, 255)
assert image.getpixel((290, 600)) != (160, 160, 160, 255)
assert image.getpixel((500, 600)) != (160, 160, 160, 255)
assert len(output.map_meta['used_num']) == 3


@pytest.mark.parametrize('stroke,expected', [('bad', 15), (None, 15), (-1, 0), (100, 40)])
def test_label_stroke_validation_keeps_rendering_usable(scene, stroke, expected):
output = render(label_style={'stroke_width': stroke})
assert scene[2](output).format == 'PNG'
assert output.map_meta['label_style']['stroke_width'] == expected


@pytest.mark.parametrize('map_type', ['default', 'world'])
def test_long_labels_auto_fit_without_changing_their_text(scene, monkeypatch, map_type):
label = 'A very long region label'
scene[0].return_value = {'one': label}
text = Mock()
monkeypatch.setattr(ImageDraw.ImageDraw, 'text', text)
render(map_type=map_type, label_style={'auto_fit': False})
original_size = text.call_args.kwargs['font'].size
render(map_type=map_type, label_style={'auto_fit': True})
assert text.call_args.args[1] == label
assert text.call_args.kwargs['font'].size < original_size



99 changes: 99 additions & 0 deletions tests/test_map_styling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Color configuration and AI-value analysis without external services."""
import importlib

import pytest


renderer = importlib.import_module('map.auto_map')


@pytest.mark.parametrize('value,expected', [
(' 2.5M ', 2_500_000), ('1B', 1_000_000_000), ('-1.5k', -1500),
('1,234', 1234), ('1 234', 1234), (0, 0),
('', None), ('NaN', None), ('inf', None), ('unknown', None),
(True, None), (None, None),
])
def test_short_number_parsing_accepts_measurements_not_missing_or_nonfinite_values(value, expected):
assert renderer._parse_short_number(value) == expected


@pytest.mark.parametrize('topic,mode,expected', [
('Christmas holidays', 'text', 'festive'),
('Winter temperatures', 'number', 'ocean'),
('Summer temperatures', 'number', 'sunset'),
('Population', 'number', 'viridis'),
('Favorite drink', 'text', 'auto'),
])
def test_automatic_theme_follows_topic_and_data_type(topic, mode, expected):
assert renderer._resolve_theme_name('auto', topic, mode) == expected


def test_explicit_theme_takes_precedence_over_topic():
assert renderer._resolve_theme_name(' OCEANIC ', 'Christmas', 'number') == 'oceanic'


def test_color_overrides_accept_hex_rgb_and_rgba_and_ignore_invalid_rules():
txt, num = renderer._parse_filling_overrides({
' Yes ': '#12Ab34', 'No': [300, -5, 25, 500], 'RGB': [1, 2, 3],
'': [1, 2, 3], 'bad': ['not-a-channel', 2, 3], 'missing': None,
}, {
'(0, 10)': '#112233', (10, 20): [4, 5, 6, 128],
'invalid': [1, 2, 3], '(20,)': [1, 2, 3], '(20, 30)': None,
})
assert txt == {'Yes': (18, 171, 52, 255), 'No': (255, 0, 25, 255),
'RGB': (1, 2, 3, 255)}
assert num == {(0, 10): (17, 34, 51, 255), (10, 20): (4, 5, 6, 128)}


def test_numeric_rule_list_accepts_supported_colors_and_skips_incomplete_entries():
_, rules = renderer._parse_filling_overrides(None, [
{'low': '0', 'high': '10', 'hex': '#112233'},
{'low': 10, 'high': 20, 'color': [4, 5, 6, 128]},
None, {'low': 20, 'high': 30, 'color': None},
{'low': 20, 'hex': '#112233'},
{'low': 'bad', 'high': 30, 'hex': '#112233'},
])
assert rules == {(0, 10): (17, 34, 51, 255), (10, 20): (4, 5, 6, 128)}


@pytest.mark.parametrize('value', [None, 'not-a-color', '#xyz'])
def test_invalid_label_color_uses_safe_default(value):
fallback = (255, 255, 255, 255)
assert renderer._hex_to_rgba(value, fallback) == fallback


def test_numeric_palette_covers_every_value_when_more_than_five_values_exist():
values = {'region' + str(i): i for i in range(-3, 12)}
txt, rules = renderer._auto_fill_from_ai(values, 'number', palette_theme='heatmap')
assert not txt
assert len(rules) == 5
for value in values.values():
matches = [color for (lo, hi), color in rules.items() if lo < value <= hi]
assert len(matches) == 1
assert len(set(rules.values())) == 5


def test_short_form_text_palette_keeps_unknown_labels_as_separate_categories():
rules, _ = renderer._auto_fill_from_ai(
{'a': '1k', 'b': '2k', 'c': '3k', 'd': 'unknown'}, 'text')
assert set(rules) == {'1k', '2k', '3k', 'unknown'}
assert rules['1k'] != rules['3k']
assert rules['unknown'] not in (rules['1k'], rules['3k'])


def test_analysis_preserves_actual_render_rules_and_skips_malformed_metadata(web):
analysis = web._build_analysis_from_ai({'a': '2.5M', 'b': 10}, mode='number', render_meta={
'resolved_theme': 'heatmap',
'used_txt': {'Yes': '#112233', 'invalid': None},
'used_num': {'(0, 10)': [1, 2, 3, 128], (10, 3_000_000): '#445566',
'broken': [1, 2, 3], '(1,)': [1, 2, 3], '(4, 5)': None},
'label_style': {'text_color': '#abcdef', 'stroke_width': 9},
})
assert analysis['resolved_theme'] == 'heatmap'
assert analysis['filling_txt'] == {'Yes': [17, 34, 51, 255]}
assert analysis['filling_num'] == {
'(0, 10)': [1, 2, 3, 128], '(10, 3000000)': [68, 85, 102, 255]}
assert analysis['label_style']['text_color'] == '#abcdef'
assert analysis['label_style']['stroke_width'] == 9
assert analysis['stats']['min_value'] == 10
assert analysis['stats']['max_value'] == 2_500_000
Loading
Loading