An article package for three languages: from the author's chat to the CMS

Build an independent UK/RU/EN package with a manifest and Python checks: seven public files, a source revision, hashes and separate working records.

Three language versions have separate content and one agreed package structure.
Three language versions have separate content and one agreed package structure.

A chat response can be a complete thought without being a package that a CMS can accept. A conversation can easily retain two versions of an introduction, a newer Ukrainian text and a translation of the previous version. The person transferring the article needs to know exactly which files belong to one revision.

Keep this Python exercise in the editorial package, with make_demo.py, validate_package.py and negative_demo.py together. Keep it separate from the Symfony article_demo project. It needs Python 3.12 and its standard library.

The earlier article “Article: how a personal journal becomes a product” introduced the idea of a package containing text, metadata and a cover. Now we will assemble a small independent example and check it with a program. Its subject is three envelopes for notes. The text is fictional, and its format does not reproduce a particular CMS contract.

Seven public files and separate working records

Each language needs an article body and metadata. One cover serves all three versions, with a localized description. Our exercise therefore has exactly seven public files.

Part Count Purpose
public/<locale>/body.html 3 UK, RU and EN bodies without the page title
public/<locale>/metadata.json 3 Language, title, summary, SEO fields and cover description
public/assets/cover.webp 1 Shared illustration file
manifest.json 1 separate file Relationships, source revision and explicit file allowlist
internal/review.json 1 separate file Working acceptance state

The manifest accompanies the handoff but does not become article text. The working record also stays out of reader-facing HTML. Export must select the seven explicitly listed files instead of recursively archiving the entire directory.

This separation is useful for one author too. A future work session should not have to reconstruct decisions from message order. A file of author comments may be necessary for editing, but readers should not receive it alongside an illustration.

Content identity and source revision

content_key identifies the teaching example. It is not a numeric database ID, a publication-folder number or an established website address. Mapping it to a particular CMS happens later.

Here, source_revision is calculated from the Ukrainian body and Ukrainian metadata. First we compute each file's SHA-256 digest, then SHA-256 over the two consecutive fixed-size digests. The Python hashlib documentation describes hashing bytes with SHA-256 and obtaining a digest.

Every language version explicitly references this source revision. If the Ukrainian body or summary changes, the old reference no longer matches the new bytes. A file's modification date cannot establish this relationship: copying can change that date without changing its content.

The relationship records the translation's declared source. It does not prove that the translation conveys its meaning correctly. Replacing a revision value does not update sentences in another language.

Create an independent package

Below is the complete generator, make_demo.py. Save the validator from the next section beside it: the generator uses its revision function. The code contains all three short texts and their localized metadata.

You also need a finished WEBP cover. This example uses an illustration with three sets of cards and envelopes. If you choose another picture, first align each language's cover_alt with what is actually visible. The generator copies supplied bytes; it neither draws nor decodes the image.

"""Create new, synthetic teaching content and its explicit manifest."""
import hashlib
import json
import sys
from pathlib import Path
from validate_package import COVER, LOCALES, revision_for

TEXT = {
    "uk": {
        "title": "Три конверти для нотаток",
        "summary": "Вигаданий приклад: питання, дія та перевірка на окремих картках.",
        "body": "<h2>Правило картки</h2>\n<p>На столі стоять три конверти. На картці я записую питання, дію та результат. Картка переходить у конверт завершених лише після перевірки результату.</p>\n<p>Це вигаданий приклад для вправи з пакування тексту. Він не описує проведеного експерименту.</p>\n",
        "cover_alt": "Три набори світлих карток із рельєфними гілками та пастельні конверти у відкритій паперовій папці.",
    },
    "ru": {
        "title": "Три конверта для заметок",
        "summary": "Вымышленный пример: вопрос, действие и проверка на отдельных карточках.",
        "body": "<h2>Правило карточки</h2>\n<p>На столе стоят три конверта. На карточке я записываю вопрос, действие и результат. Карточка переходит в конверт завершённых только после проверки результата.</p>\n<p>Это вымышленный пример для упражнения по упаковке текста. Он не описывает проведённого эксперимента.</p>\n",
        "cover_alt": "Три набора светлых карточек с рельефными ветками и пастельные конверты в открытой бумажной папке.",
    },
    "en": {
        "title": "Three envelopes for notes",
        "summary": "A fictional example: a question, an action and a check on separate cards.",
        "body": "<h2>The card rule</h2>\n<p>Three envelopes stand on a desk. On a card I record a question, an action and a result. The card moves to the completed envelope only after the result has been checked.</p>\n<p>This is a fictional example for a text-packaging exercise. It does not describe an experiment that took place.</p>\n",
        "cover_alt": "Three sets of pale cards with embossed branches and pastel envelopes in an open paper portfolio.",
    },
}


def json_bytes(value):
    return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8")


