Skip to content

Python API: knowtation-core

Generated from the docstrings.

knowtation_core.connect

One entry point for local files, folders, zips and URLs.

read_path(path, settings)

Read one file with the right connector.

summarise(dataset)

Dataset-level temporal and spatial coverage from its resources.

resolve_placeholders(dataset, proposals)

Proposals for the dataset, and for every column of a name, with their real targets.

connect_paths(paths, name=None, settings=None)

Profile several local files or folders as one dataset.

download_name(url, headers)

The file name to save a download under, with an ending a reader knows if possible.

The attachment name (Content-Disposition) wins over the URL path, whose last part is often not a file name (World Bank: .../indicator/EN.GHG.CO2.PC.CE.AR5?downloadformat=csv). Only the name is kept, never a directory. An unknown ending gets one from the content type.

redact_url(url)

The URL without user name and password, and without a query that carries credentials.

download_to(url, folder, settings, on_progress=None)

Download to folder, retrying once if the server is slow or the connection drops.

on_progress((bytes so far, total or None)) is called as data arrives. Returns the path, or an error message (which never contains the URL's credentials).

server_reason(body)

A server's short explanation of an error: XML Code and Message, or a JSON message.

Only these fields are taken: the rest may echo credentials (S3 repeats the signature for some errors).

profile_download(location, got, *, name, settings)

Profile a downloaded file (or describe the failed download) for the dataset at location.

connect(location, *, name=None, settings=None)

Profile a local file, folder or zip, or a file at an http(s) URL.

knowtation_core.connectors.base

Shared pieces for connectors.

ConnectSettings dataclass

Limits and network settings for reading sources.

Profiled dataclass

A profiled dataset plus the proposals produced while reading it (profiler, recognisers).

noting()

Collect notes readers make while a source is read (they become dataset warnings).

note(message)

Record a note for the dataset's warnings, if a collection is active.

http_client(settings)

An HTTP client whose every request, including redirects, passes the SSRF guard.

slug(text)

A stable id fragment: lower case, runs of non-word characters become '_'.

distinct_dataset_id(dataset)

Give the dataset an id no resource or element uses, so edit targets are unambiguous.

element_id(resource_id, path)

The id of an element: its resource id, '#', and its path.

sha256_bytes(data)

SHA-256 of the bytes, as hex.

failed_resource(path, kind, error, *, rid=None)

A resource that could not be read, with the reason.

check_size(path, settings)

An error message if the file is over the size limit, else None.

check_zip(path, settings)

Check a zip before extracting it.

Returns an error message if the archive has too many files, is too big uncompressed, compresses suspiciously well (a "zip bomb") or has members that would land outside the archive; otherwise None.

knowtation_core.net

Outbound HTTP safety: refuse requests to non-public addresses (SSRF protection).

Every connector's HTTP client wraps its transport in :class:GuardedTransport. The guard resolves the host once, refuses loopback, private, link-local, multicast, reserved and other non-global addresses, and then connects to the address it checked (so a second DNS answer cannot redirect the connection, "DNS rebinding"). Redirects go through the guard again.

BlockedAddress

Bases: RequestError

A request was refused because its host resolves to a non-public address.

GuardedTransport

Bases: BaseTransport

An httpx transport that only connects to public addresses (or allowlisted hosts).

handle_request(request)

Check the host's addresses, then send the request to the checked address.

close()

Close the wrapped transport.

is_public(address)

True if address is a globally routable unicast IP address.

system_resolver(host)

Resolve host with the operating system, keeping the order of the answers.

knowtation_core.identify

Identification runs and review.

RunResult dataclass

A run's result: the described dataset, scored proposals and the run record.

ReviewEdit

Bases: BaseModel

One review action on a property: accept, reject or edit.

chosen_ids(content, proposals)

The ids of the chosen proposals.

For stored properties, the highest-confidence proposal whose value is the stored one (none if the property is empty); for facts that aren't stored, the best proposal.

apply_choices(dataset, scored)

Set the best proposal of each property where the dataset has no value yet.

dataset_hash(dataset)

A hash of the dataset's resources (ids, file hashes or locations, row counts).

run_identification(profiled, *, rule_set=None, rule_sets=None, policy=None, llm_model=None, llm_budget=None, llm_cache=None, llm_refresh=False, llm_parallel=4, llm_progress=None, llm_pricing=None, llm_api_key=None, settings=None, run_id=None)

Identify one dataset. Never mutates profiled; problems become warnings on the run.

rule_sets are all evaluated and combined by the policy; rule_set is shorthand for a single one. With neither, the built-in core rules are used.

apply_review(content, proposals, edits, *, author)

Apply a reviewer's edits. The inputs are not changed.

Parameters:

Name Type Description Default
content Dataset

The version's dataset.

required
proposals list[Proposal]

The version's proposals.

required
edits list[ReviewEdit]

The reviewer's accepts, edits and rejections, in order.

required
author str

The reviewer.

required

Returns:

Type Description
Dataset

The new dataset, the new proposals and one change per edit, with the property's

list[Proposal]

value before and after it.

Raises:

Type Description
ValueError

An unknown target or property, an invalid value, or nothing to accept or reject.

new_version(content, *, number, author, parent=None, note=None)

A new immutable dictionary version of the content.

find(dataset, target)

The dataset, resource or element with this id, or None.

get_property(obj, prop)

A property's value as text (lists comma-separated, code lists as JSON), or None.

set_property(dataset, target, prop, text)

Set a property, validated by the model. Raises ValueError for unknown targets or values.

knowtation_core.identify.history

Review history: what each review changed, and an element's history across versions.

ReviewChange

Bases: _Change

One change a review made to an element property; stored with the review's version.

HistoryChange

Bases: _Change

A review change, or what a run proposed or kept for an element property.

VersionRecord

Bases: BaseModel

A stored dictionary version, as the history reads it.

HistoryEntry

Bases: BaseModel

One version in a history, with its changes.

reconstruct_changes(before, before_proposals, after, after_proposals)

A review's changes rebuilt from its version and its parent, for reviews that predate them.

New edited proposals are edits; proposals whose status became accepted or rejected are accepts and rejections. An accept of a proposal that was already accepted can't be seen.

element_history(versions, target=None)

Every version, newest first, with what its review changed.

Parameters:

Name Type Description Default
versions list[VersionRecord]

The dataset's versions, in any order.

required
target str | None

An element (or resource or dataset) id: only its changes, and for runs also what each run proposed or kept for it. Without one, only reviews have changes.

None

Returns:

Type Description
list[HistoryEntry]

One entry per version, newest first.

review_log_csv(versions)

Every review change as CSV, oldest first: for audits and checking rules against reviews.

knowtation_core.rules

Versioned identification rules.

AnalysisReport dataclass

Per-rule statistics, every conflict found, and where rules leave properties empty.

Conflict dataclass

One element property on which rules voted for different values.

RuleStats dataclass

Analysis of one rule; accuracy is None when no benchmark value covers its votes.

accuracy property

Share of judged votes that match the benchmark value, or None if none were judged.

AppliesWhen

Bases: BaseModel

When a rule pack is picked automatically for a dataset. All given conditions must hold.

Rule

Bases: BaseModel

One identification rule: conditions, the values it proposes, a weight and its tests.

RuleSet

Bases: BaseModel

A versioned set of rules. Packs say in applies_when which datasets they suit.

content_hash property

SHA-256 of the rule set's canonical JSON.

RuleTest

Bases: BaseModel

An element the rule should match (with the values it proposes) or should not match.

TestElement

Bases: BaseModel

A made-up element for a rule test: just the facts the rule's conditions read.

When

Bases: BaseModel

Conditions on one element. All given conditions must hold.

ValidationReport dataclass

Problems found in a rule set. Errors and test failures block an import.

ok property

True when nothing blocks the rule set.

problems property

Errors and test failures together, in that order.

analyse(rule_sets, datasets, benchmarks=None)

Analyse how the rules of rule_sets vote on datasets (optionally against benchmarks).

evaluate_rules(rs, dataset, default_weight=0.6)

The proposals of every rule that matches an element of the dataset.

builtin_rule_set()

The built-in core rule set.

load_rule_set(path)

Read a rule set from a YAML file.

parse_rule_set(text)

Read a rule set from YAML text.

applies(rule_set, dataset)

Whether a pack's applies_when holds for the dataset. No conditions: never automatic.

select_rule_sets(core, packs, dataset)

core first, then each pack (other than core) that applies, in the given order.

rule_set_json_schema()

The JSON Schema of a rule set, generated from the model (usable by editors).

run_rule_tests(rule)

Failures of one rule's tests, each naming the rule and the test element.

validate_rule_set(rs, *, require_tests=False)

Lint the rule set and run every rule's tests.

knowtation_core.packs

Rule packs generated from official vocabularies, and the importers that build them.

An importer downloads a source's machine-readable file, and import_pack turns it into a versioned rule pack under builtin/packs/<id>/<version>.yaml, recording the URL, the date and the file's hash. The same upstream file never makes a second version; a changed file makes a new version and never overwrites an old one.

Importer

Bases: ABC

Reads one upstream source and builds a rule pack from it.

fetch(client)

Download the source's machine-readable file (one request by default).

build(content) abstractmethod

The rule pack for this content. Its version and source are set by import_pack.

release(content)

The upstream release named in the content, if it names one.

import_pack(importer, out_dir=BUILTIN_PACKS, *, content=None, client=None, today=None)

Build and write a pack version; returns its path and whether it is new.

content is the upstream file (downloaded when not given). A version whose source hash matches is returned as it is; otherwise a new version named after the date is written.

builtin_packs()

Every version of every pack shipped with Knowtation, oldest version first per pack.

Loaded once per process (the files don't change); treat the rule sets as read-only.

knowtation_core.confidence

Confidence scoring for proposals.

ConfidencePolicy

Bases: BaseModel

A versioned set of parameters for scoring and combining proposals.

content_hash property

SHA-256 of the policy's canonical JSON.

param(name, prop=None, default=None)

A dotted parameter such as 'llm.cap', with any override for prop applied.

Parameters that exist only as overrides (such as rules.cap) fall back to default.

builtin_policies()

Every built-in policy, default first.

default_policy()

The built-in default policy.

load_policy(path)

Read a policy from a YAML file.

parse_policy(text)

Read a policy from YAML text.

band(confidence, policy)

The band (high, medium or low) a confidence falls in under the policy.

best(scored)

The chosen proposal per (target, property): highest confidence, then source, then value.

source_score(p, policy)

The score one source contributes, before combining.

knowtation_core.provenance

Where a proposed value comes from: observed, declared, inferred or reviewed.

provenance_of(p)

The proposal's own label if set, else one derived from its source and property.

labelled(proposals)

Copies of the proposals with provenance filled in.

knowtation_core.exporters

Standard profiles: write Knowtation's results out in open standards.

ExportResult dataclass

An export: the document, its media type and the validator's findings.

export(dataset, profile)

Export with the named profile. Raises KeyError for an unknown profile.

knowtation_core.exporters.document

Data dictionary documents for people: Markdown, CSV, DOCX and PDF from one model.

DictionaryDocument dataclass

A data dictionary document, ready to render in any format.

ResourceSection dataclass

One resource's part of a data dictionary document.

Row dataclass

One element's line in a data dictionary document.

Format dataclass

A document format's media type and file extension.

build_document(dataset, proposals, version=None)

The data dictionary document for a dataset version and its proposals.

render_pdf(doc)

The document as PDF, typeset with Typst and the bundled Noto fonts.

render_csv(doc)

The document as CSV, one row per element.

render_markdown(doc)

The document as Markdown.

render_docx(doc)

The document as Word (DOCX), landscape.

render(doc, fmt)

Render a document. Raises KeyError for an unknown format.

knowtation_core.evaluate

Score a run against a benchmark data dictionary.

Benchmark

Bases: BaseModel

A benchmark data dictionary: the right value of each property, by target.

Score

Bases: BaseModel

Counts for one property: expected, predicted and correct values.

precision property

Share of predicted values that are correct.

recall property

Share of expected values that were predicted correctly.

EvaluationReport

Bases: BaseModel

Scores by property for one dataset.

load_benchmark(path)

Read a benchmark data dictionary from YAML.

evaluate(dataset, benchmark)

Score a dataset against a benchmark data dictionary, property by property.

Per property: expected (benchmark values), predicted (non-empty values on benchmark targets) and correct (matching, case-insensitive).

knowtation_core.reference

The reference: Knowtation's LinkML schema is the single source.

Everything the reference shows (properties and where they apply, roles, data types, aggregations, structures, resource kinds, provenance labels, confidence bands, export profiles, document formats) is written in schema/knowtation.yaml. This module only reads it: helpers return pieces of it, and :func:markdown renders it as one Markdown document. Nothing here is stored or edited separately.

schema_text() cached

The schema file exactly as stored.

load_schema() cached

The schema parsed as data (no reshaping).

enum_values(name)

The permissible values of one enum.

reviewable_properties()

Each reviewable property and the classes it applies to (from reviewable annotations).

inherited_properties()

File properties taken from the dataset when a file has none (inherited annotations).

render_inherited_ts()

The inherited file properties for the web app (web/src/lib/inherited.generated.ts).

markdown()

The reference as one Markdown document, generated from the schema.