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
5 changes: 3 additions & 2 deletions scripts/cron/gliders/GLIDERS_GENERATORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,10 @@ resource proxy. Schema version 1 contains `maps`, each with `id`, `year`,
`platform`, `variable`, `window`, `is_nrt`, `image_url`, and `deployments`. The
image URL is read from the original GIF attached to the HTML image map and is
null when the association cannot be verified. Each deployment
contains only `mission_name`, `pixel_rect`, `bbox`, and the original mission
contains `mission_name`, `pixel_rect`, `bbox`, optional `plot_pixel_rects`, and the original mission
`url`. Pixel coordinates use `[x1,y1,x2,y2]` on the original GIF and identify
the first mission rectangle in the map. WGS84 bounds use `[west,south,east,north]`.
the first mission rectangle on the map and any subsequent mission rectangles on
the time plots. WGS84 bounds use `[west,south,east,north]` and apply to the map rectangle.
The figure and mission paths are website-root-relative. Prepend `/resource`
when opening them through the resource proxy.

Expand Down
52 changes: 30 additions & 22 deletions scripts/cron/gliders/gliders_yearmaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,26 @@ def valid_mission_path(name, path, metadata):
path in {"/gliders/" + folder + "/latest.html" for folder in folders})


def parse_yearmap(html, filename):
"""Read the first mission-labelled rectangle; later links are not geometry.
def _mission_area(attrs, name, filename, metadata):
if attrs.get("shape", "").lower() != "rect":
raise ValueError("Unsupported mission area shape: " + name)
parts = re.split(r"[\s,]+", attrs.get("coords", "").strip())
if len(parts) != 4 or any(not re.fullmatch(r"[+-]?[0-9]+", p) for p in parts):
raise ValueError("Malformed mission rectangle: " + name)
x1, y1, x2, y2 = rect = list(map(int, parts))
if x1 >= x2 or y1 >= y2:
raise ValueError("Reversed or empty mission rectangle: " + name)
href = attrs.get("href", "")
if not re.fullmatch(r"(?:\.\./|/gliders/)[A-Za-z0-9_-]+/latest\.html", href):
raise ValueError("Unexpected mission link: " + name)
path = urljoin("/gliders/yearmaps/" + filename, href)
if not valid_mission_path(name, path, metadata):
raise ValueError("Unexpected mission link: " + name)
return rect, path

In the saved CSIRO sources the geographic rectangle precedes other links for
that mission. Mission labels (title or alt) and URL must agree. Panel
position is geographic eligibility, checked per mission when generating. SL*/SG* text links are excluded. No GIF or calendar data is read.
"""

def parse_yearmap(html, filename):
"""Read the geographic rectangle followed by plot rectangles for each mission."""
metadata = map_metadata(filename)
if not re.search(r"</html\s*>\s*$", html, re.I):
raise ValueError("Incomplete year-map HTML: " + filename)
Expand All @@ -84,23 +97,18 @@ def parse_yearmap(html, filename):
if len(labels) != 1:
raise ValueError("Conflicting mission labels")
name = labels.pop()
if name in deployments:
deployment = deployments.get(name)
try:
rect, path = _mission_area(attrs, name, filename, metadata)
except ValueError as error:
if deployment is None:
raise
LOG.warning("Skipping invalid plot area map=%s: %s", metadata["id"], error)
continue
if attrs.get("shape", "").lower() != "rect":
raise ValueError("Unsupported mission area shape: " + name)
parts = re.split(r"[\s,]+", attrs.get("coords", "").strip())
if len(parts) != 4 or any(not re.fullmatch(r"[+-]?[0-9]+", p) for p in parts):
raise ValueError("Malformed mission rectangle: " + name)
x1, y1, x2, y2 = rect = list(map(int, parts))
if x1 >= x2 or y1 >= y2:
raise ValueError("Reversed or empty mission rectangle: " + name)
href = attrs.get("href", "")
if not re.fullmatch(r"(?:\.\./|/gliders/)[A-Za-z0-9_-]+/latest\.html", href):
raise ValueError("Unexpected mission link: " + name)
path = urljoin("/gliders/yearmaps/" + filename, href)
if not valid_mission_path(name, path, metadata):
raise ValueError("Unexpected mission link: " + name)
deployments[name] = dict(mission_name=name, pixel_rect=rect, bbox=None, url=path)
if deployment is None:
deployments[name] = dict(mission_name=name, pixel_rect=rect, bbox=None, url=path)
elif rect != deployment["pixel_rect"] and rect not in deployment.get("plot_pixel_rects", []):
deployment.setdefault("plot_pixel_rects", []).append(rect)
return metadata, [deployments[name] for name in sorted(deployments)]