def make_demo(directory, cover_bytes):
    root = Path(directory)
    root.mkdir(parents=True, exist_ok=False)
    files = {COVER: cover_bytes}
    for loc in LOCALES:
        item = TEXT[loc]
        files[f"public/{loc}/body.html"] = item["body"].encode("utf-8")
        files[f"public/{loc}/metadata.json"] = json_bytes({
            "language": loc, "title": item["title"], "summary": item["summary"],
            "seo_title": item["title"], "seo_description": item["summary"],
            "cover_alt": item["cover_alt"],
        })
    revision = revision_for(files["public/uk/body.html"], files["public/uk/metadata.json"])
    manifest = {
        "schema": "article-package.example.v1", "content_key": "envelope-note",
        "source_locale": "uk", "source_revision": revision,
        "translations": {loc: {"body": f"public/{loc}/body.html",
            "metadata": f"public/{loc}/metadata.json", "source_revision": revision}
            for loc in LOCALES},
        "assets": [{"path": COVER, "role": "cover"}],
        "files": {name: hashlib.sha256(data).hexdigest() for name, data in files.items()},
    }
    files["manifest.json"] = json_bytes(manifest)
    files["internal/review.json"] = json_bytes({
        "author_acceptance": "pending", "translation_review": "pending",
    })
    for name, data in files.items():
        path = root / name
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
    return root


if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise SystemExit("usage: python make_demo.py NEW_DIRECTORY COVER_FILE")
    make_demo(sys.argv[1], Path(sys.argv[2]).read_bytes())

The generator refuses to create a package over an existing directory. This simple rule prevents unnoticed mixing of old and new files. Working records are created after the allowlist has been formed, so they do not enter it.

In this miniature example the SEO title matches the title, and the SEO description matches the summary. For a real article that is a separate editorial decision. Checking that a field is nonempty does not assess its quality.

What the program checks

The validator, validate_package.py, defines a narrow profile: exactly UK, RU and EN, prescribed paths, one cover and no additional public files. Every text file must decode as UTF-8. JSON with a repeated key is rejected because two values for one property introduce ambiguity. This uses object_pairs_hook from the Python json documentation.

Paths must remain inside the staged directory. The code rejects absolute paths, .. and symbolic links, then checks the resolved path. The pathlib documentation explains resolve and is_relative_to. Eight megabytes per file is a local rule of this exercise.

The program operates on an already staged directory that nobody is changing concurrently. It does not extract arbitrary archives or address filesystem access races. That is a significant boundary of this particular path-checking approach.

"""Check a staged teaching package; this is not a CMS importer."""
import hashlib
import json
import re
import sys
from pathlib import Path

LOCALES = ("uk", "ru", "en")
COVER = "public/assets/cover.webp"
LIMIT = 8 * 1024 * 1024


def require(condition, message):
    if not condition:
        raise ValueError(message)


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        require(key not in result, "duplicate JSON key")
        result[key] = value
    return result


def decode_json(data):
    def bad_constant(_):
        raise ValueError("nonstandard JSON constant")
    return json.loads(data.decode("utf-8"), object_pairs_hook=unique_object,
                      parse_constant=bad_constant)


def read_relative(root, name):
    require(isinstance(name, str) and
            re.fullmatch(r"[a-z0-9][a-z0-9._/-]*", name), "invalid path")
    parts = name.split("/")
    require(all(part not in ("", ".", "..") for part in parts), "invalid path")
    path = root
    for part in parts:
        path = path / part
        require(not path.is_symlink(), "symbolic link")
    resolved = path.resolve(strict=True)
    require(resolved.is_relative_to(root) and resolved.is_file(), "not a local file")
    require(resolved.stat().st_size <= LIMIT, "file too large")
    return resolved.read_bytes()


def revision_for(body, metadata):
    return hashlib.sha256(hashlib.sha256(body).digest() +
                          hashlib.sha256(metadata).digest()).hexdigest()


