diff --git a/API_REFERENCE.md b/API_REFERENCE.md index cacaae0..9748564 100644 --- a/API_REFERENCE.md +++ b/API_REFERENCE.md @@ -203,11 +203,11 @@ Add an attachment to the vCon. Core-05 needs `party` plus `dialog` or `session`: attachment = vcon.add_attachment("transcript", "Full conversation...", "none", party=0, dialog=0) ``` -###### `add_image(image_path: str, purpose: str = "image") -> Attachment` -Add an image attachment from file. +###### `add_image(image_path: str, purpose: str = "image", party: Optional[int] = None, dialog: Optional[int] = None, session: Optional[Union[int, List[int]]] = None) -> Attachment` +Add an image or PDF attachment from file (JPEG, TIFF or PDF). The scope rules are the same as `add_attachment()`. ```python -attachment = vcon.add_image("screenshot.png", "screenshot") +attachment = vcon.add_image("scan.jpg", "identification", party=0, session=0) ``` ###### `find_attachment_by_purpose(purpose: str) -> Optional[Dict[str, Any]]` diff --git a/CHANGELOG.md b/CHANGELOG.md index 71e23fa..bf7e263 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## [1.0.3] - 2026-11-18 + +### Fixed +- `add_wtf_transcription_analysis()` writes the analysis entry defined by + draft-howe-vcon-wtf-extension: `type: "wtf_transcription"` (was + `"transcription"`) with the WTF document as the JSON body (was a + `json.dumps` string). It takes `session_index` for a Session scope. + `Vcon.decoded_body()` still reads entries written by older releases. +- `add_image()` scopes the attachment like `add_attachment()`: it takes + `party`, `dialog` and `session`, uses the only Session when the vCon has + exactly one, and raises `ValueError` otherwise. It used to write an + attachment with neither `dialog` nor `session`, which failed `is_valid()`. +- `Dialog.calculate_content_hash()` hashes the decoded bytes of a `base64url` + body, so it matches the hash `add_image_data()` stores and + `verify_content_hash()` succeeds on image dialogs. `verify_content_hash()` + also accepts a hash of the encoded text, as 1.0.0 and earlier computed it. +- Lawful basis `ContentHash` accepts strings (`"sha-256"`, `"jcs"`) as well as + enums, and rejects unknown values in the constructor instead of crashing in + `to_dict()`. +- Importing `vcon` no longer configures the root logger. `vcon.dialog` used + the third-party `logger` package, which set the root logger to INFO on + stdout; it now uses `logging.getLogger(__name__)` like the other modules, + and `logger` is no longer a dependency. Configure logging in your + application to see the library's messages. + ## [1.0.2] - 2026-11-15 Documentation release. No change to library behavior. (1.0.1 was never diff --git a/docs/source/installation.rst b/docs/source/installation.rst index f695bad..f73c7ab 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -47,4 +47,4 @@ Dependencies The runtime dependencies are listed in ``pyproject.toml`` and installed automatically: authlib, uuid6, requests, pydash, python-dateutil, mutagen, -ffmpeg and logger. Pillow and pypdf come with the ``image`` extra. +and ffmpeg. Pillow and pypdf come with the ``image`` extra. diff --git a/poetry.lock b/poetry.lock index 308c7af..f27974c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -577,17 +577,6 @@ files = [ [package.dependencies] referencing = ">=0.31.0" -[[package]] -name = "logger" -version = "1.4" -description = "Python logging helper" -optional = false -python-versions = "*" -groups = ["main"] -files = [ - {file = "logger-1.4.tar.gz", hash = "sha256:4ecac57133c6376fa215f0fe6b4dc4d60e4d1ad8be005cab4e8a702df682f8b3"}, -] - [[package]] name = "markupsafe" version = "2.1.5" @@ -1386,4 +1375,4 @@ image = ["pillow", "pypdf"] [metadata] lock-version = "2.1" python-versions = "^3.12" -content-hash = "2107dee660a3b77ab7fdd3fefe5c0fce6e3139ce25e41821c0f22d467e48dd8e" +content-hash = "55cca0e4301450d0fd21e42f42856fb7a728473d731d7459deb4e8b5825c37ee" diff --git a/pyproject.toml b/pyproject.toml index 4910ca3..ecd9e05 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "vcon" -version = "1.0.2" +version = "1.0.3" description = "The vCon library - vCon 0.5.0 (draft-ietf-vcon-vcon-core-05) specification implementation" authors = ["Thomas McCarthy-Howe "] license = "MIT" @@ -35,7 +35,6 @@ pydash = "^8.0.3" python-dateutil = "^2.9.0.post0" mutagen = "^1.47.0" ffmpeg = "^1.4" -logger = "^1.4" pypdf = "^6.10.2" pillow = "^12.2.0" diff --git a/setup.py b/setup.py index bfc2ab3..ab95a28 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name="vcon", - version="1.0.2", + version="1.0.3", author="Thomas McCarthy-Howe", author_email="ghostofbasho@gmail.com", description="The vCon library - vCon 0.5.0 (draft-ietf-vcon-vcon-core-05) specification implementation", diff --git a/src/vcon/dialog.py b/src/vcon/dialog.py index 00b91ca..344eddf 100644 --- a/src/vcon/dialog.py +++ b/src/vcon/dialog.py @@ -2,13 +2,15 @@ import hashlib import base64 import os -import logger +import logging import tempfile import warnings from datetime import datetime from typing import Optional, List, Dict, Union, Any, Tuple from dateutil import parser +logger = logging.getLogger(__name__) + MIME_TYPES = [ "text/plain", "audio/x-wav", @@ -1423,6 +1425,10 @@ def calculate_content_hash( """ Calculate the content hash for the dialog body. + The hash covers the content itself: for a ``base64url`` body that is + the decoded bytes, so the value matches a hash of the original file + (what ``add_image_data()`` stores). Other bodies are hashed as UTF-8. + The returned value is spec-formatted as ``"-"`` with no base64 padding (draft-ietf-vcon-vcon-core-02), e.g. ``"sha512-GLy6IPa..."``. @@ -1438,8 +1444,17 @@ def calculate_content_hash( if not hasattr(self, "body") or not self.body: raise ValueError("No body content available to hash") - body_bytes = self.body.encode() if isinstance(self.body, str) else self.body - return compute_content_hash(body_bytes, algorithm) + return compute_content_hash(self._content_bytes(), algorithm) + + def _content_bytes(self) -> bytes: + """The dialog content as bytes: decoded for base64url, else the body.""" + body = self.body + if getattr(self, "encoding", None) == "base64url" and isinstance(body, str): + try: + return b64url_decode(body) + except (ValueError, TypeError): + pass + return body.encode() if isinstance(body, str) else body def verify_content_hash( self, expected_hash: str, algorithm: Optional[str] = None @@ -1477,6 +1492,10 @@ def verify_content_hash( ).decode() return legacy == expected_hash - return self.calculate_content_hash(resolved) == expected_hash + if self.calculate_content_hash(resolved) == expected_hash: + return True + # 1.0.0 and earlier hashed a base64url body as its encoded text. + body_bytes = self.body.encode() if isinstance(self.body, str) else self.body + return compute_content_hash(body_bytes, resolved) == expected_hash except ValueError: return False diff --git a/src/vcon/extensions/lawful_basis/attachment.py b/src/vcon/extensions/lawful_basis/attachment.py index ac03b8f..250e70e 100644 --- a/src/vcon/extensions/lawful_basis/attachment.py +++ b/src/vcon/extensions/lawful_basis/attachment.py @@ -117,12 +117,16 @@ class ContentHash: def __init__( self, - algorithm: HashAlgorithm, - canonicalization: CanonicalizationMethod, + algorithm: Union[HashAlgorithm, str], + canonicalization: Union[CanonicalizationMethod, str], value: str ): - self.algorithm = algorithm - self.canonicalization = canonicalization + # Accept the enum or its string value ("sha-256", "jcs"); a value + # outside the enum raises ValueError here rather than later in to_dict(). + self.algorithm = HashAlgorithm(algorithm.lower() if isinstance(algorithm, str) else algorithm) + self.canonicalization = CanonicalizationMethod( + canonicalization.lower() if isinstance(canonicalization, str) else canonicalization + ) self.value = value def validate(self, content: Dict[str, Any]) -> bool: diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index 2b7d27a..615a033 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -1037,6 +1037,7 @@ def add_wtf_transcription_analysis( segments: List[Dict[str, Any]], metadata: Dict[str, Any], dialog_index: Optional[int] = None, + session_index: Optional[Union[int, List[int]]] = None, **kwargs ) -> None: """ @@ -1047,10 +1048,11 @@ def add_wtf_transcription_analysis( pipeline treats transcripts as derived analysis output and prefers analysis[] placement. - Emits a spec-shaped analysis entry: ``type="transcription"``, - ``vendor`` and ``product`` taken from ``metadata["provider"]`` / - ``metadata["model"]``, ``schema`` set to the WTF draft URL, - ``encoding="json"``, and ``body`` as a JSON-serialized WTF document. + Emits the analysis entry defined by draft-howe-vcon-wtf-extension + (section 5.3): ``type="wtf_transcription"``, ``vendor`` and ``product`` + taken from ``metadata["provider"]`` / ``metadata["model"]``, ``schema`` + set to the WTF draft URL, ``encoding="json"``, and ``body`` as the WTF + document itself (a JSON value, not a serialized string). Args: transcript: Transcript information dictionary @@ -1058,6 +1060,7 @@ def add_wtf_transcription_analysis( metadata: Metadata dictionary; ``provider`` and ``model`` keys map to ``vendor`` and ``product`` on the analysis entry dialog_index: Index of the dialog this transcription applies to + session_index: Session index or indices this transcription applies to **kwargs: Additional WTF parameters (words, speakers, quality, etc.) """ if not EXTENSIONS_AVAILABLE: @@ -1077,11 +1080,12 @@ def add_wtf_transcription_analysis( dialog_ref = [dialog_index] if dialog_index is not None else None self.add_analysis( - type="transcription", + type="wtf_transcription", dialog=dialog_ref, + sessions=session_index, vendor=metadata.get("provider", "unknown"), product=metadata.get("model"), - body=json.dumps(wtf_body), + body=wtf_body, encoding="json", schema=self.WTF_SCHEMA_URL, ) @@ -1346,7 +1350,14 @@ def add_attachment( logger.info(f"Added new attachment of purpose {purpose}") return attachment - def add_image(self, image_path: str, purpose: str = "image") -> Attachment: + def add_image( + self, + image_path: str, + purpose: str = "image", + party: Optional[int] = None, + dialog: Optional[int] = None, + session: Optional[Union[int, List[int]]] = None, + ) -> Attachment: """ Add an image attachment to the vCon. @@ -1356,25 +1367,38 @@ def add_image(self, image_path: str, purpose: str = "image") -> Attachment: Args: image_path: Path to the image file purpose: The purpose of the attachment (default: "image") + party: Party index (default 0) + dialog: Dialog index + session: Session index or list of indices. With neither + ``dialog`` nor ``session``, the only Session is used when the + vCon has exactly one, as in ``add_attachment()``. Returns: The created Attachment object Raises: FileNotFoundError: If the image file cannot be found - ValueError: If the image format is not supported + ValueError: If the image format is not supported, or no + ``dialog``/``session`` is given and the vCon does not have + exactly one Session Example: >>> vcon = Vcon.build_new() + >>> vcon.add_session() >>> attachment = vcon.add_image("document.pdf", "identification") >>> print(attachment.mediatype) # Prints "application/pdf" """ + if dialog is None and session is None: + session = self._resolve_attachment_scope()["session"] attachment = Attachment.from_image(image_path, purpose) # The WG JSON schema requires start on every attachment; default to - # this vCon's created_at (party/dialog already default to 0 in - # Attachment.__init__). + # this vCon's created_at. if attachment.start is None: attachment.start = self.vcon_dict.get("created_at") + if party is not None: + attachment.party = party + attachment.dialog = dialog + attachment.session = session self.vcon_dict["attachments"].append(attachment.to_dict()) logger.info(f"Added new image attachment of purpose {purpose}") return attachment diff --git a/tests/test_fixes_1_0_3.py b/tests/test_fixes_1_0_3.py new file mode 100644 index 0000000..7889237 --- /dev/null +++ b/tests/test_fixes_1_0_3.py @@ -0,0 +1,105 @@ +"""Regression tests for the 1.0.3 fixes.""" + +import logging +import subprocess +import sys +from datetime import datetime, timezone + +import pytest + +from vcon import Vcon, Session, compute_content_hash +from vcon.dialog import Dialog, b64url_encode +from vcon.party import Party +from vcon.extensions.lawful_basis.attachment import ( + CanonicalizationMethod, + ContentHash, + HashAlgorithm, +) + + +def _png(tmp_path): + PIL = pytest.importorskip("PIL.Image") + path = tmp_path / "pixel.jpg" + PIL.new("RGB", (1, 1)).save(path, "JPEG") + return path + + +def _vcon_with_sessions(n): + v = Vcon.build_new() + v.add_party(Party(tel="+15551230001")) + for _ in range(n): + v.add_session(Session(start=datetime.now(timezone.utc), parties=[0])) + return v + + +class TestAddImageScope: + def test_uses_the_only_session(self, tmp_path): + v = _vcon_with_sessions(1) + v.add_image(str(_png(tmp_path))) + att = v.attachments[0] + assert att["session"] == 0 + assert att["party"] == 0 + assert v.is_valid() == (True, []) + + def test_explicit_scope(self, tmp_path): + v = _vcon_with_sessions(2) + v.add_image(str(_png(tmp_path)), party=0, session=1) + assert v.attachments[0]["session"] == 1 + assert v.is_valid() == (True, []) + + def test_ambiguous_scope_raises(self, tmp_path): + v = _vcon_with_sessions(2) + with pytest.raises(ValueError): + v.add_image(str(_png(tmp_path))) + assert v.attachments == [] + + +class TestImageContentHash: + def test_add_image_data_hash_verifies(self, tmp_path): + path = _png(tmp_path) + d = Dialog(type="text", start=datetime.now(timezone.utc), parties=[0]) + d.add_image_data(str(path)) + assert d.content_hash == compute_content_hash(path.read_bytes()) + assert d.verify_content_hash(d.content_hash) + assert d.calculate_content_hash() == d.content_hash + + def test_legacy_hash_of_encoded_body_still_verifies(self): + data = b"\x00\x01binary" + body = b64url_encode(data) + d = Dialog(type="recording", start=datetime.now(timezone.utc), parties=[0], + body=body, encoding="base64url", mediatype="audio/x-wav") + assert d.verify_content_hash(compute_content_hash(body.encode())) + assert d.verify_content_hash(compute_content_hash(data)) + assert not d.verify_content_hash(compute_content_hash(b"other")) + + def test_text_body_unchanged(self): + d = Dialog(type="text", start=datetime.now(timezone.utc), parties=[0], + body="hello", encoding="none", mediatype="text/plain") + assert d.calculate_content_hash() == compute_content_hash(b"hello") + + +class TestContentHashStrings: + def test_accepts_strings(self): + h = ContentHash(algorithm="sha-256", canonicalization="JCS", value="x") + assert h.algorithm is HashAlgorithm.SHA_256 + assert h.canonicalization is CanonicalizationMethod.JCS + assert h.to_dict()["canonicalization"] == "jcs" + + def test_accepts_enums(self): + h = ContentHash(HashAlgorithm.BLAKE2B_256, CanonicalizationMethod.JCS, "x") + assert h.to_dict()["algorithm"] == "blake2b-256" + + def test_rejects_unknown_values(self): + with pytest.raises(ValueError): + ContentHash(algorithm="md5", canonicalization="jcs", value="x") + + +def test_import_does_not_configure_root_logging(): + code = ( + "import logging, vcon\n" + "root = logging.getLogger()\n" + "print(root.level, len(root.handlers))\n" + ) + out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], + capture_output=True, text=True, check=True) + assert out.stdout.split() == [str(logging.WARNING), "0"] diff --git a/tests/test_wtf_extension.py b/tests/test_wtf_extension.py index 592d06e..64da630 100644 --- a/tests/test_wtf_extension.py +++ b/tests/test_wtf_extension.py @@ -629,15 +629,35 @@ def test_add_wtf_transcription_analysis_basic(self): assert vcon.vcon_dict["attachments"] == [] entry = vcon.vcon_dict["analysis"][0] - assert entry["type"] == "transcription" + assert entry["type"] == "wtf_transcription" assert entry["vendor"] == "whisper" assert entry["product"] == "whisper-1" assert entry["encoding"] == "json" assert entry["schema"] == Vcon.WTF_SCHEMA_URL assert entry["dialog"] == [0] - body = json.loads(entry["body"]) - assert body["transcript"]["text"] == "Hello world" + # The body is the WTF document itself, not a JSON string + assert isinstance(entry["body"], dict) + assert entry["body"]["transcript"]["text"] == "Hello world" + assert Vcon.decoded_body(entry)["transcript"]["text"] == "Hello world" + + def test_add_wtf_transcription_analysis_session_scope_is_valid(self): + from datetime import datetime, timezone + from vcon import Vcon, Session + from vcon.dialog import Dialog + from vcon.party import Party + + vcon = Vcon.build_new() + vcon.add_party(Party(tel="+15551230001")) + s = vcon.add_session(Session(start=datetime.now(timezone.utc), parties=[0])) + vcon.add_dialog(Dialog(type="recording", start=datetime.now(timezone.utc), parties=[0], + url="https://example.com/a.wav", mediatype="audio/x-wav", + content_hash="sha512-AAAA"), session=s) + vcon.add_wtf_transcription_analysis(**self._payload(), session_index=s) + entry = vcon.vcon_dict["analysis"][0] + assert entry["sessions"] in (0, [0]) + assert "dialog" not in entry + assert vcon.is_valid() == (True, []) def test_add_wtf_transcription_analysis_registers_extension(self): from vcon import Vcon