"""Anki flashcard generator for Polish rivers. Generates Anki-compatible flashcard decks with maps showing rivers highlighted on a Poland map. """ from __future__ import annotations import argparse import hashlib from io import BytesIO import multiprocessing as mp from pathlib import Path import random import sys import tempfile from typing import TYPE_CHECKING import genanki import geopandas as gpd import matplotlib as mpl mpl.use("Agg") # Non-interactive backend for multiprocessing import matplotlib.pyplot as plt sys.path.insert(0, str(Path(__file__).parent.parent)) from geo_data import get_poland_boundary, get_polish_rivers if TYPE_CHECKING: from collections.abc import Sequence from matplotlib.figure import Figure RIVER_COLOR = "#2980B9" # Dark blue for rivers NEIGHBOR_COLOR = "#EAECEE" # Light gray for neighboring areas def create_river_map( river_gdf: gpd.GeoDataFrame, poland_boundary: gpd.GeoDataFrame, ) -> Figure: """Create a map showing Poland with one river highlighted. Rivers that extend beyond Poland show an extended view. """ fig, ax = plt.subplots(figsize=(10, 12)) ax.set_aspect("equal") ax.axis("off") fig.patch.set_alpha(0) ax.patch.set_alpha(0) # Get Poland bounds poland_bounds = poland_boundary.total_bounds river_bounds = river_gdf.total_bounds # Check if river extends beyond Poland extends_beyond = ( river_bounds[0] < poland_bounds[0] or river_bounds[1] < poland_bounds[1] or river_bounds[2] > poland_bounds[2] or river_bounds[3] > poland_bounds[3] ) if extends_beyond: # Calculate extended bounds with some padding min_x = min(poland_bounds[0], river_bounds[0]) - 0.2 min_y = min(poland_bounds[1], river_bounds[1]) - 0.2 max_x = max(poland_bounds[2], river_bounds[2]) + 0.2 max_y = max(poland_bounds[3], river_bounds[3]) + 0.2 # Draw background for extended area (neighboring countries) ax.fill( [min_x, max_x, max_x, min_x, min_x], [min_y, min_y, max_y, max_y, min_y], color=NEIGHBOR_COLOR, alpha=0.3, ) # Plot Poland as a plain gray shape poland_boundary.plot(ax=ax, color="#D5D8DC", alpha=0.6) poland_boundary.boundary.plot(ax=ax, color="#2C3E50", linewidth=1) # Plot the river river_gdf.plot(ax=ax, color=RIVER_COLOR, linewidth=3, alpha=0.9) if extends_beyond: ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) else: # Set bounds to Poland ax.set_xlim(poland_bounds[0], poland_bounds[2]) ax.set_ylim(poland_bounds[1], poland_bounds[3]) return fig def generate_river_image_bytes( river_gdf: gpd.GeoDataFrame, poland_boundary: gpd.GeoDataFrame, ) -> bytes: """Generate a river map image as bytes.""" fig = create_river_map(river_gdf, poland_boundary) buf = BytesIO() fig.savefig(buf, format="png", bbox_inches="tight", dpi=150) plt.close(fig) buf.seek(0) return buf.read() # Global variables for multiprocessing (set via initializer) _mp_poland_boundary: gpd.GeoDataFrame | None = None def _init_worker(poland_geojson: str) -> None: """Initialize worker process with shared data.""" global _mp_poland_boundary # noqa: PLW0603 _mp_poland_boundary = gpd.read_file(poland_geojson) def _render_single_river(args: tuple[str, str]) -> tuple[str, bytes]: """Render a single river image (worker function). Args: args: Tuple of (river_name, river_geojson_str). Returns: Tuple of (river_name, image_bytes). """ river_name, river_geojson = args river_gdf = gpd.read_file(river_geojson) assert _mp_poland_boundary is not None # noqa: S101 image_data = generate_river_image_bytes(river_gdf, _mp_poland_boundary) return river_name, image_data def generate_anki_package( rivers: gpd.GeoDataFrame, poland_boundary: gpd.GeoDataFrame, deck_name: str = "Polish Rivers", ) -> genanki.Package: """Generate Anki package for Polish rivers.""" model_id_hash = hashlib.md5(f"polish_rivers_{deck_name}".encode()) # noqa: S324 model_id = int(model_id_hash.hexdigest()[:8], 16) card_css = """ .card { font-family: Arial, sans-serif; font-size: 24px; text-align: center; color: #333; background-color: #fff; } .card.night_mode { color: #eee; background-color: #2f2f2f; } .map-container { display: flex; justify-content: center; align-items: center; min-height: 80vh; } .map-container img { max-width: 100%; max-height: 80vh; object-fit: contain; } .answer-text { font-size: 32px; font-weight: bold; margin-top: 20px; color: #2C3E50; } .card.night_mode .answer-text { color: #ECF0F1; } .info-text { font-size: 18px; color: #7F8C8D; margin-top: 10px; } .card.night_mode .info-text { color: #BDC3C7; } """ my_model = genanki.Model( model_id, "Polish River Model", fields=[ {"name": "RiverMap"}, {"name": "RiverName"}, {"name": "Length"}, ], templates=[ { "name": "Card 1", "qfmt": '