Expand Down
12 changes: 9 additions & 3 deletions scripts/cron/gliders/publish_gliders_yearmaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ def require(condition, message):
if not condition:
raise ValueError(message)

def validate_rect(rect, field):
require(isinstance(rect, list) and len(rect) == 4 and all(type(v) is int for v in rect), "Invalid " + field)
require(rect[0] < rect[2] and rect[1] < rect[3], "Invalid rectangle extent")

require(isinstance(document, dict) and type(document.get("schema_version")) is int
and document["schema_version"] == 1, "Expected schema_version == 1")
maps = document.get("maps")
Expand All @@ -42,9 +46,11 @@ def require(condition, message):
name = deployment.get("mission_name")
require(isinstance(name, str) and MISSION.fullmatch(name), "Invalid mission name")
names.append(name)
rect = deployment.get("pixel_rect")
require(isinstance(rect, list) and len(rect) == 4 and all(type(v) is int for v in rect), "Invalid pixel_rect")
require(rect[0] < rect[2] and rect[1] < rect[3], "Invalid rectangle extent")
validate_rect(deployment.get("pixel_rect"), "pixel_rect")
plots = deployment.get("plot_pixel_rects", [])
require(isinstance(plots, list), "Invalid plot_pixel_rects")
for rect in plots:
validate_rect(rect, "plot_pixel_rects")
require(valid_mission_path(name, deployment.get("url"), metadata), "Invalid deployment URL")
require("bbox" in deployment, "Missing bbox")
bbox = deployment["bbox"]
Expand Down
50 changes: 35 additions & 15 deletions scripts/cron/test_gliders_yearmaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def test_signed_legacy_rectangle_keeps_first_mission_area(self):
self.assertEqual(len(deployments), 1)
self.assertEqual(deployments[0]['pixel_rect'],
list(map(int, re.split(r'[\s,]+', coords))))
self.assertEqual(deployments[0]['plot_pixel_rects'], [[1231, 70, 1245, 95]])
self.assertEqual(deployments[0]['url'], '/gliders/TimorSea20181017a_4d/latest.html')
self.assertIsNone(deployments[0]['bbox'])

Expand Down Expand Up @@ -76,6 +77,7 @@ def test_saved_maps_separate_geography_calendar_and_labels(self):
_, deployments = generator.parse_yearmap((FIXTURES / NAME).read_text(), NAME)
esperance = next(d for d in deployments if d['mission_name'] == 'Esperance20260526_nrt')
self.assertEqual(esperance['pixel_rect'], [204, 368, 232, 393])
self.assertEqual(esperance['plot_pixel_rects'], [[997, 455, 1051, 486]])
self.assertEqual(esperance['url'], '/gliders/Esperance20260526_nrt_4d/latest.html')

def test_malformed_incomplete_and_mismatched_html(self):
Expand All @@ -98,16 +100,27 @@ def test_metadata_and_comma_separated_rectangles(self):
with self.assertRaises(ValueError):
generator.map_metadata(name)

def test_title_only_legacy_labels_and_ignored_non_geographic_areas(self):
def test_title_only_legacy_labels(self):
for name in ['2018_sg_temp_04d.html', NAME]:
html = (FIXTURES / name).read_text()
expected = generator.parse_yearmap(html, name)[1]
title_only = re.sub(r' alt="[^"]*"', '', html)
self.assertEqual(generator.parse_yearmap(title_only, name)[1], expected)
# Neither non-geographic coordinates nor the displayed GIF participates in geometry.
html = html.replace('997 455 1051 486', 'not geographic coordinates')
html = html.replace('2026_sl_temp_nrt.gif', 'missing.gif')
self.assertEqual(generator.parse_yearmap(html, NAME)[1], expected)

