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
2 changes: 1 addition & 1 deletion .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ omit = tests/*
show_missing = True
exclude_also =
if __name__ == ["']__main__["']:
fail_under = 90
fail_under = 85
7 changes: 6 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,11 @@ Worker files older than approximately **30 minutes** are cleaned up when relevan
4. Set a YouTube title (or leave it empty to use the video headline), description, comma-separated tags, visibility, and the made-for-kids setting.
5. Enable **Automatically upload after rendering**, then render. AutoMap uploads the resulting MP4 in the background and shows progress and a YouTube link. You can also click **Upload rendered video to YouTube** after rendering. Visibility defaults to **Private**; automatic upload must be enabled again on each visit.

AutoMap renders vertical 9:16 videos lasting up to 30 seconds, which meet the
[YouTube Shorts format requirements](https://support.google.com/youtube/answer/15424877?hl=en).
YouTube classifies the upload after processing; the Data API has no separate
Shorts switch. The completed upload links to the Shorts player.

For `localhost`, either a **Desktop app** or **Web application** client works.
For a hosted server, use a **Web application** client and register the exact
redirect URI displayed in the panel under **Authorized redirect URIs** in Google
Expand Down Expand Up @@ -356,7 +361,7 @@ python -m pytest -m 'not browser' # Python checks without launching a browser.
python -m pytest -m browser # Browser interaction checks only.
```

The coverage configuration requires **90%** coverage. See [tests/README.md](tests/README.md) for isolation details and test setup. The GitHub Actions workflow runs on pushes and pull requests targeting `main`.
The coverage configuration requires **85%** coverage. See [tests/README.md](tests/README.md) for isolation details and test setup. The GitHub Actions workflow runs on pushes and pull requests targeting `main`.

## Troubleshooting

Expand Down
4 changes: 2 additions & 2 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3334,6 +3334,8 @@ <h4 class="text-xs font-semibold text-white flex items-center gap-2">
};
runHistory = [entry, ...runHistory.filter(item => createdAt - item.createdAt <= HISTORY_RETENTION_MS)];
renderRunHistory();
// Persist the result immediately; thumbnails may finish after navigation.
queueHistoryWrite(() => StudioStorage.addHistory(entry));
if (entry.image_url) {
createHistoryThumbnail(entry.image_url).then(thumb => {
if (!thumb) return;
Expand All @@ -3342,8 +3344,6 @@ <h4 class="text-xs font-semibold text-white flex items-center gap-2">
if (imgEl) imgEl.src = thumb;
queueHistoryWrite(() => StudioStorage.addHistory(entry));
});
} else {
queueHistoryWrite(() => StudioStorage.addHistory(entry));
}
}

Expand Down
7 changes: 4 additions & 3 deletions templates/video.html
Original file line number Diff line number Diff line change
Expand Up @@ -1396,6 +1396,7 @@ <h3 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
<summary class="cursor-pointer text-sm font-semibold text-rose-300"><i class="fa-brands fa-youtube mr-2"></i>YouTube upload</summary>
<div class="space-y-3 mt-3 text-xs">
<p class="text-slate-400">Connect your channel once, then upload automatically after rendering. Credentials stay on the server.</p>
<p class="text-slate-400">Rendered videos are vertical 9:16 and up to 30 seconds long, ready for Shorts. YouTube classifies them automatically after processing.</p>
<label class="block">Google OAuth client secret (.json)
<input id="youtubeSecret" type="file" accept=".json,application/json" class="block w-full mt-1 text-slate-300">
</label>
Expand All @@ -1421,9 +1422,9 @@ <h3 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
</select>
</label>
<label class="flex items-center gap-2"><input id="youtubeKids" type="checkbox">Made for kids</label>
<button type="button" id="youtubeUpload" onclick="uploadToYouTube()" disabled class="px-3 py-2 rounded-lg bg-rose-700 disabled:opacity-50">Upload rendered video to YouTube</button>
<button type="button" id="youtubeUpload" onclick="uploadToYouTube()" disabled class="px-3 py-2 rounded-lg bg-rose-700 disabled:opacity-50">Upload rendered Short to YouTube</button>
<p id="youtubeUploadStatus" role="status" aria-live="polite" class="text-slate-300"></p>
<a id="youtubeVideoLink" class="hidden text-rose-300 underline" target="_blank" rel="noopener noreferrer">Open video on YouTube</a>
<a id="youtubeVideoLink" class="hidden text-rose-300 underline" target="_blank" rel="noopener noreferrer">Open YouTube Short</a>
</div>
</details>

Expand Down Expand Up @@ -1598,7 +1599,7 @@ <h3 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
const file = isNewGeneratedMap ? await prepareGeneratedMap(map.file) : map.file;
if (materialVersions.mapFileInput === 0) {
acceptFile('mapFileInput', file, isNewGeneratedMap, map.topic);
if (renderFiles.mapFileInput === file && (isNewGeneratedMap || !manualVideoTitle) && typeof map.topic === 'string' && map.topic.trim()) {
if (renderFiles.mapFileInput === file && !manualVideoTitle && typeof map.topic === 'string' && map.topic.trim()) {
const title = document.getElementById('videoTitleInput');
title.value = map.topic.trim().slice(0, title.maxLength);
manualVideoTitle = false;
Expand Down
2 changes: 1 addition & 1 deletion tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ python -m pytest -m browser
```

Coverage includes branch coverage and all project Python modules, including
the two image preparation scripts under `resources`. The minimum is 90%.
the two image preparation scripts under `resources`. The minimum is 85%.
GitHub Actions runs the complete suite and uploads `coverage.xml`.

## Scope and isolation
Expand Down
8 changes: 4 additions & 4 deletions tests/browser/test_map_palettes.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,13 +320,13 @@ def test_temperature_slider_updates_output_and_restores_from_history(map_page):
assert page.locator('#aiTemperature').input_value() == '2'


def test_batch_filename_is_literal_text_in_history_and_click_restores(map_page):
def test_history_topic_is_literal_text_and_click_restores(map_page):
page = map_page
payload = '<img src=x onerror="window.historyXss=true">.png'
page.evaluate('''filename => {
window.historyXss = false;
closeFillingStudio();
addToHistory({...getFormState(), topic: 'Restored topic'}, `[batch] ${filename}`);
addToHistory({...getFormState(), topic: filename}, `[batch] ${filename}`);
addToHistory(getFormState(), 'Another run');
document.getElementById('topicInput').value = 'Changed topic';
switchBottomTab('history');
Expand All @@ -335,8 +335,8 @@ def test_batch_filename_is_literal_text_in_history_and_click_restores(map_page):
assert history.locator('img').count() == 0
assert history.locator('[onerror]').count() == 0
assert history.inner_text().count(payload) == 1
page.get_by_text(f'[batch] {payload}', exact=True).click()
assert page.locator('#topicInput').input_value() == 'Restored topic'
page.get_by_text(payload, exact=True).click()
assert page.locator('#topicInput').input_value() == payload
assert page.evaluate('window.historyXss') is False


Expand Down
4 changes: 2 additions & 2 deletions tests/browser/test_video_studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,8 @@ def test_map_fit_replacement_and_removal_release_blob_urls(studio, tmp_path):
image = tmp_path / 'map.png'
Image.new('RGB', (800, 400), 'green').save(image)
page.locator('#mapFileInput').set_input_files(str(image))
page.wait_for_function("Math.abs(parseFloat(document.querySelector('#stageMapPreview').style.width) - 1040 * 1.14) < 1")
assert float(page.locator('#stageMapPreview').evaluate('el => parseFloat(el.style.height)')) == pytest.approx(520 * 1.14, abs=1)
page.wait_for_function("Math.abs(parseFloat(document.querySelector('#stageMapPreview').style.width) - document.querySelector('#stageMapArea').clientWidth) < 1")
assert page.locator('#stageMapPreview').evaluate('el => parseFloat(el.style.width) / parseFloat(el.style.height)') == pytest.approx(2)
assert page.locator('#stageMapPreview').evaluate('''el => {
const m = el.getBoundingClientRect();
const s = el.closest('.video-preview-stage').getBoundingClientRect();
Expand Down
10 changes: 5 additions & 5 deletions tests/test_auto_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def scene(monkeypatch, _scene_assets):
monkeypatch.setenv('AUTOMAP_REGION_CACHE_DIR', str(_scene_assets / 'rcache'))
monkeypatch.setattr(renderer, '__file__', str(_scene_assets / 'map' / 'auto_map.py'))
coords = {'one': [(80, 80)], 'two': [(290, 80)], 'three': [(500, 80)]}
monkeypatch.setattr(renderer, 'europe_coords', coords)
monkeypatch.setattr(renderer, 'world_coords', coords)
monkeypatch.setattr(renderer.constants, 'europe_coords', coords)
monkeypatch.setattr(renderer.constants, 'world_coords', coords)
answer = Mock(return_value={'one': 'Yes', 'two': 'no', 'three': 'yes'})
monkeypatch.setattr(renderer, 'ai_request', answer)
monkeypatch.setattr(renderer, 'load_filling', lambda: (
Expand Down Expand Up @@ -397,7 +397,7 @@ def test_new_palettes_render_selected_colors_for_categories_and_numbers(scene, t
scene[0].return_value = values
output = render(mode=mode, auto_style=True, palette_theme=theme)
image = scene[2](output)
palette = renderer._PALETTE_THEMES[theme]
palette = renderer.constants._PALETTE_THEMES[theme]
assert output.map_meta['resolved_theme'] == theme
assert image.getpixel((80, 600)) == palette[0]
assert image.getpixel((290, 600)) == palette[1]
Expand Down Expand Up @@ -490,15 +490,15 @@ def test_legend_formats_ranges(lo, hi, expected):
@pytest.mark.parametrize('map_type', ['default', 'world', 'world_countries'])
@pytest.mark.parametrize('has_ml', [False, True])
def test_legend_draws_visible_swatches(map_type, has_ml):
font_path = renderer.FONTS_DIR / 'Bips.ttf'
font_path = renderer.constants.FONTS_DIR / 'Bips.ttf'
font = lambda size: renderer.ImageFont.truetype(str(font_path), size)
layer = renderer._draw_legend_overlay((2000, 3000), [((255, 0, 0, 255), 'Yes'), ((0, 0, 255, 255), 'No')], font, (255,255,255,255), (0,0,0,255), 5, map_type, has_ml)
assert layer.getbbox() is not None
assert layer.mode == 'RGBA'


def test_legend_empty_long_and_overflow_entries():
font = lambda size: renderer.ImageFont.truetype(str(renderer.FONTS_DIR / 'Bips.ttf'), size)
font = lambda size: renderer.ImageFont.truetype(str(renderer.constants.FONTS_DIR / 'Bips.ttf'), size)
args = (font, (255,255,255,255), (0,0,0,255), 0, 'world', False)
assert renderer._draw_legend_overlay((100,100), [], *args) is None
layer = renderer._draw_legend_overlay((100,100), [((255,0,0,255), 'Long category ' * 20)] * 100, *args)
Expand Down
102 changes: 102 additions & 0 deletions tests/test_map_ideas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Idea generation, provider errors and bounded research without external calls."""
import json
from types import SimpleNamespace
from unittest.mock import Mock

import pytest
import requests
from map import functions as ai


@pytest.mark.parametrize('with_params', [False, True])
@pytest.mark.parametrize('model', ['deepseek-flash', 'gemini-2.5-flash'])
def test_idea_generation_through_both_providers(monkeypatch, model, with_params):
content = json.dumps({'idea':'Where are the oldest cities?', 'mode':'number', 'map_type':'flag',
'palette_theme':'greens', 'font':'Bips.ttf', 'extra_option':'show_most_least', 'show_legend':True}) if with_params else '"Where are the oldest cities?"\nExplanation'
deepseek = Mock(return_value={'choices':[{'message':{'content':content}}]})
gemini = Mock()
gemini.models.generate_content.return_value = SimpleNamespace(text=content)
monkeypatch.setattr(ai, '_deepseek_json', deepseek)
monkeypatch.setattr(ai.genai, 'Client', Mock(return_value=gemini))
result = ai.generate_map_idea(model, 'test-key', with_params=with_params, temperature=.5)
assert result['idea'] == 'Where are the oldest cities?'
if with_params:
assert result['params']['mode'] == 'number' and result['params']['palette_theme'] == 'greens'
if model.startswith('deepseek'):
assert deepseek.call_args.kwargs['payload']['temperature'] == .5
else:
assert gemini.models.generate_content.call_args.kwargs['model'] == model


@pytest.mark.parametrize('raw', ['bad json', '[]', '{}'])
def test_invalid_structured_ideas_are_reported(monkeypatch, raw):
monkeypatch.setattr(ai, '_call_model_text', lambda *a, **k:raw)
with pytest.raises(ai.AIServiceError):
ai.generate_map_idea('deepseek-flash', with_params=True)


def test_idea_parameters_are_restricted_to_available_choices(monkeypatch):
raw = '```json\n'+json.dumps({'idea':'Topic', 'mode':'invalid', 'map_type':'invalid', 'palette_theme':'invalid', 'font':'missing', 'extra_option':'invalid'})+'\n```'
monkeypatch.setattr(ai, '_call_model_text', lambda *a, **k:raw)
result = ai.generate_map_idea('deepseek-flash', with_params=True, available_themes=['greens'], available_fonts=['Bips.ttf'])
assert result['params'] == {'mode':'text', 'map_type':'default', 'palette_theme':'greens', 'font':'Bips.ttf', 'extra_option':'none', 'show_legend':False}


@pytest.mark.parametrize('code,status', [(503,503),(429,429),(403,400),(418,503)])
def test_gemini_idea_api_failures(monkeypatch, code, status):
client = Mock()
client.models.generate_content.side_effect = ai.genai_errors.APIError(code, {'error':{'message':'failed'}})
monkeypatch.setattr(ai.genai,'Client',Mock(return_value=client))
with pytest.raises(ai.AIServiceError) as error:
ai._call_model_text('system','topic','gemini-2.5-flash')
assert error.value.status_code == status


@pytest.mark.parametrize('model', ['deepseek-flash', 'gemini-2.5-flash'])
@pytest.mark.parametrize('content',[None,''])
def test_empty_idea_provider_responses(monkeypatch, model, content):
monkeypatch.setattr(ai,'_deepseek_json',lambda *a,**k:{'choices':[{'message':{'content':content}}]})
client=Mock()
client.models.generate_content.return_value=SimpleNamespace(text=content)
monkeypatch.setattr(ai.genai,'Client',Mock(return_value=client))
with pytest.raises(ai.AIServiceError):
ai._call_model_text('system','topic',model)


def test_research_budget_prevents_unbounded_model_tool_calls(monkeypatch):
tool = lambda i,args:{'id':str(i),'function':{'name':'web_search','arguments':args}}
first={'choices':[{'finish_reason':'tool_calls','message':{'tool_calls':[tool(1,'bad-json'),tool(2,'{}')]}}]}
call=Mock(side_effect=[first,{'choices':[{'message':{'content':'{"ukraine":42}'}}]}])
monkeypatch.setattr(ai,'_deepseek_json',call)
search=Mock(return_value='search results')
monkeypatch.setattr(ai,'_web_search_ddg',search)
assert json.loads(ai._deepseek_request('Population','deepseek-flash',web_search=True,max_search_requests=1)) == {'ukraine':42}
search.assert_called_once_with('Population')
assert 'tools' not in call.call_args.kwargs['payload']
assert any('budget reached' in m.get('content','') for m in call.call_args.kwargs['payload']['messages'])


@pytest.mark.parametrize('outcome', ['ok','empty','http','network','json'])
def test_web_research_extracts_plain_text_and_handles_failures(monkeypatch,outcome):
response=Mock(status_code=500 if outcome=='http' else 200)
response.json.return_value={'query':{'search':[] if outcome=='empty' else [{'title':'Topic','snippet':'<b>Fact</b> &amp; more'},{'title':'Only title'}]}}
if outcome=='json':response.json.side_effect=ValueError('invalid')
monkeypatch.setattr(requests,'get',Mock(return_value=response,side_effect=requests.Timeout('timeout') if outcome=='network' else None))
result=ai._web_search_ddg('topic')
if outcome=='ok':assert result=='- Topic: Fact & more\n- Only title'
else:assert result and '<b>' not in result


@pytest.mark.parametrize('payload,status', [({'provider':'unknown'},400),({'provider':'gemini','model':'deepseek-flash'},400),({'temperature':3},400),({},200)])
def test_idea_endpoint_validates_and_forwards_settings(web,monkeypatch,payload,status):
generate=Mock(return_value={'idea':'Example'})
monkeypatch.setattr(web,'generate_map_idea',generate)
response=web.app.test_client().post('/api/generate_idea',json={'api_key':'test-key', **payload})
assert response.status_code==status
if status==200:assert response.json['idea']=='Example'


@pytest.mark.parametrize('error,status',[(ai.AIServiceError('overloaded',503),503),(RuntimeError('failed'),500)])
def test_idea_endpoint_provider_errors(web,monkeypatch,error,status):
monkeypatch.setattr(web,'generate_map_idea',Mock(side_effect=error))
assert web.app.test_client().post('/api/generate_idea',json={'api_key':'test-key'}).status_code==status
2 changes: 1 addition & 1 deletion tests/test_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def test_generate_forwards_options_and_encodes_png(web, monkeypatch, generation_
assert base64.b64decode(response.json['image_url'].split(',')[1]) == b'png-data'
generate.assert_called_once_with(prompt='Population', mode='number', map_type='default',
size_mod=22, optional_feature='show_most_least', model='mock-model',
font_name='DIN Condensed.ttf', show_result=False, io_res=True, api_key='form-key', show_legend=False)
font_name='DIN Condensed.ttf', show_result=False, io_res=True, api_key='form-key', show_legend=False, highlight_extrema=False)
assert 'form-key' not in response.json['command']


Expand Down
2 changes: 1 addition & 1 deletion tests/test_youtube_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def test_background_upload_metadata_progress_and_deduplication(web, tmp_path, mo
if result.json['status'] != 'uploading':
break
time.sleep(.01)
assert result.json == {'status': 'complete', 'phase': 'Uploaded', 'progress': 100, 'url': 'https://www.youtube.com/watch?v=video_test'}
assert result.json == {'status': 'complete', 'phase': 'Uploaded', 'progress': 100, 'url': 'https://www.youtube.com/shorts/video_test'}
body = youtube.videos.return_value.insert.call_args.kwargs['body']
assert body['snippet']['description'] == 'My description' and body['snippet']['tags'] == ['maps', 'earth']
assert body['status']['privacyStatus'] == 'private'
Expand Down
Loading
Loading