Metadata-Version: 2.4
Name: ckanext-ai-translation
Version: 0.1.1
Summary: AI translations of CKAN dataset metadata into the portal's languages, read and applied by an editor
Home-page: https://github.com/bjornhagstrom/ckanext-ai-translation
Author: Bjorn Hagstrom
Author-email: bjorn@hagstrom.nu
License: MIT
Project-URL: Source, https://github.com/bjornhagstrom/ckanext-ai-translation
Project-URL: Changelog, https://github.com/bjornhagstrom/ckanext-ai-translation/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/bjornhagstrom/ckanext-ai-translation/issues
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: ckanext-ai-connector<0.4,>=0.3
Requires-Dist: pydantic<3,>=2
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# ckanext-ai-translation

AI translations of CKAN dataset metadata (title, description, keywords) into the portal's other languages, read,
corrected and applied by an editor. Nothing is saved or published by itself.

> **Status: alpha (`0.1.1`).** Split out of
> [ckanext-ai-metadata](https://github.com/bjornhagstrom/ckanext-ai-metadata) (until 0.3.0 ckanext-metadata-assistant), which
> until then held these features. Developed against CKAN 2.12; try it on a test installation first.

## Installation

Requirements: CKAN 2.11 or 2.12 (tested on 2.11.1, the newest 2.11 and 2.12), Python 3.10 or later,
[ckanext-ai-connector](https://github.com/bjornhagstrom/ckanext-ai-connector) 0.3 (installed with this extension, see
below), and for the multilingual fields [ckanext-scheming](https://github.com/ckan/ckanext-scheming) and
[ckanext-fluent](https://github.com/ckan/ckanext-fluent). ckanext-fluent's release on PyPI (1.0.0) does not load on
CKAN 2.11 or 2.12; install it from its repository (the tests use commit `eb5581a`):

    pip install "ckanext-fluent @ https://github.com/ckan/ckanext-fluent/archive/eb5581ac952cd1d0d3ceac78b43adb97e7068895.tar.gz"
    pip install ckanext-ai-translation

This also installs [ckanext-ai-connector](https://github.com/bjornhagstrom/ckanext-ai-connector) 0.3, a separate
extension with its own plugin (`ai_connector`), settings page (`/ckan-admin/ai`) and README. It holds the AI
connection (service, model, key, time limits, the call itself) that the AI extensions share, so the model and key
are set once for all of them. If 0.3 is already installed, for example with ckanext-ai-metadata, pip keeps it.

Add the plugins, with `ai_translation` before `fluent` (see [Keywords on the dataset page](#keywords-on-the-dataset-page)):

    ckan.plugins = … ai_connector ai_translation scheming_datasets fluent …

Then create the table of proposals, rebuild the search index once (for the keywords in each language), and check the
setup:

    ckan -c $CKAN_INI db upgrade -p ai_translation
    ckan -c $CKAN_INI search-index rebuild
    ckan -c $CKAN_INI ai-translation doctor

The AI connection (service, model and key) is set on ckanext-ai-connector's page `/ckan-admin/ai`. A worker for the
background jobs is optional (see [Background jobs and limits](#background-jobs-and-limits)).

## Where the data is

- **Applied translations are the dataset's own data.** They are stored in the standard ckanext-fluent multilingual fields
  (`title_translated`, `notes_translated`, the multilingual keywords), written by `package_patch` as the editor who
  applies them. They stay if this extension is removed.
- **This extension stores only work in progress and settings:** pending translation proposals (its own table), the
  instruction given to the AI, the further fields it translates, and (in ckanext-ai-connector) the model chosen for translation.

## Schema, validators and command

The languages come from the dataset schema (ckanext-scheming): from the file named by
`ckanext.ai_translation.schema_file`, else the schema scheming has loaded. Either one hidden field carries the settings
(`translation_targets`, `source_language`, `target_languages`, `translation_glossary`, `translation_instructions`) and
stores the translation checksums with the validator `ai_translation_state`, or the settings are read from the
multilingual fields' `form_languages`. An optional top-level block `ai_translation: {level, source}` says where the
requirement comes from (`source`) and, only when the languages come from the multilingual fields, how strongly a missing
translation is reported (`level`; a settings field gives a level per language in `target_languages` instead). The rules `translation_missing` and
`translation_outdated` follow from it.

For ckanext-fluent fields the extension registers `ai_translation_fluent_from_core`, `ai_translation_fluent_to_core`,
`ai_translation_fluent_tags_strip` and `ai_translation_fluent_tags_output`. A complete example is
[fluent_schema.yaml](https://github.com/bjornhagstrom/ckanext-ai-translation/blob/main/ckanext/ai_translation/examples/fluent_schema.yaml)
(`scheming.dataset_schemas = ckanext.ai_translation.examples:fluent_schema.yaml`). After adding the multilingual fields
to a schema, `ckan -c $CKAN_INI ai-translation migrate-multilingual` copies existing titles and descriptions into them
(`--dry-run` first).

For a fluent title, `form_snippet: ai_translation_title.html` gives one box per language and lets the first one fill in
the dataset's URL, as CKAN's own title does (fluent's own snippet leaves the URL empty).

## AI connection

The AI connection is [ckanext-ai-connector](https://github.com/bjornhagstrom/ckanext-ai-connector)'s. This extension is
its own consumer (`ai_translation`) with one purpose (`translate`), so a sysadmin can give translation a model of its
own on the AI settings page.

## Translating

The action `ai_translation_translate_dataset` (`id` of a saved dataset, or `dataset` with an unsaved form draft;
optional `languages`) sends the title, description and keywords (and the further fields that are on, see "More
fields") in the source language to the AI, one request per
target language, with that language's glossary and guidance from the schema. It returns
`{"suggestions": [...], "failed": [...]}`: each suggestion names the source field, the multilingual field and the
language, with the source text beside it. Nothing is saved: an editor reads and applies each suggestion. Only a signed-in
user who may edit the dataset (create it, for a new one) may ask, and access is checked before any AI call: a portal that
lets anonymous visitors create datasets (`ckan.auth.anon_create_dataset`) still does not let them ask for a paid
translation, which would count against no one's quota.

### More fields

Besides the title, description and keywords, the AI can translate further multilingual text fields of the schema (any
ckanext-fluent field ending in `_translated`, e.g. `provenance_translated`), but only the ones the portal turns on, one
at a time:

- on the page **/ckan-admin/ai-translation/fields** (tab "More fields"), which lists the schema's further multilingual
  fields with a box to tick; it is stored as the runtime option `ckanext.ai_translation.translate_fields`;
- or in the server's configuration, `ckanext.ai_translation.translate_fields = provenance usage_note` (source field
  names, without `_translated`; `none` for none);
- or, when neither names any, with `ai_translate: true` on the multilingual field in the schema.

For each such field the AI service gets its name, its label, whether it is Markdown (`fluent_markdown`, or a
`form_snippet` such as `fluent_markdown.html`), and its text in the source language; nothing else. Tick only fields whose
texts may be sent to the AI service. At most 8 fields (the page refuses more, and the setup check names any left out); a
text longer than 5000 characters is left out rather than cut, and the editor is told so when nothing else is left to
translate. A multilingual list (`fluent_tags`) is translated from the keywords and is no further field. The fields come
from the whole schema, also when a settings field (`translation_targets`) names the ones the rules check: the rules
check the fields that settings field names (or, without one, every multilingual field), turned on for the AI or not. The
catalogue's proposals ask the AI only about missing translations it would write, per language. A proposal is not
offered or applied once the source text of any of its texts has changed. A job that waits in the queue sends only the
further fields that are still turned on when it runs, and a translation far longer than its source is left out. The answer is asked for with a schema that has a
`fields` list only when there are further fields, so the call is unchanged for a portal without them.

The whole instruction to the AI is editable by sysadmins on **/ckan-admin/ai-translation** (a tab of the sysadmin
pages), stored as the runtime option `ckanext.ai_translation.instructions`; the built-in text is only the default
(`{source}` and `{target}` become the languages' names). "Try the translation" runs the text in the form on a dataset
without saving the text or changing the dataset.

## In the dataset form

The extension adds a **Translations** section to the dataset form (before the buttons; through
`package/snippets/package_form.html`, so it works with ckanext-scheming's form too). It is shown only to someone who may
edit the dataset (create one, on a new dataset) and only when the schema names languages to translate into. It shows
the translation findings for the form as it is (checked again by the action `ai_translation_check` when a text or a
translation changes; no AI), and a button **Get translations** that sends the form's texts to
`ai_translation_job_start` and waits for the job. Each suggestion is shown next to its source text and can be edited;
**Use** puts it into the form's input for that field and language (ckanext-fluent's `title_translated-en`; keywords are
added to the ones there). Nothing is saved until the editor saves the dataset. An open proposal for the dataset (see
below) is shown the same way, with a link to the proposals page.

## Keywords on the dataset page

CKAN shows a dataset's tags, its search and its tag facet in the source language only: the translated keywords live in
the multilingual field (e.g. `keywords_translated`). So each target language's keywords are indexed in a field of their
own, `vocab_<field>_<language>` (e.g. `vocab_keywords_translated_en`; CKAN's Solr schema keeps `vocab_*` as lists of
strings), and on a page in a target language the tag row (`package/read.html`, block `package_tags`) shows that
language's keywords, each linking to a search on that field, and a facet with them (under the multilingual field's
label, e.g. "Tags (English)") stands next to CKAN's tag facet, which stays. On the source language's
page, and for a dataset without keywords in the page's language, CKAN's own tags are shown. After installing or
upgrading, rebuild the search index once (`ckan search-index rebuild`).

CKAN's start page asks only for the facets in `search.facets`, not for those an extension adds, so a theme that lists
popular tags there can ask the helper `h.ai_translation_popular_keywords(limit)`: the most used keywords in the page's
language among the public datasets, in the shape of `h.get_facet_items_dict` plus each one's `url`, or `None` on the
source language's page (and when no dataset has keywords in the page's language), for the theme to show CKAN's tags.

With ckanext-fluent, the multilingual keyword field's own row (its display snippet `fluent_tags.html`) links each word
to the search on its language's keywords as well; for that, `ai_translation` must come before `fluent` in
`ckan.plugins`, else fluent's row links to CKAN's tags, which hold only the source language.

What the page shows is what is exported. ckanext-dcat writes `dcat:keyword` from the tags (the source language, with no
language tag), or from `tags_translated` when the schema has that field. When the translated keywords live in another
field, add this extension's profile after the portal's own, and each target language's keywords are exported with their
language tag (`"map"@en`):

    ckanext.dcat.rdf.profiles = euro_dcat_ap_3 ai_translation_keywords

The profile reads no RDF, and adds nothing when the dataset has `tags_translated` (ckanext-dcat writes it) or the
schema does not translate the keywords. The profile is known to ckanext-dcat once this extension is installed; a profile named in `ckanext.dcat.rdf.profiles` that is not
installed stops every RDF page, so remove the name before uninstalling.

## Proposals for the whole catalogue

The table of proposals is created with

    ckan -c $CKAN_INI db upgrade -p ai_translation

Then

    ckan -c $CKAN_INI ai-translation propose --limit 20 [--organization NAME] [--include-outdated] [--dry-run]

asks the AI for translations of the datasets whose translation is missing (or, with `--include-outdated`, older than the
source text) and stores them as proposals (table `ai_translation_proposal`). Nothing is saved to a dataset. A proposal
fills only translations that are missing; an existing one is proposed for replacement only with `--include-outdated`.
Private datasets are included: their texts, too, go to the AI service. A dataset costs at most one paid AI call per
language, and only for the languages and texts whose translation is missing (with `--include-outdated`, all of them);
within the limits below, so start with a small `--limit`; a dataset with an open or rejected proposal for the same source
text is not asked again (after a proposal is applied, languages still missing, e.g. one that failed, are asked for).

Editors read the proposals on **/ai-translation/proposals** (the extension's tab "AI translation" on the dashboard of
editors and organization admins, and linked from the dataset form; any signed-in user may open it and sees only the
datasets of the organizations where they are editor or admin). Sysadmins have the same list, of all datasets, under the
extension's one tab in the sysadmin pages (/ckan-admin/ai-translation/proposals), next to the instruction to the AI.
Each proposal is shown next to the source text and can be corrected before it is applied, one at a time or several
ticked as read. Applying or rejecting one proposal answers in its own box without reloading the page.
Applying writes with `package_patch` as that editor, with their permissions, and the checksums of the source text are
updated as for any save. A proposal whose source text has changed since it was made is refused and marked stale.

    ckan -c $CKAN_INI ai-translation doctor

lists what translation needs and what is missing: the table, the AI connection, the languages, the workers and the
limits reached today. It exits with 1 when something must be fixed.

## Background jobs and limits

`ai_translation_job_start` (the same keys as the action) and `ai_translation_job_status` (`job_id`; only the person who
started it, and sysadmins) let a page hand the slow AI call to a worker:

    ckan -c $CKAN_INI ai-translation worker

listens on the queue `ai_translation`. `ckanext.ai_translation.jobs` is `auto` (default: queue when a worker listens,
else run in the web request), `on` or `off`. With Redis, limits hold across all workers and web processes (Redis keys
`ai_translation:*`, separate from any other extension's): `max_concurrent` (4), `max_per_minute` (0 = none),
`max_jobs_per_user` (3), `max_per_user_per_day` (0), `breaker_failures` (5) and `breaker_seconds` (30),
`slot_wait_seconds` (120) and `retry_pauses` (`5 15 45`), each under `ckanext.ai_translation.`. Without Redis
translation still works, without limits.

## For other extensions

`ckanext/ai_translation/api.py` is the only public module (`API_VERSION = 1`): `languages()`, `source_language()`,
`findings(dataset)` (the translation findings as plain dicts) and `is_ready()`. None of them raises, saves anything or
calls an AI service. Import it in a `try`, and check `API_VERSION` for what you need.

## Development

The Python tests run in Docker with CKAN, PostgreSQL, Solr and Redis (CKAN 2.12 unless `CKAN_VERSION` and
`SOLR_VERSION` say otherwise, as in CI: 2.11.1, 2.11 and 2.12):

    docker compose -f docker-compose.test.yml run --build --rm tests
    docker compose -f docker-compose.test.yml down -v

The JavaScript tests need only Node.js:

    node --test ckanext/ai_translation/tests/js/*.js

## License

MIT.
