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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ See [`docs/versioning.md`](docs/versioning.md) for what the numbers mean and
included, can open the profile.
- The privacy page names the site by `APP_URL` instead of a fixed
`maply.ws04.cc`, so moving the domain needs no text change.
- `harvest.py` counts why a region gave no frame (no frame since 2018, no
panorama, none at quality 0.7, too narrow, too soft, and so on), per country
of the plan, and prints it with `<out>/rejects.json`. A run that yields
nothing in a country now says at which step. `scripts/curation/test_curation.py`
checks offline which parts of Ukraine the plan covers and what the counter
reports.

### Added

Expand Down
35 changes: 34 additions & 1 deletion scripts/curation/harvest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,14 @@
A panorama softer than MAPLY_MIN_SHARP (see sharpness) is passed over for
another frame, and MAPLY_AVOID keeps the batch clear of the other pool's
places (see avoid.py).

A region that gives no frame says why: every pass over a tile or a frame is
counted by step, per country of the plan (per region for the built-in list),
printed at the end and written to <out>/rejects.json. So a country that yields
nothing shows whether the tiles hold no frames, no panoramas, only panoramas
under the quality bar, or only narrow or soft ones.
"""
import io, json, math, os, random, sys, time, urllib.request, concurrent.futures as cf
import collections, io, json, math, os, random, sys, threading, time, urllib.request, concurrent.futures as cf
import mapbox_vector_tile
from PIL import Image, ImageDraw, ImageFilter, ImageFont, ImageStat
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
Expand All @@ -37,6 +43,13 @@
# Gaussian blur of 1.5 px brings every frame tried below 280.
MIN_SHARP = float(os.environ.get("MAPLY_MIN_SHARP", "350"))
MIN_WIDTH = int(os.environ.get("MAPLY_MIN_WIDTH", "2048"))
REJECTS = collections.defaultdict(collections.Counter)
_rejects_lock = threading.Lock()

def count(key, why):
with _rejects_lock:
REJECTS[key][why] += 1

LAPLACE = ImageFilter.Kernel((3, 3), (0, 1, 0, 1, -4, 1, 0, 1, 0), scale=1, offset=128)

def get(url, timeout=60):
Expand Down Expand Up @@ -89,16 +102,21 @@ def harvest(region):
inner, kind = region.get("inner", 0), region.get("kind", "city")
else:
(name, lat, lon, km), inner, kind = region, 0, "city"
key = (region.get("country") if isinstance(region, dict) else None) or name
# Roads far from town are often empty: more tries.
for _ in range(12 if kind == "nature" or PANO_ONLY else 5):
tlat, tlon = random_point(lat, lon, km, inner)
x, y = tile_of(tlat, tlon)
try:
t = mapbox_vector_tile.decode(get(f"https://tiles.mapillary.com/maps/vtp/mly1_public/2/14/{x}/{y}?access_token={TOKEN}"))
except Exception:
count(key, "tile not loaded")
continue
raw = [f for f in t.get("image", {}).get("features", [])
if (f["properties"].get("captured_at") or 0) >= MIN_TS]
if not raw:
count(key, "no frame since 2018 in the tile")
tile_panos = sum(1 for f in raw if f["properties"].get("is_pano"))
if kind == "town":
# The frames nearest the town's centre, not the bypass road.
def far(f):
Expand All @@ -110,28 +128,39 @@ def far(f):
flats = [f for f in feats if not f.get("is_pano") and (f.get("quality_score") or 0) >= 0.75]
pool = panos if PANO_ONLY else (panos or flats)
if not pool:
if raw and not any(f.get("is_pano") for f in feats):
count(key, "frames, none a panorama" if not tile_panos else "panoramas only beyond the 40 nearest frames")
elif raw:
count(key, "panoramas, none at quality 0.7")
continue
for f in random.sample(pool, min(3, len(pool))):
if AVOID and AVOID.taken(f["id"]):
count(key, "frame is in the other pool")
continue
try:
meta = json.loads(get(f"https://graph.mapillary.com/{f['id']}?fields={FIELDS}&access_token={TOKEN}"))
lo, la = meta["geometry"]["coordinates"]
if AVOID and AVOID.why(la, lo):
count(key, "near a place of the other pool")
continue
im = Image.open(io.BytesIO(get(meta["thumb_2048_url"]))).convert("RGB")
except Exception:
count(key, "frame not loaded")
continue
w, h = im.size
pano = bool(meta.get("is_pano"))
if pano and abs(w / h - 2) > 0.05:
count(key, "panorama not 2:1")
continue
# A panorama under 2048 px wide is soft in the game, -sharpen or not.
if pano and w < MIN_WIDTH:
count(key, "panorama under 2048 px")
continue
sharp = sharpness(im) if pano else None
if pano and sharp < MIN_SHARP:
count(key, "panorama softer than MIN_SHARP")
continue
count(key, "TAKEN")
return {"region": name, "kind": kind, "country": region.get("country") if isinstance(region, dict) else None,
"source": "mapillary", "source_id": str(f["id"]), "lat": la, "lon": lo,
"is_pano": pano, "sharpness": round(sharp) if sharp is not None else None,
Expand Down Expand Up @@ -176,6 +205,10 @@ def main():
d.text((x + 8, y + 2), label, fill="white", font=font)
sheet.save(f"{OUT}/sheet-{k // 30 + 1}.jpg", quality=82)
print(f"candidates: {len(cands)} of {len(regions)} regions, sheets: {(len(cands) + 29) // 30}")
report = {k: dict(v.most_common()) for k, v in sorted(REJECTS.items())}
json.dump(report, open(f"{OUT}/rejects.json", "w"), ensure_ascii=False, indent=1)
for k, v in report.items():
print(f" {k}: " + ", ".join(f"{why} {n}" for why, n in v.items()))

if __name__ == "__main__":
main()
107 changes: 107 additions & 0 deletions scripts/curation/test_curation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Offline checks of the curation scripts: no network, no Mapillary token.

python -m unittest scripts/curation/test_curation.py (needs shapely, mapbox-vector-tile, pillow)

The first group pins the zones pool.py plans in, Ukraine's above all: the west
and the centre are in, the front line, the occupied south and east and Crimea
are out. The second pins the reasons harvest.py counts when a tile gives no frame.
"""
import os, random, sys, tempfile, unittest
from unittest import mock

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
os.environ.setdefault("MAPILLARY_TOKEN", "offline")
os.environ.pop("MAPLY_AVOID", None)
sys.argv = [sys.argv[0], tempfile.mkdtemp()] # harvest.py reads its output folder on import

