Číst číselníky z OAI i ve formátu oai_amcr

Server AMČR OAI na metadataPrefix=oai_dc vrací nativní záznamy amcr:amcr
místo Dublin Core (#96, dříve #89), takže všech 17 OAI číselníků vycházelo
prázdných. fetch_set dál žádá oai_dc, ale každý záznam čte v tom formátu,
ve kterém přijde: oai_dc:dc jako dosud, jinak entitu amcr:* (heslo,
ruian_kraj, ruian_okres, ruian_katastr, organizace). Výsledné kódy a
názvy jsou stejné jako z DC. Smazané záznamy se přeskakují jako dřív.

- tests/api_contract.py: oai_amcr na oai_dc je DRIFT, nečitelný záznam FAIL
- tests/smoke_test.py: offline případy pro oba formáty
- OpenSpec: úkoly odškrtnuty, v designu doplněny smazané záznamy

Živě ověřeno 2026-12-02: všech 17 setů dává totéž co heslar.csv
(včetně 13 091 katastrů), api_plugin_live v qgis:ltr bez FAIL/DRIFT.

Kód navržen AI, ověřen automatickými kontrolami.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013nPfHUicaDVqWsYEoQWhYD
This commit is contained in:
Claude committed 2026-12-02 04:35:47 +00:00
1 parent c868f1dc44
commit 17da0ca175
5 files changed
+298 -68

No files matched your search

+132 -50
View File
@@ -39,9 +39,15 @@ slovnicek = {
NS = { NS = {
'oai': 'http://www.openarchives.org/OAI/2.0/', 'oai': 'http://www.openarchives.org/OAI/2.0/',
'dc': 'http://purl.org/dc/elements/1.1/', '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(): def ensure_codelists_dir():
"""Creates the codelists directory if it does not exist.""" """Creates the codelists directory if it does not exist."""
@@ -119,8 +125,106 @@ def _facet_name(item):
return None 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:<tag> 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): def fetch_set(base_url, internal_name, api_set, task=None):
dataset = [] dataset = []
amcr_count = 0
skipped = 0
params_amcr = { params_amcr = {
"verb": "ListRecords", "verb": "ListRecords",
"metadataPrefix": "oai_dc", "metadataPrefix": "oai_dc",
@@ -148,58 +252,35 @@ def fetch_set(base_url, internal_name, api_set, task=None):
records = root.findall('.//oai:record', NS) records = root.findall('.//oai:record', NS)
for rec in records: for rec in records:
metadata = rec.find('.//oai_dc:dc', NS) header = rec.find('oai:header', NS)
if metadata is not None: if (header is not None
# Code (identifier) and header.get('status') == 'deleted'):
identifier_el = metadata.find('dc:identifier', NS) continue # deleted records carry no metadata
kod = ( parsed = _parse_dc(rec.find('.//oai_dc:dc', NS))
identifier_el.text if parsed is None:
if identifier_el is not None parsed = _parse_amcr(rec.find('.//amcr:amcr', NS))
else "" if parsed is None:
) skipped += 1
continue
amcr_count += 1
kod, nazev, zkratka = parsed
# Title – filter out system labels "AMČR - ..." if internal_name in ('okres', 'katastr'):
titles = metadata.findall('dc:title', NS) kod = nazev
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
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: dataset.append({
kod = nazev 'Název': nazev,
'Kód': kod,
if internal_name == 'pristupnost': 'Kategorie': internal_name
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
})
# Pagination # Pagination
token = root.find('.//oai:resumptionToken', NS) 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) time.sleep(0.5)
else: else:
_log_formats(api_set, amcr_count, skipped)
break break
else: else:
@@ -59,7 +59,8 @@
`.//amcr:heslo` from the record. `.//amcr:heslo` from the record.
3. **Unknown entity or missing key fields → skip the record** and count it. 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 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. 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. 4. **Contract test:** for each record, `oai_dc:dc` + `dc:identifier` → DC.
Otherwise an `amcr:amcr` child with the mapped key fields → AMCR. Otherwise an `amcr:amcr` child with the mapped key fields → AMCR.
@@ -2,44 +2,44 @@
## 1. Parsing both formats in the plugin ## 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 `_parse_amcr(metadata)` in `amcr_viewer/amcr_codelists.py` per design.md
(mapping table; direct-child lookups on the entity). Move the (mapping table; direct-child lookups on the entity). Move the
`okres` / `katastr` / `pristupnost` special cases after the extraction so `okres` / `katastr` / `pristupnost` special cases after the extraction so
both paths share them. Verify with `python3 tests/check_sources.py`, both paths share them. Verify with `python3 tests/check_sources.py`,
`flake8 --isolated amcr_viewer/` and `ruff check .` `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 unreadable records) and log once per set how many records came in the
AMCR format. Verify by code review: the request parameters are unchanged AMCR format. Verify by code review: the request parameters are unchanged
(`metadataPrefix=oai_dc`) (`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 fault lasts, and compare the rows to the committed `heslar.csv` by
category (same codes; differences only from real codelist changes). category (same codes; differences only from real codelist changes).
Verify the diff summary is recorded in the PR Verify the diff summary is recorded in the PR
## 2. Tests ## 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 record, AMCR `heslo`, `heslo:pristupnost` (with and without a one-letter
`zkratka`), `ruian_kraj`, `ruian_okres`, `ruian_katastr`, `organizace`, `zkratka`), `ruian_kraj`, `ruian_okres`, `ruian_katastr`, `organizace`,
and an unknown payload. Verify the smoke test passes in `qgis/qgis:ltr` and an unknown payload. Verify the smoke test passes in `qgis/qgis:ltr`
and `qgis/qgis:stable` 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 → readable AMCR → DRIFT ("server returns oai_amcr on oai_dc"), neither →
FAIL. Verify with FAIL. Verify with
`uv run -q --no-project --with requests==2.34.2 python tests/api_contract.py` `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 (expect DRIFT for the oai checks while the fault lasts, and exit code per
the DRIFT rules) 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 `fetch_set` check is OK
## 3. Release preparation and verification ## 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 `CITATION.cff`. Add a changelog entry with the date from
`python -c "import datetime; print(datetime.date.today().isoformat())"`. `python -c "import datetime; print(datetime.date.today().isoformat())"`.
Verify both files show the same version 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, bandit, detect-secrets `--all-files`, flake8 `--isolated`, ruff,
pyqgis4-checker log empty, smoke test ltr + stable); verify all clean pyqgis4-checker log empty, smoke test ltr + stable); verify all clean
- [ ] 3.3 Manual test in QGIS: refresh the codelists; verify there is no - [ ] 3.3 Manual test in QGIS: refresh the codelists; verify there is no
+55 -9
View File
@@ -116,6 +116,17 @@ NS = {
"oai": "http://www.openarchives.org/OAI/2.0/", "oai": "http://www.openarchives.org/OAI/2.0/",
"dc": "http://purl.org/dc/elements/1.1/", "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/",
}
# 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() SESSION = requests.Session()
@@ -461,6 +472,37 @@ def check_facet_sets():
f"mixed shapes {sorted(shapes)}", url) f"mixed shapes {sorted(shapes)}", url)
def _has_text(entity, tag):
"""True when a direct amcr:<tag> 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(): def check_oai_sets():
"""Every OAI set in slovnicek: first page + resumptionToken paging.""" """Every OAI set in slovnicek: first page + resumptionToken paging."""
url = OAI_URL url = OAI_URL
@@ -489,15 +531,14 @@ def check_oai_sets():
record(f"oai {name}", "FAIL", record(f"oai {name}", "FAIL",
f"set {oai_set} returned no records", url) f"set {oai_set} returned no records", url)
continue continue
# record shape: identifier, titles, dc payload # record shape: oai_dc payload with an identifier, or – the server
ok_shape = all( # fault of #89 / #96 – a readable oai_amcr payload on an oai_dc
r.find(".//oai_dc:dc", NS) is not None # request, which the plugin tolerates
and r.find(".//dc:identifier", NS) is not None shapes = {_record_shape(r) for r in records}
for r in records if "bad" in shapes:
)
if not ok_shape:
record(f"oai {name}", "FAIL", 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 continue
token = root.find(".//oai:resumptionToken", NS) token = root.find(".//oai:resumptionToken", NS)
token_ok = True token_ok = True
@@ -526,7 +567,12 @@ def check_oai_sets():
desc = f"{len(records)} records" desc = f"{len(records)} records"
if token is not None and token.text: if token is not None and token.text:
desc += ", token page followed" 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: else:
record(f"oai {name}", "FAIL", record(f"oai {name}", "FAIL",
"resumptionToken page returned no records", url) "resumptionToken page returned no records", url)
+101
View File
@@ -645,6 +645,106 @@ def upozorneni_obnovy():
dialog._REMEMBERED_STATE.clear() dialog._REMEMBERED_STATE.clear()
_OAI_HEAD = (
'<OAI-PMH xmlns="http://www.openarchives.org/OAI/2.0/"><ListRecords>'
)
_OAI_TAIL = '</ListRecords></OAI-PMH>'
_AMCR_NS = 'xmlns:amcr="https://api.aiscr.cz/schema/amcr/2.2/"'
def _dc_record(identifier, *titles):
tituly = "".join(f"<dc:title>{t}</dc:title>" for t in titles)
return (
"<record><header><identifier>x</identifier></header><metadata>"
'<oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/'
'oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/">'
f"<dc:identifier>{identifier}</dc:identifier>{tituly}"
"</oai_dc:dc></metadata></record>"
)
def _amcr_record(entity, **fields):
obsah = "".join(f"<amcr:{k}>{v}</amcr:{k}>" for k, v in fields.items())
return (
"<record><header><identifier>x</identifier></header><metadata>"
f"<amcr:amcr {_AMCR_NS}><amcr:{entity}>{obsah}</amcr:{entity}>"
"</amcr:amcr></metadata></record>"
)
def _deleted_record():
return ('<record><header status="deleted"><identifier>x</identifier>'
'</header></record>')
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(),
"<record><header><identifier>x</identifier></header>"
"<metadata><jine/></metadata></record>"],
[]),
]
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("scoped enumy", enumy)
zkouska("UpdateCodelistsTask", uloha) zkouska("UpdateCodelistsTask", uloha)
zkouska("filtrační dialogy", dialogy) zkouska("filtrační dialogy", dialogy)
@@ -658,6 +758,7 @@ zkouska("upozornění obnovy", upozorneni_obnovy)
zkouska("stav přihlášení", prihlasovaci_stav) zkouska("stav přihlášení", prihlasovaci_stav)
zkouska("odhlášení", odhlaseni) zkouska("odhlášení", odhlaseni)
zkouska("váha komponent", vaha_komponent) zkouska("váha komponent", vaha_komponent)
zkouska("číselníky z OAI", ciselniky_oai)
qgs.exitQgis() qgs.exitQgis()