def validate(directory):
    root = Path(directory).resolve(strict=True)
    require(root.is_dir(), "not a directory")
    manifest = decode_json(read_relative(root, "manifest.json"))
    require(isinstance(manifest, dict) and set(manifest) == {
        "schema", "content_key", "source_locale", "source_revision",
        "translations", "assets", "files"}, "manifest fields")
    require(manifest["schema"] == "article-package.example.v1", "schema")
    require(manifest["content_key"] == "envelope-note", "content key")
    require(manifest["source_locale"] == "uk", "source locale")
    translations = manifest["translations"]
    require(isinstance(translations, dict) and set(translations) == set(LOCALES),
            "locale set")
    require(manifest["assets"] == [{"path": COVER, "role": "cover"}], "asset allowlist")
    expected = {f"public/{loc}/{name}" for loc in LOCALES
                for name in ("body.html", "metadata.json")} | {COVER}
    hashes = manifest["files"]
    require(isinstance(hashes, dict) and set(hashes) == expected, "file allowlist")
    data = {}
    for name in sorted(expected):
        data[name] = read_relative(root, name)
        require(bool(data[name]), "empty file")
        digest = hashes[name]
        require(isinstance(digest, str) and re.fullmatch(r"[0-9a-f]{64}", digest),
                "hash format")
        require(hashlib.sha256(data[name]).hexdigest() == digest, "hash mismatch")
    seen = set()
    for path in (root / "public").rglob("*"):
        require(not path.is_symlink(), "symbolic link")
        if path.is_file():
            seen.add(path.relative_to(root).as_posix())
        else:
            require(path.is_dir(), "unsupported file type")
    require(seen == expected, "unexpected public file")
    revision = revision_for(data["public/uk/body.html"], data["public/uk/metadata.json"])
    require(manifest["source_revision"] == revision, "source revision")
    for loc in LOCALES:
        body, meta = f"public/{loc}/body.html", f"public/{loc}/metadata.json"
        require(translations[loc] == {"body": body, "metadata": meta,
                                     "source_revision": revision}, "locale mapping")
        require(bool(data[body].decode("utf-8").strip()), "empty body")
        metadata = decode_json(data[meta])
        require(isinstance(metadata, dict) and set(metadata) == {
            "language", "title", "summary", "seo_title", "seo_description",
            "cover_alt"}, "metadata fields")
        require(metadata["language"] == loc, "metadata locale")
        require(all(isinstance(v, str) and v.strip() for v in metadata.values()),
                "empty metadata")
    return {"status": "complete", "locales": list(LOCALES), "files": len(expected),
            "publication": "not_requested"}


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("usage: python validate_package.py DIRECTORY")
    try:
        print(json.dumps(validate(sys.argv[1]), ensure_ascii=False))
    except (ValueError, OSError, UnicodeError, KeyError, TypeError) as error:
        print(f"rejected: {error}", file=sys.stderr)
        raise SystemExit(1)

The files mapping serves two purposes: it limits the contents and records the expected bytes. An additional image would require an explicit profile change. Automatically accepting any file under assets would remove that boundary.

A matching hash establishes that a file matches its declared bytes. It authenticates neither the author nor the truth of the text: somebody able to change both the file and manifest can recalculate both values. Transfer the checked package as an immutable snapshot and make the trust decision separately.

Run the check and introduce two faults

Save both Python files in the same working directory. These commands create a new demo directory and validate it. The example uses the Python 3.12 standard library.

python make_demo.py demo cover.webp
python validate_package.py demo

A positive case does not yet explain whether the program notices a relevant fault. The next file, negative_demo.py, therefore works on two temporary copies. In the first, it replaces the revision supposedly used for the RU translation. In the second, it adds an internal note to the public area.

"""Two deliberate faults, each applied to a temporary copy."""
import json
import shutil
import sys
import tempfile
from pathlib import Path
from validate_package import validate


def expect_rejection(directory, expected):
    try:
        validate(directory)
    except ValueError as error:
        if str(error) != expected:
            raise AssertionError(f"unexpected rejection: {error}") from error
    else:
        raise AssertionError("fault was accepted")


with tempfile.TemporaryDirectory() as temporary:
    stale = Path(temporary) / "stale"
    shutil.copytree(sys.argv[1], stale)
    path = stale / "manifest.json"
    manifest = json.loads(path.read_text(encoding="utf-8"))
    manifest["translations"]["ru"]["source_revision"] = "0" * 64
    path.write_text(json.dumps(manifest), encoding="utf-8")
    expect_rejection(stale, "locale mapping")
    extra = Path(temporary) / "extra"
    shutil.copytree(sys.argv[1], extra)
    (extra / "public/review.txt").write_text("internal note", encoding="utf-8")
    expect_rejection(extra, "unexpected public file")
print("Both deliberate faults were rejected.")

Running python negative_demo.py demo should finish successfully only when both changes are rejected for the expected reason. The original directory remains usable because the faults were introduced into copies.

The first fault explains why revision mapping matters even when every file hash is correct. The second explains why checking that required files exist is insufficient: an extra file can also spoil a handoff.

The boundary of automated completeness

After this check, we know that the declared file set is consistent in structure and bytes. Other questions require other kinds of review.

Question How to check it
Do the three languages convey the same meaning? Compare translations with the source
Can the HTML be displayed safely? Apply the CMS markup policy and processing
Is the file a valid image? Decode it, inspect dimensions and review it visually
Are CMS fields mapped correctly? Inspect the current importer and perform a test handoff
Is publication authorized? Obtain the author's separate decision

The name cover.webp does not establish the file format. Likewise, nonempty HTML bytes can contain unsuitable markup. The validator deliberately does not present these separate tasks as completed.

Once the author accepts the content, the importer must still map locales, category, tags and cover to existing entities. A repeated handoff also needs defined behavior: update a particular article or refuse, instead of accidentally creating a duplicate. These are integration properties that our local example does not test.

The exercise manifest contains no target environment, publication time or CMS execution command. File readiness completes one stage. The next stage begins with a concrete package, its verified revision and an explicit decision about the action that is allowed.

  1. Editorial Three languages, one article: how to spot an outdated translation
  2. Symfony Core Reimporting content: where updates are allowed and where to stop
  3. Knowledge & AI AI prepares the publication, a human decides: preserving the exact approved version
  4. Editorial Article: how a personal journal becomes a product

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article