def test_invalid_plot_area_preserves_map_rectangle(self):
html = (FIXTURES / NAME).read_text()
plot_coords = '997 455 1051 486'
plot_link = f'{plot_coords}" href="../Esperance20260526_nrt_4d/latest.html"'
for original, replacement in (
(plot_coords, 'not plot coordinates'),
(plot_link, plot_link.replace('Esperance20260526_nrt', 'other')),
):
with self.subTest(replacement=replacement):
with self.assertLogs(generator.LOG, level='WARNING'):
_, deployments = generator.parse_yearmap(html.replace(original, replacement), NAME)
esperance = next(d for d in deployments if d['mission_name'] == 'Esperance20260526_nrt')
self.assertEqual(esperance['pixel_rect'], [204, 368, 232, 393])
self.assertNotIn('plot_pixel_rects', esperance)


class GeographyTests(unittest.TestCase):
Expand Down Expand Up @@ -317,7 +330,8 @@ def test_publish_signed_legacy_rectangle_without_fabricated_bounds(self):
legacy = next(m for m in result['maps'] if m['id'] == LEGACY_NAME[:-5])
self.assertEqual(legacy['deployments'], [dict(
mission_name='TimorSea20181017a', pixel_rect=[268, -40, 289, -22],
bbox=None, url='/gliders/TimorSea20181017a_4d/latest.html')])
bbox=None, url='/gliders/TimorSea20181017a_4d/latest.html',
plot_pixel_rects=[[1231, 70, 1245, 95]])])
self.assertIsNone(legacy['image_url'])
self.assertEqual(json.loads(self.output.read_text()), result)
# The signed rectangle is also accepted when validating the published baseline.
Expand All @@ -333,15 +347,19 @@ def test_publish_signed_legacy_rectangle_without_fabricated_bounds(self):

def test_deterministic_unchanged_and_reference_json(self):
(self.source / 'index.html').write_text('<html>Directory listing</html>')
expected_file = FIXTURES / 'expected.json'
baseline = json.loads(expected_file.read_bytes())
for entry in baseline['maps']:
del entry['image_url']
self.output.write_text(json.dumps(baseline))
self.publish()
# The reference covers the additive image URLs, map/deployment order, links, and bounds.
expected = expected_file.read_bytes()
self.assertEqual(self.output.read_bytes(), expected)
expected = (FIXTURES / 'expected.json').read_bytes()
for has_image_url in (False, True):
with self.subTest(has_image_url=has_image_url):
baseline = json.loads(expected)
for entry in baseline['maps']:
if not has_image_url:
del entry['image_url']
for deployment in entry['deployments']:
del deployment['plot_pixel_rects']
self.output.write_text(json.dumps(baseline))
self.publish()
self.assertEqual(self.output.read_bytes(), expected)

previous = self.output.stat()
self.publish()
self.assertEqual(self.output.read_bytes(), expected)
Expand Down Expand Up @@ -458,6 +476,8 @@ def test_configuration_and_schema_validation(self):
lambda d: d['maps'].append(d['maps'][0]),
lambda d: d['maps'][0].update(image_url='/gliders/yearmaps/2000_sg_temp.gif'),
lambda d: d['maps'][0]['deployments'][0].update(pixel_rect=[1, 2, 0, 3]),
lambda d: d['maps'][0]['deployments'][0].update(plot_pixel_rects=[1, 2, 3, 4]),
lambda d: d['maps'][0]['deployments'][0].update(plot_pixel_rects=[[1, 2, 0, 3]]),
lambda d: d['maps'][0]['deployments'][0].update(url='https://other/'),
lambda d: d['maps'][0]['deployments'][0].update(bbox=[-200, -40, 120, -30])]
for change in changes:
Expand Down
Loading