diff --git a/amcr_viewer/amcr_codelists.py b/amcr_viewer/amcr_codelists.py index 4001e5e..315e85e 100644 --- a/amcr_viewer/amcr_codelists.py +++ b/amcr_viewer/amcr_codelists.py @@ -39,9 +39,15 @@ slovnicek = { NS = { 'oai': 'http://www.openarchives.org/OAI/2.0/', 'dc': 'http://purl.org/dc/elements/1.1/', - 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/' + 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/', + 'amcr': 'https://api.aiscr.cz/schema/amcr/2.2/', } +# Entities of the native oai_amcr format that hold a codelist item +_AMCR_ENTITIES = ('heslo', 'ruian_kraj', 'ruian_okres', 'ruian_katastr', + 'organizace') +_AMCR_PREFIX = '{' + NS['amcr'] + '}' + def ensure_codelists_dir(): """Creates the codelists directory if it does not exist.""" @@ -119,8 +125,106 @@ def _facet_name(item): return None +def _is_access_code(text): + """True for a one-letter access level code such as "A" or "D".""" + return bool(text) and len(text) == 1 and text.isalpha() + + +def _parse_dc(metadata): + """ + Reads one codelist item from an oai_dc:dc element. + + Returns (code, name, access_code) or None when metadata is None. + access_code is the one-letter title used by the pristupnost set. + """ + if metadata is None: + return None + identifier_el = metadata.find('dc:identifier', NS) + kod = identifier_el.text if identifier_el is not None else "" + + # Title – filter out system labels "AMČR - ..." + titles = metadata.findall('dc:title', NS) + nazev = "" + for t in titles: + if ( + t.text + and not t.text.startswith("AMČR -") + and not t.text.startswith(" AMČR -") + ): + nazev = t.text + break + # If no title passed the filter, fall back to the first available one + if not nazev and titles: + nazev = titles[0].text + + zkratka = next( + (t.text for t in titles if _is_access_code(t.text)), None) + return kod, nazev, zkratka + + +def _amcr_text(entity, tag): + """Stripped text of a direct amcr: child, or None.""" + el = entity.find('amcr:' + tag, NS) + if el is None or not el.text or not el.text.strip(): + return None + return el.text.strip() + + +def _parse_amcr(amcr_el): + """ + Reads one codelist item from an amcr:amcr element (oai_amcr format). + + The AMČR OAI server has been seen answering metadataPrefix=oai_dc with + this format (issues #89, #96). Returns (code, name, access_code) with + the same values the oai_dc format gives, or None when the entity is + unknown or lacks its code or name. + + Lookups are direct children of the entity on purpose: amcr:heslo is + both the entity and the child holding its name. + """ + if amcr_el is None: + return None + entity = next( + (child for child in amcr_el + if child.tag.startswith(_AMCR_PREFIX) + and child.tag[len(_AMCR_PREFIX):] in _AMCR_ENTITIES), + None) + if entity is None: + return None + if entity.tag == _AMCR_PREFIX + 'heslo': + kod = _amcr_text(entity, 'ident_cely') + nazev = _amcr_text(entity, 'heslo') + zkratka = _amcr_text(entity, 'zkratka') + if not _is_access_code(zkratka): + zkratka = None + else: + kod = (_amcr_text(entity, 'ident_cely') + or _amcr_text(entity, 'kod')) + nazev = _amcr_text(entity, 'nazev') + zkratka = None + if not kod or not nazev: + return None + return kod, nazev, zkratka + + +def _log_formats(api_set, amcr_count, skipped): + """Logs once per set when records did not come as oai_dc.""" + if amcr_count: + QgsMessageLog.logMessage( + f"Set {api_set}: {amcr_count} záznamů přišlo ve formátu " + "oai_amcr místo oai_dc, čtu je z něj.", + "AMČR", Qgis.MessageLevel.Info) + if skipped: + QgsMessageLog.logMessage( + f"Set {api_set}: {skipped} záznamů v neznámém formátu " + "přeskočeno.", + "AMČR", Qgis.MessageLevel.Warning) + + def fetch_set(base_url, internal_name, api_set, task=None): dataset = [] + amcr_count = 0 + skipped = 0 params_amcr = { "verb": "ListRecords", "metadataPrefix": "oai_dc", @@ -148,58 +252,35 @@ def fetch_set(base_url, internal_name, api_set, task=None): records = root.findall('.//oai:record', NS) for rec in records: - metadata = rec.find('.//oai_dc:dc', NS) - if metadata is not None: - # Code (identifier) - identifier_el = metadata.find('dc:identifier', NS) - kod = ( - identifier_el.text - if identifier_el is not None - else "" - ) + header = rec.find('oai:header', NS) + if (header is not None + and header.get('status') == 'deleted'): + continue # deleted records carry no metadata + parsed = _parse_dc(rec.find('.//oai_dc:dc', NS)) + if parsed is None: + parsed = _parse_amcr(rec.find('.//amcr:amcr', NS)) + if parsed is None: + skipped += 1 + continue + amcr_count += 1 + kod, nazev, zkratka = parsed - # Title – filter out system labels "AMČR - ..." - titles = metadata.findall('dc:title', NS) - nazev = "" - for t in titles: - if ( - t.text - and not t.text.startswith("AMČR -") - and not t.text.startswith(" AMČR -") - ): - nazev = t.text - break - # If no title passed the filter, fall back - # to the first available one - if not nazev and titles: - nazev = titles[0].text + if internal_name in ('okres', 'katastr'): + kod = nazev - specialni_pripady = ['okres', 'katastr'] + if internal_name == 'pristupnost': + # Skip records without a valid one-letter code – + # a None code would end up in the CSV and later + # in the API filter as the string "None" + kod = zkratka + if not kod: + continue - if internal_name in specialni_pripady: - kod = nazev - - if internal_name == 'pristupnost': - kod = next( - ( - t.text for t in titles - if t.text - and len(t.text) == 1 - and t.text.isalpha() - ), - None - ) - # Skip records without a valid one-letter code – - # a None code would end up in the CSV and later - # in the API filter as the string "None" - if not kod: - continue - - dataset.append({ - 'Název': nazev, - 'Kód': kod, - 'Kategorie': internal_name - }) + dataset.append({ + 'Název': nazev, + 'Kód': kod, + 'Kategorie': internal_name + }) # Pagination token = root.find('.//oai:resumptionToken', NS) @@ -210,6 +291,7 @@ def fetch_set(base_url, internal_name, api_set, task=None): } time.sleep(0.5) else: + _log_formats(api_set, amcr_count, skipped) break else: diff --git a/openspec/changes/fix-oai-amcr-fallback/design.md b/openspec/changes/fix-oai-amcr-fallback/design.md index 4ee92cc..db5e825 100644 --- a/openspec/changes/fix-oai-amcr-fallback/design.md +++ b/openspec/changes/fix-oai-amcr-fallback/design.md @@ -59,7 +59,8 @@ `.//amcr:heslo` from the record. 3. **Unknown entity or missing key fields → skip the record** and count it. If a set yields no rows, `download_heslare` already keeps the old rows - and warns. Log once per set, not per record, how many records were read + and warns. Records whose header has `status="deleted"` carry no + metadata. They are skipped without being counted, as before. Log once per set, not per record, how many records were read in the `amcr` format, so the fault is visible in the QGIS log. 4. **Contract test:** for each record, `oai_dc:dc` + `dc:identifier` → DC. Otherwise an `amcr:amcr` child with the mapped key fields → AMCR. diff --git a/openspec/changes/fix-oai-amcr-fallback/tasks.md b/openspec/changes/fix-oai-amcr-fallback/tasks.md index 08c37d3..b638589 100644 --- a/openspec/changes/fix-oai-amcr-fallback/tasks.md +++ b/openspec/changes/fix-oai-amcr-fallback/tasks.md @@ -2,44 +2,44 @@ ## 1. Parsing both formats in the plugin -- [ ] 1.1 Add `amcr` to `NS` and the helpers `_parse_dc(metadata)` / +- [x] 1.1 Add `amcr` to `NS` and the helpers `_parse_dc(metadata)` / `_parse_amcr(metadata)` in `amcr_viewer/amcr_codelists.py` per design.md (mapping table; direct-child lookups on the entity). Move the `okres` / `katastr` / `pristupnost` special cases after the extraction so both paths share them. Verify with `python3 tests/check_sources.py`, `flake8 --isolated amcr_viewer/` and `ruff check .` -- [ ] 1.2 Use the helpers in `fetch_set` (DC first, AMCR otherwise, skip +- [x] 1.2 Use the helpers in `fetch_set` (DC first, AMCR otherwise, skip unreadable records) and log once per set how many records came in the AMCR format. Verify by code review: the request parameters are unchanged (`metadataPrefix=oai_dc`) -- [ ] 1.3 Live check: run `fetch_set` for every OAI set while the server +- [x] 1.3 Live check: run `fetch_set` for every OAI set while the server fault lasts, and compare the rows to the committed `heslar.csv` by category (same codes; differences only from real codelist changes). Verify the diff summary is recorded in the PR ## 2. Tests -- [ ] 2.1 Extend `tests/smoke_test.py` with offline XML snippets: DC +- [x] 2.1 Extend `tests/smoke_test.py` with offline XML snippets: DC record, AMCR `heslo`, `heslo:pristupnost` (with and without a one-letter `zkratka`), `ruian_kraj`, `ruian_okres`, `ruian_katastr`, `organizace`, and an unknown payload. Verify the smoke test passes in `qgis/qgis:ltr` and `qgis/qgis:stable` -- [ ] 2.2 Update `check_oai_sets` in `tests/api_contract.py`: DC → OK, +- [x] 2.2 Update `check_oai_sets` in `tests/api_contract.py`: DC → OK, readable AMCR → DRIFT ("server returns oai_amcr on oai_dc"), neither → FAIL. Verify with `uv run -q --no-project --with requests==2.34.2 python tests/api_contract.py` (expect DRIFT for the oai checks while the fault lasts, and exit code per the DRIFT rules) -- [ ] 2.3 Run `tests/api_plugin_live.py` in `qgis/qgis:ltr`; verify every +- [x] 2.3 Run `tests/api_plugin_live.py` in `qgis/qgis:ltr`; verify every `fetch_set` check is OK ## 3. Release preparation and verification -- [ ] 3.1 Bump the version (patch) in `amcr_viewer/metadata.txt` and +- [x] 3.1 Bump the version (patch) in `amcr_viewer/metadata.txt` and `CITATION.cff`. Add a changelog entry with the date from `python -c "import datetime; print(datetime.date.today().isoformat())"`. Verify both files show the same version -- [ ] 3.2 Run the full local check set from `AGENTS.md` (check_sources, +- [x] 3.2 Run the full local check set from `AGENTS.md` (check_sources, bandit, detect-secrets `--all-files`, flake8 `--isolated`, ruff, pyqgis4-checker log empty, smoke test ltr + stable); verify all clean - [ ] 3.3 Manual test in QGIS: refresh the codelists; verify there is no diff --git a/tests/api_contract.py b/tests/api_contract.py index ddd8867..0adfa97 100644 --- a/tests/api_contract.py +++ b/tests/api_contract.py @@ -116,6 +116,17 @@ NS = { "oai": "http://www.openarchives.org/OAI/2.0/", "dc": "http://purl.org/dc/elements/1.1/", "oai_dc": "http://www.openarchives.org/OAI/2.0/oai_dc/", + "amcr": "https://api.aiscr.cz/schema/amcr/2.2/", +} + +# oai_amcr entities the plugin can read a codelist item from, with the +# (code, name) children it uses – mirrors _parse_amcr in amcr_codelists +AMCR_ENTITIES = { + "heslo": (("ident_cely",), "heslo"), + "ruian_kraj": (("ident_cely", "kod"), "nazev"), + "ruian_okres": (("ident_cely", "kod"), "nazev"), + "ruian_katastr": (("ident_cely", "kod"), "nazev"), + "organizace": (("ident_cely", "kod"), "nazev"), } SESSION = requests.Session() @@ -461,6 +472,37 @@ def check_facet_sets(): f"mixed shapes {sorted(shapes)}", url) +def _has_text(entity, tag): + """True when a direct amcr: child has non-blank text.""" + el = entity.find(f"amcr:{tag}", NS) + return el is not None and bool((el.text or "").strip()) + + +def _amcr_readable(amcr_el): + """True when amcr:amcr holds a known entity with its code and name.""" + if amcr_el is None: + return False + for tag, (code_tags, name_tag) in AMCR_ENTITIES.items(): + entity = amcr_el.find(f"amcr:{tag}", NS) + if entity is not None: + return (any(_has_text(entity, t) for t in code_tags) + and _has_text(entity, name_tag)) + return False + + +def _record_shape(rec): + """'dc', 'amcr', 'deleted' or 'bad' for one oai:record.""" + header = rec.find("oai:header", NS) + if header is not None and header.get("status") == "deleted": + return "deleted" + if (rec.find(".//oai_dc:dc", NS) is not None + and rec.find(".//dc:identifier", NS) is not None): + return "dc" + if _amcr_readable(rec.find(".//amcr:amcr", NS)): + return "amcr" + return "bad" + + def check_oai_sets(): """Every OAI set in slovnicek: first page + resumptionToken paging.""" url = OAI_URL @@ -489,15 +531,14 @@ def check_oai_sets(): record(f"oai {name}", "FAIL", f"set {oai_set} returned no records", url) continue - # record shape: identifier, titles, dc payload - ok_shape = all( - r.find(".//oai_dc:dc", NS) is not None - and r.find(".//dc:identifier", NS) is not None - for r in records - ) - if not ok_shape: + # record shape: oai_dc payload with an identifier, or – the server + # fault of #89 / #96 – a readable oai_amcr payload on an oai_dc + # request, which the plugin tolerates + shapes = {_record_shape(r) for r in records} + if "bad" in shapes: record(f"oai {name}", "FAIL", - "record missing oai_dc:dc or dc:identifier", url) + "record in neither readable format (oai_dc:dc with " + "dc:identifier, or amcr:amcr with code and name)", url) continue token = root.find(".//oai:resumptionToken", NS) token_ok = True @@ -526,7 +567,12 @@ def check_oai_sets(): desc = f"{len(records)} records" if token is not None and token.text: desc += ", token page followed" - record(f"oai {name}", "OK", desc, url) + if "amcr" in shapes: + record(f"oai {name}", "DRIFT", + "server returns oai_amcr on oai_dc – the plugin " + f"reads it ({desc})", url) + else: + record(f"oai {name}", "OK", desc, url) else: record(f"oai {name}", "FAIL", "resumptionToken page returned no records", url) diff --git a/tests/smoke_test.py b/tests/smoke_test.py index b2bb19e..cd8798c 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -645,6 +645,106 @@ def upozorneni_obnovy(): dialog._REMEMBERED_STATE.clear() +_OAI_HEAD = ( + '' +) +_OAI_TAIL = '' +_AMCR_NS = 'xmlns:amcr="https://api.aiscr.cz/schema/amcr/2.2/"' + + +def _dc_record(identifier, *titles): + tituly = "".join(f"{t}" for t in titles) + return ( + "
x
" + '' + f"{identifier}{tituly}" + "
" + ) + + +def _amcr_record(entity, **fields): + obsah = "".join(f"{v}" for k, v in fields.items()) + return ( + "
x
" + f"{obsah}" + "
" + ) + + +def _deleted_record(): + return ('
x' + '
') + + +def _fetch_offline(codelists, internal_name, *records): + """fetch_set against one canned OAI page – no request leaves.""" + class Odpoved: + content = (_OAI_HEAD + "".join(records) + _OAI_TAIL).encode("utf-8") + + def raise_for_status(self): + pass + + puvodni = codelists.requests.get + codelists.requests.get = lambda *a, **k: Odpoved() + try: + data = codelists.fetch_set(codelists.BASE_URL_AMCR, internal_name, + "set") + finally: + codelists.requests.get = puvodni + return [(d["Kód"], d["Název"]) for d in data] + + +def ciselniky_oai(): + """ + fetch_set reads oai_dc and – the server fault of #89 / #96 – the + native oai_amcr payload, with the same values for both. + """ + c = amcr_viewer.amcr_codelists + pripady = [ + ("obdobi", [_dc_record("HES-000277", "AMČR - obdobi", + "rané středohradištní období")], + [("HES-000277", "rané středohradištní období")]), + ("obdobi", [_amcr_record("heslo", ident_cely="HES-000277", + nazev_heslare="obdobi", + heslo="rané středohradištní období", + zkratka="rs.3.ra")], + [("HES-000277", "rané středohradištní období")]), + ("pristupnost", [_dc_record("HES-000868", "archivář", "D")], + [("D", "archivář")]), + ("pristupnost", [_amcr_record("heslo", ident_cely="HES-000868", + heslo="archivář", zkratka="D"), + _amcr_record("heslo", ident_cely="HES-000869", + heslo="bez zkratky"), + _amcr_record("heslo", ident_cely="HES-000870", + heslo="dlouhá", zkratka="AB")], + [("D", "archivář")]), + ("kraj", [_amcr_record("ruian_kraj", kod="ruian-27", + nazev="Středočeský kraj")], + [("ruian-27", "Středočeský kraj")]), + ("okres", [_amcr_record("ruian_okres", kod="ruian-3713", + nazev="Znojmo", spz="ZN")], + [("Znojmo", "Znojmo")]), + ("katastr", [_amcr_record("ruian_katastr", kod="ruian-751910", + nazev="Soběšice")], + [("Soběšice", "Soběšice")]), + ("organizace", [_amcr_record("organizace", ident_cely="ORG-000128", + nazev="Galerie a muzeum Vysočiny", + nazev_zkraceny="GMV")], + [("ORG-000128", "Galerie a muzeum Vysočiny")]), + ("obdobi", [_amcr_record("projekt", ident_cely="X", nazev="Y"), + _amcr_record("heslo", ident_cely="HES-1"), + _deleted_record(), + "
x
" + "
"], + []), + ] + for interni, zaznamy, ocekavano in pripady: + vysledek = _fetch_offline(c, interni, *zaznamy) + assert vysledek == ocekavano, (interni, vysledek, ocekavano) + return f"{len(pripady)} případů oai_dc / oai_amcr" + + zkouska("scoped enumy", enumy) zkouska("UpdateCodelistsTask", uloha) zkouska("filtrační dialogy", dialogy) @@ -658,6 +758,7 @@ zkouska("upozornění obnovy", upozorneni_obnovy) zkouska("stav přihlášení", prihlasovaci_stav) zkouska("odhlášení", odhlaseni) zkouska("váha komponent", vaha_komponent) +zkouska("číselníky z OAI", ciselniky_oai) qgs.exitQgis()