Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]]`
Expand Down
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/source/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
13 changes: 1 addition & 12 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 <ghostofbasho@gmail.com>"]
license = "MIT"
Expand Down Expand Up @@ -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"

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
27 changes: 23 additions & 4 deletions src/vcon/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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 ``"<algorithm>-<base64url>"``
with no base64 padding (draft-ietf-vcon-vcon-core-02), e.g.
``"sha512-GLy6IPa..."``.
Expand All @@ -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
Expand Down Expand Up @@ -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
12 changes: 8 additions & 4 deletions src/vcon/extensions/lawful_basis/attachment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
44 changes: 34 additions & 10 deletions src/vcon/vcon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand All @@ -1047,17 +1048,19 @@ 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
segments: List of segment dictionaries
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:
Expand All @@ -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,
)
Expand Down Expand Up @@ -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.

Expand All @@ -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
Expand Down
105 changes: 105 additions & 0 deletions tests/test_fixes_1_0_3.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading
Loading