mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-27 10:49:05 +01:00
Use real Warsaw district boundaries from OpenStreetMap instead of mock circles
Co-authored-by: kuhyx <147418882+kuhyx@users.noreply.github.com>
This commit is contained in:
parent
b200d8957f
commit
92a306b731
@ -5,11 +5,16 @@ Generate Anki flashcards for learning the 18 districts (dzielnice) of Warsaw, Po
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Generates flashcards for all 18 Warsaw districts
|
- Generates flashcards for all 18 Warsaw districts
|
||||||
- Front of card: Map showing only the district in question with its borders highlighted
|
- **Uses real district boundaries from OpenStreetMap data**
|
||||||
|
- Front of card: Map showing the full city with only the target district's border highlighted in bold
|
||||||
- Back of card: District name in Polish
|
- Back of card: District name in Polish
|
||||||
- Self-contained .apkg file with embedded images
|
- Self-contained .apkg file with embedded images
|
||||||
- Compatible with AnkiWeb and AnkiDroid
|
- Compatible with AnkiWeb and AnkiDroid
|
||||||
|
|
||||||
|
## Data Source
|
||||||
|
|
||||||
|
District boundaries are sourced from [andilabs/warszawa-dzielnice-geojson](https://github.com/andilabs/warszawa-dzielnice-geojson), which provides accurate OpenStreetMap-based GeoJSON data for all Warsaw districts.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
Install dependencies using your preferred method:
|
Install dependencies using your preferred method:
|
||||||
@ -18,23 +23,23 @@ Install dependencies using your preferred method:
|
|||||||
```bash
|
```bash
|
||||||
pyenv install 3.10 # or later
|
pyenv install 3.10 # or later
|
||||||
pyenv shell 3.10
|
pyenv shell 3.10
|
||||||
pip install matplotlib genanki
|
pip install matplotlib genanki geopandas
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using pipx
|
### Using pipx
|
||||||
```bash
|
```bash
|
||||||
pipx install --python python3.10 matplotlib genanki
|
pipx install --python python3.10 matplotlib genanki geopandas
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using system package manager (Arch Linux)
|
### Using system package manager (Arch Linux)
|
||||||
```bash
|
```bash
|
||||||
sudo pacman -S python-matplotlib
|
sudo pacman -S python-matplotlib python-geopandas
|
||||||
pip install genanki
|
pip install genanki
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using pip directly
|
### Using pip directly
|
||||||
```bash
|
```bash
|
||||||
pip install matplotlib genanki
|
pip install matplotlib genanki geopandas
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|||||||
@ -35,27 +35,19 @@ class TestDistricts:
|
|||||||
"""Test that we have exactly 18 Warsaw districts."""
|
"""Test that we have exactly 18 Warsaw districts."""
|
||||||
assert len(WARSAW_DISTRICTS) == 18
|
assert len(WARSAW_DISTRICTS) == 18
|
||||||
|
|
||||||
def test_all_districts_have_names(self) -> None:
|
def test_all_districts_are_strings(self) -> None:
|
||||||
"""Test that all districts have non-empty names."""
|
"""Test that all district entries are strings."""
|
||||||
for district in WARSAW_DISTRICTS:
|
for district in WARSAW_DISTRICTS:
|
||||||
assert district.name
|
assert isinstance(district, str)
|
||||||
assert isinstance(district.name, str)
|
assert len(district) > 0
|
||||||
assert len(district.name) > 0
|
|
||||||
|
|
||||||
def test_all_districts_have_valid_coordinates(self) -> None:
|
|
||||||
"""Test that all districts have coordinates in valid range."""
|
|
||||||
for district in WARSAW_DISTRICTS:
|
|
||||||
assert 0 <= district.x <= 1
|
|
||||||
assert 0 <= district.y <= 1
|
|
||||||
|
|
||||||
def test_districts_are_unique(self) -> None:
|
def test_districts_are_unique(self) -> None:
|
||||||
"""Test that all district names are unique."""
|
"""Test that all district names are unique."""
|
||||||
names = [d.name for d in WARSAW_DISTRICTS]
|
assert len(WARSAW_DISTRICTS) == len(set(WARSAW_DISTRICTS))
|
||||||
assert len(names) == len(set(names))
|
|
||||||
|
|
||||||
def test_known_districts_present(self) -> None:
|
def test_known_districts_present(self) -> None:
|
||||||
"""Test that all known Warsaw districts are in the list."""
|
"""Test that all known Warsaw districts are in the list."""
|
||||||
district_names = {d.name for d in WARSAW_DISTRICTS}
|
district_set = set(WARSAW_DISTRICTS)
|
||||||
# Check all 18 districts
|
# Check all 18 districts
|
||||||
expected_districts = {
|
expected_districts = {
|
||||||
"Bemowo",
|
"Bemowo",
|
||||||
@ -63,8 +55,8 @@ class TestDistricts:
|
|||||||
"Bielany",
|
"Bielany",
|
||||||
"Mokotów",
|
"Mokotów",
|
||||||
"Ochota",
|
"Ochota",
|
||||||
"Praga-Południe",
|
"Praga Południe", # Note: space, not hyphen
|
||||||
"Praga-Północ",
|
"Praga Północ", # Note: space, not hyphen
|
||||||
"Rembertów",
|
"Rembertów",
|
||||||
"Śródmieście",
|
"Śródmieście",
|
||||||
"Targówek",
|
"Targówek",
|
||||||
@ -77,7 +69,7 @@ class TestDistricts:
|
|||||||
"Wola",
|
"Wola",
|
||||||
"Żoliborz",
|
"Żoliborz",
|
||||||
}
|
}
|
||||||
assert district_names == expected_districts
|
assert district_set == expected_districts
|
||||||
|
|
||||||
|
|
||||||
class TestCreateDistrictMap:
|
class TestCreateDistrictMap:
|
||||||
|
|||||||
@ -2,7 +2,8 @@
|
|||||||
"""Anki flashcard generator for Warsaw districts.
|
"""Anki flashcard generator for Warsaw districts.
|
||||||
|
|
||||||
Generates Anki-compatible flashcard decks with maps showing individual
|
Generates Anki-compatible flashcard decks with maps showing individual
|
||||||
Warsaw districts (dzielnice) with their borders.
|
Warsaw districts (dzielnice) with their borders using real boundary data
|
||||||
|
from OpenStreetMap.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
# Generate Anki cards for all Warsaw districts
|
# Generate Anki cards for all Warsaw districts
|
||||||
@ -24,10 +25,10 @@ from io import BytesIO
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import random
|
import random
|
||||||
import sys
|
import sys
|
||||||
from typing import TYPE_CHECKING, NamedTuple
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
import genanki
|
import genanki
|
||||||
import matplotlib.patches as mpatches
|
import geopandas as gpd
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -36,115 +37,85 @@ if TYPE_CHECKING:
|
|||||||
from matplotlib.figure import Figure
|
from matplotlib.figure import Figure
|
||||||
|
|
||||||
|
|
||||||
class District(NamedTuple):
|
# Path to GeoJSON file with Warsaw district boundaries
|
||||||
"""A Warsaw district with its approximate position."""
|
GEOJSON_PATH = Path(__file__).parent / "warszawa-dzielnice.geojson"
|
||||||
|
|
||||||
name: str # Polish name
|
|
||||||
x: float # Approximate x coordinate (0-1)
|
|
||||||
y: float # Approximate y coordinate (0-1)
|
|
||||||
|
|
||||||
|
|
||||||
# Warsaw districts (dzielnice) - 18 total
|
def load_district_data() -> gpd.GeoDataFrame:
|
||||||
# Coordinates are approximate relative positions for visualization
|
"""Load Warsaw district boundaries from GeoJSON.
|
||||||
WARSAW_DISTRICTS: list[District] = [
|
|
||||||
District("Bemowo", 0.15, 0.55),
|
Returns:
|
||||||
District("Białołęka", 0.75, 0.7),
|
GeoDataFrame with district boundaries.
|
||||||
District("Bielany", 0.35, 0.75),
|
"""
|
||||||
District("Mokotów", 0.45, 0.3),
|
if not GEOJSON_PATH.exists():
|
||||||
District("Ochota", 0.3, 0.45),
|
msg = f"GeoJSON file not found at {GEOJSON_PATH}"
|
||||||
District("Praga-Południe", 0.7, 0.35),
|
raise FileNotFoundError(msg)
|
||||||
District("Praga-Północ", 0.7, 0.6),
|
|
||||||
District("Rembertów", 0.85, 0.5),
|
gdf = gpd.read_file(GEOJSON_PATH)
|
||||||
District("Śródmieście", 0.5, 0.5),
|
# Filter out the "Warszawa" entry (whole city) and keep only districts
|
||||||
District("Targówek", 0.65, 0.8),
|
return gdf[gdf["name"] != "Warszawa"].copy()
|
||||||
District("Ursus", 0.05, 0.4),
|
|
||||||
District("Ursynów", 0.5, 0.15),
|
|
||||||
District("Wawer", 0.8, 0.25),
|
|
||||||
District("Wesoła", 0.9, 0.45),
|
|
||||||
District("Wilanów", 0.6, 0.1),
|
|
||||||
District("Włochy", 0.15, 0.3),
|
|
||||||
District("Wola", 0.35, 0.6),
|
|
||||||
District("Żoliborz", 0.45, 0.7),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def create_district_map(district: District, *, highlight_only: bool = True) -> Figure:
|
def get_district_names() -> list[str]:
|
||||||
|
"""Get list of all district names from GeoJSON data.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Sorted list of district names.
|
||||||
|
"""
|
||||||
|
gdf = load_district_data()
|
||||||
|
return sorted(gdf["name"].tolist())
|
||||||
|
|
||||||
|
|
||||||
|
# Load district names from actual data
|
||||||
|
WARSAW_DISTRICTS = get_district_names()
|
||||||
|
|
||||||
|
|
||||||
|
def create_district_map(district_name: str) -> Figure:
|
||||||
"""Create a map showing Warsaw districts with one district highlighted.
|
"""Create a map showing Warsaw districts with one district highlighted.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
district: The district to highlight.
|
district_name: Name of the district to highlight.
|
||||||
highlight_only: If True, show only the highlighted district's border.
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A matplotlib Figure object.
|
A matplotlib Figure object.
|
||||||
"""
|
"""
|
||||||
fig, ax = plt.subplots(figsize=(8, 8))
|
# Load all district data
|
||||||
ax.set_xlim(0, 1)
|
gdf = load_district_data()
|
||||||
ax.set_ylim(0, 1)
|
|
||||||
|
# Create figure
|
||||||
|
fig, ax = plt.subplots(figsize=(10, 10))
|
||||||
ax.set_aspect("equal")
|
ax.set_aspect("equal")
|
||||||
ax.axis("off")
|
ax.axis("off")
|
||||||
|
|
||||||
# Draw all districts as points if not highlight_only
|
# Plot all districts with light gray borders
|
||||||
if not highlight_only:
|
gdf.boundary.plot(ax=ax, color="lightgray", linewidth=0.5, alpha=0.5)
|
||||||
for dist in WARSAW_DISTRICTS:
|
|
||||||
if dist.name != district.name:
|
|
||||||
circle = mpatches.Circle(
|
|
||||||
(dist.x, dist.y),
|
|
||||||
0.03,
|
|
||||||
color="lightgray",
|
|
||||||
alpha=0.3,
|
|
||||||
)
|
|
||||||
ax.add_patch(circle)
|
|
||||||
|
|
||||||
# Draw the highlighted district with a border
|
# Find and highlight the target district
|
||||||
# Create a polygon approximating the district area
|
target = gdf[gdf["name"] == district_name]
|
||||||
# For simplicity, we'll use a circle with border
|
if len(target) == 0:
|
||||||
highlighted = mpatches.Circle(
|
msg = f"District {district_name} not found in data"
|
||||||
(district.x, district.y),
|
raise ValueError(msg)
|
||||||
0.08,
|
|
||||||
facecolor="white",
|
|
||||||
edgecolor="black",
|
|
||||||
linewidth=3,
|
|
||||||
)
|
|
||||||
ax.add_patch(highlighted)
|
|
||||||
|
|
||||||
# Add some neighboring circles to show context (lighter borders)
|
# Plot the highlighted district with bold black border
|
||||||
# Find nearest districts
|
target.boundary.plot(ax=ax, color="black", linewidth=3)
|
||||||
distances = [
|
|
||||||
(
|
|
||||||
d,
|
|
||||||
((d.x - district.x) ** 2 + (d.y - district.y) ** 2) ** 0.5,
|
|
||||||
)
|
|
||||||
for d in WARSAW_DISTRICTS
|
|
||||||
if d.name != district.name
|
|
||||||
]
|
|
||||||
distances.sort(key=lambda x: x[1])
|
|
||||||
|
|
||||||
# Draw 3-4 nearest neighbors with light borders
|
# Set tight layout
|
||||||
for neighbor, _ in distances[:4]:
|
ax.set_xlim(gdf.total_bounds[0], gdf.total_bounds[2])
|
||||||
neighbor_circle = mpatches.Circle(
|
ax.set_ylim(gdf.total_bounds[1], gdf.total_bounds[3])
|
||||||
(neighbor.x, neighbor.y),
|
|
||||||
0.08,
|
|
||||||
facecolor="white",
|
|
||||||
edgecolor="lightgray",
|
|
||||||
linewidth=1,
|
|
||||||
alpha=0.5,
|
|
||||||
)
|
|
||||||
ax.add_patch(neighbor_circle)
|
|
||||||
|
|
||||||
return fig
|
return fig
|
||||||
|
|
||||||
|
|
||||||
def generate_district_image_bytes(district: District) -> bytes:
|
def generate_district_image_bytes(district_name: str) -> bytes:
|
||||||
"""Generate a district map image as bytes.
|
"""Generate a district map image as bytes.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
district: The district to visualize.
|
district_name: Name of the district to visualize.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
PNG image data as bytes.
|
PNG image data as bytes.
|
||||||
"""
|
"""
|
||||||
fig = create_district_map(district)
|
fig = create_district_map(district_name)
|
||||||
|
|
||||||
# Save to bytes buffer
|
# Save to bytes buffer
|
||||||
buf = BytesIO()
|
buf = BytesIO()
|
||||||
@ -199,19 +170,19 @@ def generate_anki_package(
|
|||||||
media_files = []
|
media_files = []
|
||||||
|
|
||||||
# Generate notes for each district
|
# Generate notes for each district
|
||||||
for district in WARSAW_DISTRICTS:
|
for district_name in WARSAW_DISTRICTS:
|
||||||
# Generate image
|
# Generate image
|
||||||
image_data = generate_district_image_bytes(district)
|
image_data = generate_district_image_bytes(district_name)
|
||||||
|
|
||||||
# Create unique filename
|
# Create unique filename
|
||||||
filename = f"{district.name.replace('-', '_').replace(' ', '_')}.png"
|
filename = f"{district_name.replace(' ', '_').replace('-', '_')}.png"
|
||||||
|
|
||||||
# Create note
|
# Create note
|
||||||
note = genanki.Note(
|
note = genanki.Note(
|
||||||
model=my_model,
|
model=my_model,
|
||||||
fields=[
|
fields=[
|
||||||
f'<img src="{filename}">',
|
f'<img src="{filename}">',
|
||||||
district.name,
|
district_name,
|
||||||
],
|
],
|
||||||
tags=["geography", "warsaw", "poland"],
|
tags=["geography", "warsaw", "poland"],
|
||||||
)
|
)
|
||||||
@ -272,6 +243,7 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
sys.stdout.write(
|
sys.stdout.write(
|
||||||
f"Generating flashcards for {num_districts} Warsaw districts...\n"
|
f"Generating flashcards for {num_districts} Warsaw districts...\n"
|
||||||
)
|
)
|
||||||
|
sys.stdout.write("Using real district boundaries from OpenStreetMap data.\n")
|
||||||
|
|
||||||
# Generate the package
|
# Generate the package
|
||||||
package = generate_anki_package(args.deck_name)
|
package = generate_anki_package(args.deck_name)
|
||||||
|
|||||||
15849
python_pkg/warsaw_districts/warszawa-dzielnice.geojson
Normal file
15849
python_pkg/warsaw_districts/warszawa-dzielnice.geojson
Normal file
File diff suppressed because it is too large
Load Diff
@ -2,6 +2,7 @@ beautifulsoup4>=4.0
|
|||||||
berserk>=0.13
|
berserk>=0.13
|
||||||
bottle>=0.12
|
bottle>=0.12
|
||||||
genanki>=0.13
|
genanki>=0.13
|
||||||
|
geopandas>=1.0
|
||||||
lxml>=5.0
|
lxml>=5.0
|
||||||
|
|
||||||
# Optional dependencies for specific scripts (needed for full pylint analysis)
|
# Optional dependencies for specific scripts (needed for full pylint analysis)
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user