import harvest, pool
from regions import REGIONS

IN = {
"Kyiv": (50.45, 30.52), "Lviv": (49.84, 24.03), "Odesa": (46.48, 30.73),
"Vinnytsia": (49.23, 28.47), "Uzhhorod": (48.62, 22.29), "Chernivtsi": (48.29, 25.94),
"Ivano-Frankivsk": (48.92, 24.71), "Zhytomyr": (50.25, 28.66), "Rivne": (50.62, 26.25),
"Cherkasy": (49.44, 32.06),
}
OUT = {
"Simferopol": (44.95, 34.1), "Sevastopol": (44.6, 33.53), "Donetsk": (48.0, 37.8),
"Luhansk": (48.57, 39.3), "Mariupol": (47.1, 37.55), "Melitopol": (46.85, 35.37),
"Kherson": (46.64, 32.6), "Zaporizhzhia": (47.84, 35.14), "Kharkiv": (49.99, 36.23),
"Sumy": (50.9, 34.8),
}


class Zones(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.countries = pool.load_countries()

def test_west_and_centre_are_planned_in(self):
for name, (lat, lon) in IN.items():
with self.subTest(name):
self.assertEqual(pool.country_of(self.countries, lat, lon), "UA")
self.assertTrue(pool.allowed("UA", lat, lon))

def test_front_line_and_occupied_land_stay_out(self):
for name, (lat, lon) in OUT.items():
with self.subTest(name):
self.assertFalse(pool.allowed("UA", lat, lon))

def test_a_random_point_is_in_ukraine_and_in_a_zone_kept(self):
random.seed(1)
for _ in range(200):
lat, lon = pool.random_in(self.countries["UA"], "UA")
self.assertEqual(pool.country_of(self.countries, lat, lon), "UA")
self.assertTrue(pool.allowed("UA", lat, lon))

def test_the_big_cities_of_the_built_in_list(self):
# harvest.py's own list does not filter by zone; pool.py does. The
# list holds the Ukrainian cities, and Poltava is the one left out.
ua = {n: (la, lo) for n, la, lo, _ in REGIONS if pool.country_of(self.countries, la, lo) == "UA"}
self.assertEqual({n for n, p in ua.items() if not pool.allowed("UA", *p)}, {"Полтава"})
self.assertEqual(len(ua), 8)


def tile(*frames):
"""What mapbox_vector_tile.decode returns for a z14 tile of these frames."""
return {"image": {"features": [
{"geometry": {"type": "Point", "coordinates": [2048 + i, 2048]}, "properties": p}
for i, p in enumerate(frames)]}}


def frame(i, pano=True, quality=0.9, ts=1589816581000):
return {"id": i, "is_pano": pano, "quality_score": quality, "captured_at": ts}


class Reasons(unittest.TestCase):
def run_region(self, t, kind="town"):
harvest.REJECTS.clear()
region = {"name": "x", "lat": 49.4, "lon": 31.3, "km": 0.3, "inner": 0, "kind": kind, "country": "UA"}
with mock.patch.object(harvest, "get", return_value=b""), \
mock.patch.object(harvest.mapbox_vector_tile, "decode", return_value=t):
self.assertIsNone(harvest.harvest(region))
return dict(harvest.REJECTS["UA"])

def test_a_tile_of_flat_frames(self):
r = self.run_region(tile(frame(1, pano=False), frame(2, pano=False)))
self.assertEqual(r, {"frames, none a panorama": 12})

def test_a_panorama_under_the_quality_bar(self):
r = self.run_region(tile(frame(1, quality=0.5), frame(2, quality=None)))
self.assertEqual(r, {"panoramas, none at quality 0.7": 12})

def test_frames_before_2018(self):
r = self.run_region(tile(frame(1, ts=1400000000000)))
self.assertEqual(r, {"no frame since 2018 in the tile": 12})

def test_a_town_whose_panoramas_are_beyond_its_nearest_frames(self):
# 40 flat frames nearer the centre than the one panorama, as a dashcam town has.
t = tile(*[frame(i, pano=False) for i in range(40)], frame(99))
t["image"]["features"][-1]["geometry"]["coordinates"] = [4000, 4000]
r = self.run_region(t)
self.assertEqual(r, {"panoramas only beyond the 40 nearest frames": 12})


if __name__ == "__main__":
unittest.main()