diff --git a/doclang/README.md b/doclang/README.md
index 5292f78..81fc8c4 100644
--- a/doclang/README.md
+++ b/doclang/README.md
@@ -93,6 +93,9 @@ doclang pack markup.dclg --pages screenshots/
doclang pack markup.dclg --page a.png --page b.png
doclang pack markup.dclg --asset chart.svg=exports/diagram.svg
doclang pack markup.dclg --assets payload/
+doclang pack markup.dclg --source report.pdf --keep-source-name # kept as source.pdf
+doclang pack markup.dclg --source upload.bin --source-name "Q3 report.pdf" # also kept as source.pdf
+doclang pack markup.dclg --audio episode-12.mp3 --source episode-12.mp3 --keep-source-name # reuses audio/1.mp3
doclang pack markup.dclg --validate
```
diff --git a/doclang/_packaging.py b/doclang/_packaging.py
index 1c81f44..b85780f 100644
--- a/doclang/_packaging.py
+++ b/doclang/_packaging.py
@@ -23,7 +23,41 @@
_CONTENT_TYPES_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/content-types"
_RELATIONSHIPS_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/relationships"
-_DOCUMENT_RELATIONSHIP = "http://doclang.ai/ns/package/2026/relationships/document"
+
+_RELATIONSHIP_TYPES = "http://doclang.ai/ns/package/2026/relationships/"
+_DOCUMENT_RELATIONSHIP = _RELATIONSHIP_TYPES + "document"
+_SOURCE_RELATIONSHIP = _RELATIONSHIP_TYPES + "source"
+_SOURCE_METADATA_RELATIONSHIP = _RELATIONSHIP_TYPES + "source-metadata"
+
+_SOURCE_METADATA_NAMESPACE = "http://doclang.ai/ns/package/2026/source-metadata"
+_SOURCE_METADATA_CONTENT_TYPE = "application/vnd.doclang.source-metadata+xml"
+
+_DEFAULT_CONTENT_TYPES = {
+ "rels": "application/vnd.openxmlformats-package.relationships+xml",
+ "png": "image/png",
+ "jpg": "image/jpeg",
+ "jpeg": "image/jpeg",
+ "webp": "image/webp",
+ "svg": "image/svg+xml",
+ "mp3": "audio/mpeg",
+ "m4a": "audio/mp4",
+ "aac": "audio/aac",
+ "ogg": "audio/ogg",
+ "opus": "audio/ogg",
+ "wav": "audio/wav",
+ "flac": "audio/flac",
+ "mp4": "video/mp4",
+ "webm": "video/webm",
+ "mkv": "video/x-matroska",
+ "mov": "video/quicktime",
+ "pdf": "application/pdf",
+ "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ "doc": "application/msword",
+ "xls": "application/vnd.ms-excel",
+ "ppt": "application/vnd.ms-powerpoint",
+}
_DOCUMENT_CONTENT_TYPE = "application/vnd.doclang.document+xml"
# Positional parts: ``pages/{N}.{ext}`` align with the N-th page, ``audio/{N}.{ext}`` and ``video/{N}.{ext}`` with
@@ -38,38 +72,7 @@
# markup and on parts not accounted for.
_FIRST_ARCHIVE_VERSION = (0, 8)
_REFERENCES_VERSION = (0, 10)
-
-_CONTENT_TYPES_XML = """\
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-"""
-
-_RELS_XML = """\
-
-
-
-
-"""
+_SOURCE_VERSION = (0, 10) # the original source, located by a relationship
PagesInput = Union[
str,
@@ -89,6 +92,8 @@
SourceInput = Union[str, Path, bytes]
_SOURCE_MIMETYPE_PATTERN = re.compile(r"[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+\Z")
+# Extensions taken over from an original file name into the source part's name (``source.``).
+_SOURCE_EXTENSION_PATTERN = re.compile(r"[a-z0-9]{1,16}\Z")
class PackagingError(Exception):
@@ -118,14 +123,19 @@ def _validate_archive_relative_path(path: str, *, label: str) -> None:
raise PackagingError(f"Invalid {label} path: {path!r}")
-def _copy_file(source: Path, destination: Path, *, label: str) -> None:
+Placed = dict[Path, Path]
+"""The input files placed in the stage so far: resolved input path → destination."""
+
+
+def _copy_file(source: Path, destination: Path, *, label: str, placed: Placed) -> None:
_reject_symlink(source, label=label)
_require_file(source, label=label)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
+ placed.setdefault(source.resolve(), destination)
-def _copy_tree_into(source: Path, destination: Path, *, label: str) -> None:
+def _copy_tree_into(source: Path, destination: Path, *, label: str, placed: Placed) -> None:
_reject_symlink(source, label=label)
_require_directory(source, label=label)
destination.mkdir(parents=True, exist_ok=True)
@@ -133,9 +143,10 @@ def _copy_tree_into(source: Path, destination: Path, *, label: str) -> None:
target = destination / item.name
_reject_symlink(item, label=label)
if item.is_dir():
- _copy_tree_into(item, target, label=label)
+ _copy_tree_into(item, target, label=label, placed=placed)
else:
shutil.copy2(item, target)
+ placed.setdefault(item.resolve(), target)
def _place_document(stage: Path, document: Path) -> None:
@@ -151,6 +162,7 @@ def _place_indexed(
file_label: str,
dir_label: str,
number_label: str,
+ placed: Placed,
) -> None:
"""Place 1-based positionally-indexed files (``{N}.{ext}``) under ``stage/subdir``.
@@ -164,20 +176,20 @@ def _place_indexed(
raise PackagingError(f"{number_label} must be positive integers, got {number!r}")
source_path = Path(source)
destination = target_dir / f"{number}{source_path.suffix}"
- _copy_file(source_path, destination, label=file_label)
+ _copy_file(source_path, destination, label=file_label, placed=placed)
return
if isinstance(spec, str | Path):
- _copy_tree_into(Path(spec), target_dir, label=dir_label)
+ _copy_tree_into(Path(spec), target_dir, label=dir_label, placed=placed)
return
for index, source in enumerate(spec, start=1):
source_path = Path(source)
destination = target_dir / f"{index}{source_path.suffix}"
- _copy_file(source_path, destination, label=file_label)
+ _copy_file(source_path, destination, label=file_label, placed=placed)
-def _place_pages(stage: Path, pages: PagesInput) -> None:
+def _place_pages(stage: Path, pages: PagesInput, placed: Placed) -> None:
_place_indexed(
stage,
pages,
@@ -185,10 +197,11 @@ def _place_pages(stage: Path, pages: PagesInput) -> None:
file_label="Page file",
dir_label="Pages directory",
number_label="Page numbers",
+ placed=placed,
)
-def _place_audio(stage: Path, audio: MediaInput) -> None:
+def _place_audio(stage: Path, audio: MediaInput, placed: Placed) -> None:
_place_indexed(
stage,
audio,
@@ -196,10 +209,11 @@ def _place_audio(stage: Path, audio: MediaInput) -> None:
file_label="Audio file",
dir_label="Audio directory",
number_label="Audio track numbers",
+ placed=placed,
)
-def _place_video(stage: Path, video: MediaInput) -> None:
+def _place_video(stage: Path, video: MediaInput, placed: Placed) -> None:
_place_indexed(
stage,
video,
@@ -207,39 +221,131 @@ def _place_video(stage: Path, video: MediaInput) -> None:
file_label="Video file",
dir_label="Video directory",
number_label="Video track numbers",
+ placed=placed,
)
-def _place_assets(stage: Path, assets: AssetsInput) -> None:
+def _place_assets(stage: Path, assets: AssetsInput, placed: Placed) -> None:
assets_dir = stage / "assets"
if isinstance(assets, Mapping):
for archive_path, source in assets.items():
_validate_archive_relative_path(archive_path, label="asset")
destination = assets_dir / archive_path
- _copy_file(Path(source), destination, label="Asset file")
+ _copy_file(Path(source), destination, label="Asset file", placed=placed)
return
- _copy_tree_into(Path(assets), assets_dir, label="Assets directory")
+ _copy_tree_into(Path(assets), assets_dir, label="Assets directory", placed=placed)
-def _place_source(stage: Path, source: SourceInput, mimetype: str) -> None:
- if _SOURCE_MIMETYPE_PATTERN.fullmatch(mimetype) is None:
- raise PackagingError("Invalid source MIME type; expected type/subtype")
+def _extension(part: str) -> str | None:
+ """The extension of the part ``part`` (as OPC matches ````), lowercased, or None."""
+ name = part.rsplit("/", 1)[-1]
+ return name.rsplit(".", 1)[1].lower() if "." in name else None
+
+
+def _source_part_name(source: SourceInput, name: str | None) -> str:
+ """``source.`` with the extensions of the original file name (up to two, e.g. ``source.tar.gz``), or
+ ``source`` without a reliable one."""
+ original = name if name is not None else (None if isinstance(source, bytes) else Path(source).name)
+ if original is None:
+ return "source"
+ stem, *extensions = original.lower().split(".")
+ if not stem or not extensions or extensions[-1] == "rels":
+ return "source"
+ kept: list[str] = []
+ for extension in reversed(extensions[-2:]):
+ if _SOURCE_EXTENSION_PATTERN.fullmatch(extension) is None:
+ break
+ kept.insert(0, extension)
+ return f"source.{'.'.join(kept)}" if kept else "source"
+
+
+def _check_source_name(name: str) -> None:
+ if (
+ not name
+ or name in {".", ".."}
+ or any(c in name for c in "/\\")
+ or any(ord(c) < 32 or ord(c) == 127 for c in name)
+ ):
+ raise PackagingError(f"Invalid source file name: {name!r}")
+
+
+def _place_source(stage: Path, source: SourceInput, name: str | None, placed: Placed) -> str:
+ """Place the original source, unless it is a file already placed (e.g. the whole-track media of a single
+ recording); return its part name."""
+ if not isinstance(source, bytes):
+ _reject_symlink(Path(source), label="Source document")
+ destination = placed.get(Path(source).resolve())
+ if destination is not None:
+ return destination.relative_to(stage).as_posix()
+ part = _source_part_name(source, name)
if isinstance(source, bytes):
- (stage / "source").write_bytes(source)
+ (stage / part).write_bytes(source)
else:
- _copy_file(Path(source), stage / "source", label="Source document")
+ _copy_file(Path(source), stage / part, label="Source document", placed=placed)
+ return part
-def _write_opc_metadata(stage: Path, *, source_mimetype: str | None = None) -> None:
- content_types = _CONTENT_TYPES_XML
- if source_mimetype is not None:
- override = f' \n'
- content_types = content_types.replace("", f"{override}")
- (stage / "[Content_Types].xml").write_text(content_types, encoding="utf-8")
+def _declare_content_type(
+ part: str, content_type: str | None, defaults: dict[str, str], overrides: dict[str, str]
+) -> None:
+ """Make sure ``part`` has a content type (``content_type`` if given): a ```` for its extension if
+ there is none yet, else an ```` if the existing one differs."""
+ extension = _extension(part)
+ current = overrides.get(part) or (defaults.get(extension) if extension else None)
+ if content_type is None:
+ if current is None:
+ raise PackagingError(f"No content type known for the source part {part!r}; pass its MIME type")
+ elif content_type != current:
+ if _SOURCE_MIMETYPE_PATTERN.fullmatch(content_type) is None:
+ raise PackagingError("Invalid source MIME type; expected type/subtype")
+ if extension is not None and extension not in defaults and part not in overrides:
+ defaults[extension] = content_type
+ else:
+ overrides[part] = content_type
+
+
+def _source_metadata_xml(name: str) -> str:
+ return (
+ '\n'
+ f"\n"
+ )
+
+
+def _write_opc_metadata(
+ stage: Path,
+ defaults: Mapping[str, str],
+ overrides: Mapping[str, str],
+ relationships: Sequence[tuple[str, str]],
+) -> None:
+ """Write ``_rels/.rels`` and ``[Content_Types].xml``; ``relationships`` are (type, target part) pairs, and of
+ ``defaults`` only the extensions of parts without an override are declared."""
+ lines = ['', f'']
+ for number, (relationship_type, target) in enumerate(relationships, start=1):
+ lines += [
+ f' ",
+ ]
+ lines.append("")
rels_dir = stage / "_rels"
rels_dir.mkdir(parents=True, exist_ok=True)
- (rels_dir / ".rels").write_text(_RELS_XML, encoding="utf-8")
+ (rels_dir / ".rels").write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+ used = {
+ _extension(part)
+ for part in (path.relative_to(stage).as_posix() for path in stage.rglob("*") if path.is_file())
+ if part not in overrides and not _should_exclude_zip_member(part)
+ }
+ lines = ['', f'']
+ lines += [
+ f" "
+ for ext, ct in defaults.items()
+ if ext in used
+ ]
+ lines += [f" " for p, ct in overrides.items()]
+ lines.append("")
+ (stage / "[Content_Types].xml").write_text("\n".join(lines) + "\n", encoding="utf-8")
def _should_exclude_zip_member(arcname: str) -> bool:
@@ -274,27 +380,41 @@ def _pack(
video: MediaInput | None = None,
source: SourceInput | None = None,
source_mimetype: str | None = None,
+ source_name: str | None = None,
validate: bool = False,
) -> Path:
- if (source is None) != (source_mimetype is None):
- raise PackagingError("source and source_mimetype must be provided together")
+ if source is None and (source_mimetype is not None or source_name is not None):
+ raise PackagingError("source_mimetype and source_name need source")
+ if source_name is not None:
+ _check_source_name(source_name)
document_path = Path(document)
output_path = Path(output) if output is not None else document_path.with_suffix(".dclx")
with tempfile.TemporaryDirectory() as temp_dir:
stage = Path(temp_dir)
+ placed: Placed = {}
_place_document(stage, document_path)
if pages is not None:
- _place_pages(stage, pages)
+ _place_pages(stage, pages, placed)
if assets is not None:
- _place_assets(stage, assets)
+ _place_assets(stage, assets, placed)
if audio is not None:
- _place_audio(stage, audio)
+ _place_audio(stage, audio, placed)
if video is not None:
- _place_video(stage, video)
- if source is not None and source_mimetype is not None:
- _place_source(stage, source, source_mimetype)
- _write_opc_metadata(stage, source_mimetype=source_mimetype)
+ _place_video(stage, video, placed)
+ defaults = dict(_DEFAULT_CONTENT_TYPES)
+ overrides = {"document.xml": _DOCUMENT_CONTENT_TYPE}
+ relationships = [(_DOCUMENT_RELATIONSHIP, "document.xml")]
+ if source is not None:
+ part = _place_source(stage, source, source_name, placed)
+ _declare_content_type(part, source_mimetype, defaults, overrides)
+ relationships.append((_SOURCE_RELATIONSHIP, part))
+ if source_name is not None:
+ descriptor = "source-metadata.xml"
+ (stage / descriptor).write_text(_source_metadata_xml(source_name), encoding="utf-8")
+ overrides[descriptor] = _SOURCE_METADATA_CONTENT_TYPE
+ relationships.append((_SOURCE_METADATA_RELATIONSHIP, descriptor))
+ _write_opc_metadata(stage, defaults, overrides, relationships)
if validate: # the archive, before it replaces any existing output
from doclang.validation import validate as validate_document
@@ -359,11 +479,14 @@ def _write_archive(
) -> None:
"""Write a copy of the archive ``source`` to ``output`` with ``document`` as its ``document.xml``.
- ``renames`` maps member names to new names, or to None to leave the member out. Every other member is
- copied as is, with its zip metadata, in the original order. ``output`` may be ``source``.
+ ``renames`` maps member names to new names, or to None to leave the member out; package relationships and
+ content type overrides follow. Every other member is copied as is, with its zip metadata, in the original
+ order. ``output`` may be ``source``.
"""
output_path = Path(output)
output_path.parent.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(source) as archive_in:
+ metadata = _renamed_opc_metadata(archive_in, renames)
with tempfile.NamedTemporaryFile(dir=output_path.parent, suffix=".dclx", delete=False) as temp:
temp_path = Path(temp.name)
try:
@@ -378,6 +501,8 @@ def _write_archive(
if member.filename == "document.xml":
info.date_time = time.localtime()[:6]
archive_out.writestr(info, document)
+ elif member.filename in metadata:
+ archive_out.writestr(info, metadata[member.filename])
elif member.is_dir():
archive_out.writestr(info, b"")
else: # streamed: media can be large
@@ -406,12 +531,6 @@ def _archive_rules_apply(version: tuple[int, int] | None, since: tuple[int, int]
return version is None or version >= since
-def _extension(part: str) -> str | None:
- """The extension of the part ``part`` (as OPC matches ````), lowercased, or None."""
- name = part.rsplit("/", 1)[-1]
- return name.rsplit(".", 1)[1].lower() if "." in name else None
-
-
def _parse_xml(data: bytes) -> etree._Element:
return etree.fromstring(data, etree.XMLParser(resolve_entities=False, no_network=True))
@@ -504,7 +623,8 @@ def _relationship_targets_of_parts(archive: zipfile.ZipFile, parts: list[str]) -
def _check_archive(path: Union[str, Path], version: tuple[int, int] | None) -> tuple[Problems, Problems]:
"""The errors and warnings on the rules of Annex B for a document of the spec ``version`` (None for the
latest) in the archive ``path``, apart from the validity of its ``document.xml``: the OPC metadata
- (``[Content_Types].xml``, ``_rels/.rels``), the positional parts (``pages/``, ``audio/``, ``video/``), and
+ (``[Content_Types].xml``, ``_rels/.rels``), the original source and its descriptor, the positional parts
+ (``pages/``, ``audio/``, ``video/``), and
the parts referenced from the markup or not accounted for. The archive must be readable (see
``_read_archive``).
"""
@@ -521,6 +641,8 @@ def warning(location: str, message: str) -> None:
parts = [name for name in archive.namelist() if not name.endswith("/")]
_check_content_types(archive, parts, error)
_check_package_relationships(archive, error)
+ if _archive_rules_apply(version, _SOURCE_VERSION):
+ _check_source(archive, parts, error)
try:
root = _parse_xml(archive.read("document.xml"))
except etree.XMLSyntaxError:
@@ -602,3 +724,88 @@ def _check_references(
or any(pattern.fullmatch(part) for pattern in (_RELATIONSHIP_PART_RE, _PAGE_RE, _TRACK_MEDIA_RE))
):
warning(part, "Not referenced by the markup or a relationship, nor a page image or whole-track media")
+
+
+def _check_source(archive: zipfile.ZipFile, parts: list[str], error: Callable[[str, str], None]) -> None:
+ """The rules on the original source and its descriptor (their content types are checked with all parts')."""
+ try:
+ relationships = _package_relationships(archive) or []
+ except etree.XMLSyntaxError:
+ return # reported with the package relationships
+ by_type: dict[str, list[etree._Element]] = {}
+ for relationship in relationships:
+ by_type.setdefault(relationship.get("Type", ""), []).append(relationship)
+ for relationship_type, label in (
+ (_SOURCE_RELATIONSHIP, "source"),
+ (_SOURCE_METADATA_RELATIONSHIP, "source descriptor"),
+ ):
+ found = by_type.get(relationship_type, [])
+ if len(found) > 1:
+ error("_rels/.rels", f"More than one {relationship_type} relationship")
+ for relationship in found:
+ if relationship.get("TargetMode") == "External":
+ error("_rels/.rels", f"The {label} relationship must target a part of the archive")
+ continue
+ part = _relationship_target_part(relationship.get("Target", ""))
+ if part not in parts:
+ error("_rels/.rels", f"The {label} part {part!r} is missing")
+ continue
+ if relationship_type == _SOURCE_METADATA_RELATIONSHIP:
+ try:
+ root = _parse_xml(archive.read(part))
+ except etree.XMLSyntaxError as exc:
+ error(part, f"Not well-formed XML: {exc}")
+ continue
+ if root.tag != f"{{{_SOURCE_METADATA_NAMESPACE}}}source":
+ error(part, f"The root element must be source in the namespace {_SOURCE_METADATA_NAMESPACE}")
+ if _SOURCE_METADATA_RELATIONSHIP in by_type and _SOURCE_RELATIONSHIP not in by_type:
+ error("_rels/.rels", "A source-metadata relationship without a source relationship")
+
+
+def _relationship_targets(path: Union[str, Path]) -> set[str]:
+ """The parts targeted by relationships, apart from the main document (e.g. the original source)."""
+ with zipfile.ZipFile(path) as archive:
+ return _relationship_targets_of_parts(archive, archive.namelist()) - {"document.xml"}
+
+
+def _renamed_opc_metadata(archive: zipfile.ZipFile, renames: Mapping[str, str | None]) -> dict[str, bytes]:
+ """``_rels/.rels`` and ``[Content_Types].xml`` updated for the parts in ``renames`` (relationship targets and
+ ```` part names follow a renamed part; an ```` of a removed part is dropped). Only the
+ ones that change are returned; ones that are not well-formed are left alone."""
+ updated: dict[str, bytes] = {}
+ names = set(archive.namelist())
+ if "_rels/.rels" in names:
+ try:
+ root = _parse_xml(archive.read("_rels/.rels"))
+ except etree.XMLSyntaxError:
+ root = None
+ changed = False
+ for relationship in [] if root is None else root.iterfind(f"{{{_RELATIONSHIPS_NAMESPACE}}}Relationship"):
+ target = relationship.get("Target", "")
+ if relationship.get("TargetMode") == "External":
+ continue
+ new = renames.get(_relationship_target_part(target))
+ if new is not None:
+ relationship.set("Target", f"/{new}" if target.startswith("/") else new)
+ changed = True
+ if changed:
+ updated["_rels/.rels"] = etree.tostring(root, xml_declaration=True, encoding="UTF-8")
+ if "[Content_Types].xml" in names:
+ try:
+ root = _parse_xml(archive.read("[Content_Types].xml"))
+ except etree.XMLSyntaxError:
+ root = None
+ lowered = {old.lower(): new for old, new in renames.items()}
+ changed = False
+ for override in [] if root is None else list(root.iterfind(f"{{{_CONTENT_TYPES_NAMESPACE}}}Override")):
+ part = override.get("PartName", "").lstrip("/").lower()
+ if part not in lowered:
+ continue
+ if lowered[part] is None:
+ root.remove(override)
+ else:
+ override.set("PartName", f"/{lowered[part]}")
+ changed = True
+ if changed:
+ updated["[Content_Types].xml"] = etree.tostring(root, xml_declaration=True, encoding="UTF-8")
+ return updated
diff --git a/doclang/cli.py b/doclang/cli.py
index a40dd7f..668fced 100644
--- a/doclang/cli.py
+++ b/doclang/cli.py
@@ -93,10 +93,10 @@ def validate(
For a .dclx archive, its document.xml is validated, and (unless --xsd-only
or --schematron-only) its other parts are checked against the archive rules
- (Annex B, from version 0.8): the OPC metadata, page images and whole-track
- media beyond the pages and