From a4e068d2a5ddbd39c690a985a6e8396d46e96a5d Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Wed, 18 Nov 2026 19:55:26 -0500 Subject: [PATCH] 1.0.4: content_hash and lawful basis validation, keep created_at, working video helpers, joserfc, deprecate the WTF attachment helper --- API_REFERENCE.md | 110 ++++++---- CHANGELOG.md | 58 ++++++ GUIDE.md | 58 ++++-- LLM_GUIDE.md | 86 ++++---- MIGRATION_GUIDE.md | 42 ++++ README.md | 30 ++- docs/source/installation.rst | 14 +- docs/source/usage.rst | 15 +- poetry.lock | 50 +++-- pyproject.toml | 9 +- setup.py | 2 +- src/vcon/dialog.py | 69 +++++-- .../extensions/lawful_basis/validation.py | 10 +- src/vcon/validation.py | 66 ++++++ src/vcon/vcon.py | 195 +++++++++++++----- tests/test_core05_changes.py | 28 ++- tests/test_core05_examples.py | 2 +- tests/test_dialog.py | 10 +- tests/test_fixes_1_0_4.py | 181 ++++++++++++++++ ...est_fixes_1_0_3.py => test_fixes_1_0_x.py} | 27 +++ tests/test_migration_0_4_0.py | 4 +- tests/test_vcon.py | 7 +- tests/test_wtf_extension.py | 2 +- 23 files changed, 843 insertions(+), 232 deletions(-) create mode 100644 tests/test_fixes_1_0_4.py rename tests/{test_fixes_1_0_3.py => test_fixes_1_0_x.py} (72%) diff --git a/API_REFERENCE.md b/API_REFERENCE.md index 9748564..8b803fc 100644 --- a/API_REFERENCE.md +++ b/API_REFERENCE.md @@ -17,6 +17,18 @@ Complete API documentation for the vCon library - a Python implementation of the | `extensions` SHOULD list extensions | `is_valid()` errors when an extension in use is not listed | | (new) | `Vcon.add_session`, `Vcon.sessions`, `Vcon.events`, `Dialog.placeholder()`, `migrate_0_4_0_to_0_5_0()` | +## Changes in 1.0.4 + +| Before | 1.0.4 | +| --- | --- | +| `add_tag()` wrote `party: 0` even with no parties | `add_tag(name, value, party=None)`; `party` defaults to 0. On a vCon with no parties it still writes party 0 but emits a `DeprecationWarning` (it will raise in 1.1); a `party` index out of range raises `ValueError` | +| `add_wtf_transcription_attachment()` | deprecated (`DeprecationWarning`); use `add_wtf_transcription_analysis()`, which writes the analysis entry the WTF draft requires | +| `is_valid()` core structure only | also reports a malformed `content_hash` and errors in the body of every `lawful_basis` attachment; `get_validation_warnings()` adds a `url` without `content_hash` (an error from 1.1), JSON-string bodies under `encoding: "json"`, and lawful-basis warnings | +| loading rewrote `created_at` (and crashed on an unparseable one) | `created_at` is kept exactly as written; `is_valid()` reports an unparseable value | +| `Dialog.add_inline_data(body: str, ...)` | also accepts `bytes` (encoded to base64url); `content_hash` is over the decoded content | +| `generate_thumbnail()` defined twice (the image one won) | dispatches to `generate_image_thumbnail()` or `generate_video_thumbnail()`; video helpers need `pip install "vcon[video]"` and the ffmpeg binary | +| `authlib` for JWS | `joserfc`; `sign()`/`verify()` accept RSA, EC and Ed25519 keys | + ## Table of Contents - [Overview](#overview) @@ -48,6 +60,12 @@ pip install vcon Image/PDF processing support is included by default with the standard installation. +The video helpers (`extract_video_metadata`, `generate_video_thumbnail`, `transcode_video`) need the `video` extra (ffmpeg-python) and the ffmpeg binary on `PATH`: + +```bash +pip install "vcon[video]" +``` + ## Core Classes ### Vcon Class @@ -248,11 +266,11 @@ body is the JSON value itself, not a serialized string). `get_tag()` and -02 conventions, or by this library prior to 0.10.0 -- decoding it automatically; `add_tag()` normalizes it back to a list in place. -###### `add_tag(tag_name: str, tag_value: str) -> None` -Add a tag to the vCon. +###### `add_tag(tag_name: str, tag_value: str, party: Optional[int] = None) -> None` +Add a tag to the vCon. Core-05 requires the tags attachment's `party` to be a valid party index (the party that adds the tags): `party` defaults to 0. When a new tags attachment is needed and the vCon has no parties, it still writes party 0 (so the vCon fails `is_valid()`) and emits a `DeprecationWarning`; this will raise `ValueError` in vcon 1.1, so add a party before the first tag. A `party` index that is out of range raises `ValueError`. ```python -vcon.add_tag("customer_id", "12345") +vcon.add_tag("customer_id", "12345") # a new tags attachment names party 0 ``` ###### `get_tag(tag_name: str) -> Optional[str]` @@ -319,18 +337,24 @@ vcon.add_lawful_basis_attachment( ) ``` -###### `add_wtf_transcription_attachment(transcript: Dict[str, Any], segments: List[Dict[str, Any]], metadata: Dict[str, Any], party_index: Optional[int] = None, dialog_index: Optional[int] = None, session_index: Optional[Union[int, List[int]]] = None, **kwargs) -> None` -Add a WTF transcription attachment to the vCon. Scoped by `dialog_index` and/or `session_index`; with neither, the only Session is used when the vCon has exactly one, otherwise `ValueError` is raised. +###### `add_wtf_transcription_analysis(transcript: Dict[str, Any], segments: List[Dict[str, Any]], metadata: Dict[str, Any], dialog_index: Optional[int] = None, session_index: Optional[Union[int, List[int]]] = None, **kwargs) -> None` +Add a WTF transcription as an analysis entry, the placement draft-howe-vcon-wtf-extension requires: `type` `"wtf_transcription"`, `vendor`/`product` from `metadata["provider"]`/`metadata["model"]`, `encoding` `"json"` and the WTF document as the body. `**kwargs` takes the other WTF fields (`words`, `speakers`, `quality`, ...). ```python -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript={"text": "Hello world", "language": "en", "duration": 2.0, "confidence": 0.95}, segments=[{"id": 0, "start": 0.0, "end": 2.0, "text": "Hello world", "confidence": 0.95}], - metadata={"created_at": "2025-01-01T00:00:00Z", "provider": "whisper", "model": "whisper-1"}, + metadata={"created_at": "2025-01-01T00:00:00Z", "processed_at": "2025-01-01T00:00:05Z", + "provider": "whisper", "model": "whisper-1"}, dialog_index=0 ) +entry = vcon.find_analysis_by_type("wtf_transcription") +wtf_body = Vcon.decoded_body(entry) ``` +###### `add_wtf_transcription_attachment(transcript, segments, metadata, party_index=None, dialog_index=None, session_index=None, **kwargs) -> None` +Deprecated: emits a `DeprecationWarning`. It writes the transcription to `attachments`, which the WTF draft does not allow; use `add_wtf_transcription_analysis()`. + ###### `find_lawful_basis_attachments(party_index: Optional[int] = None) -> List[Dict[str, Any]]` Find lawful basis attachments in the vCon. @@ -339,10 +363,10 @@ attachments = vcon.find_lawful_basis_attachments(party_index=0) ``` ###### `find_wtf_attachments(party_index: Optional[int] = None) -> List[Dict[str, Any]]` -Find WTF transcription attachments in the vCon. +Find WTF transcription attachments written by the deprecated `add_wtf_transcription_attachment()`. Transcriptions added with `add_wtf_transcription_analysis()` are analysis entries: ```python -attachments = vcon.find_wtf_attachments(party_index=0) +transcriptions = [a for a in vcon.analysis if a["type"] == "wtf_transcription"] ``` ###### `check_lawful_basis_permission(purpose: str, party_index: Optional[int] = None) -> bool` @@ -369,14 +393,14 @@ results = vcon.process_extensions() ##### Security ###### `sign(private_key: Union[rsa.RSAPrivateKey, bytes], alg: str = "RS256") -> None` -Sign the vCon with a private key. +Sign the vCon with a private key. Signing uses joserfc; the key may be an RSA, EC or Ed25519 `cryptography` key object or PEM bytes, matching `alg` (RS\*/PS\* for RSA, ES\* for EC, EdDSA for Ed25519). ```python vcon.sign(private_key) ``` ###### `verify(public_key: Union[rsa.RSAPublicKey, bytes]) -> bool` -Verify the vCon signature. +Verify the vCon signature. Accepts the public key as a `cryptography` key object or PEM, of the type the signature's `alg` needs. ```python is_valid = vcon.verify(public_key) @@ -385,12 +409,19 @@ is_valid = vcon.verify(public_key) ##### Validation ###### `is_valid() -> Tuple[bool, List[str]]` -Validate the vCon object. +Validate the vCon object against the core-05 MUST rules. Besides structure, this reports a malformed `content_hash` (it must be `-`, 86 characters for sha512 and 43 for sha256); an unparseable `created_at`; and errors in the body of every `lawful_basis` attachment (missing `lawful_basis`, `expiration`, `purpose_grants` and so on). ```python is_valid, errors = vcon.is_valid() ``` +###### `get_validation_warnings() -> List[str]` +Findings that do not make the vCon invalid, for example a `url` without a `content_hash` on a dialog, attachment or analysis entry (a MUST in core-05, reported as a warning in 1.0.x and an `is_valid()` error from vcon 1.1), an `encoding: "json"` body that is a serialized JSON string, and lawful-basis warnings (an unknown proof type, hash algorithm or canonicalization method is a warning, since the draft's lists are open). + +```python +warnings = vcon.get_validation_warnings() +``` + ##### Serialization ###### `to_json() -> str` @@ -446,7 +477,7 @@ Get the vCon syntax version (`build_new()` writes `"0.5.0"`; input declaring `"0 Get the vCon subject. ##### `created_at` -Get the creation timestamp. +Get the creation timestamp, exactly as written in the loaded vCon (loading does not reformat it). ##### `updated_at` Get the update timestamp. @@ -618,8 +649,8 @@ Convert Dialog to dictionary. ##### `add_external_data(url: str, filename: str, mediatype: str) -> None` Add external data to dialog. -##### `add_inline_data(body: str, filename: str, mediatype: str) -> None` -Add inline data to dialog. +##### `add_inline_data(body: Union[str, bytes], filename: str, mediatype: str) -> None` +Add inline data to dialog with `encoding` `"base64url"`. Raw `bytes` are encoded for you; a `str` must already be base64url. The `content_hash` is computed over the decoded content. ##### `is_external_data() -> bool` Check if dialog has external data. @@ -658,10 +689,16 @@ Check if dialog has PDF content. Add video data to dialog. ##### `extract_video_metadata(video_path: Optional[str] = None) -> dict` -Extract video metadata using FFmpeg. +Extract video metadata using FFmpeg. Needs `pip install "vcon[video]"` (ffmpeg-python) and the ffmpeg binary. -##### `generate_thumbnail(timestamp: float = 0.0, width: int = 320, height: int = 240, quality: int = 90) -> bytes` -Generate video thumbnail. +##### `generate_thumbnail(*args, **kwargs)` +Generate a thumbnail for an image or video Dialog: calls `generate_video_thumbnail()` for video content and `generate_image_thumbnail()` otherwise, passing the arguments through. + +##### `generate_video_thumbnail(timestamp: float = 0.0, width: int = 320, height: int = 240, quality: int = 90) -> bytes` +Generate a JPEG thumbnail from the video at `timestamp`. Needs the `video` extra and the ffmpeg binary. + +##### `get_video_format_from_mediatype(mediatype: Optional[str] = None) -> str` +Map a video media type to a format name (`mp4`, `webm`, ...; `unknown` otherwise). Defaults to this Dialog's `mediatype`. ##### `add_streaming_video_reference(reference_id: str, mediatype: str, metadata: Optional[dict] = None) -> None` Add streaming video reference. @@ -670,7 +707,7 @@ Add streaming video reference. Add video with optimal storage method. ##### `transcode_video(target_format: str, codec: Optional[str] = None, bit_rate: Optional[int] = None, width: Optional[int] = None, height: Optional[int] = None) -> None` -Transcode video to different format. +Transcode video to different format. Needs the `video` extra and the ffmpeg binary. ##### `add_image_data(image_path: str, mediatype: Optional[str] = None) -> None` Add image data from file. @@ -678,8 +715,8 @@ Add image data from file. ##### `extract_image_metadata(image_data: bytes, mediatype: str) -> None` Extract image metadata. -##### `generate_thumbnail(max_size: Tuple[int, int] = (200, 200)) -> Optional[str]` -Generate image thumbnail. +##### `generate_image_thumbnail(max_size: Tuple[int, int] = (200, 200)) -> Optional[str]` +Generate an image thumbnail, returned as a base64url string (None if it cannot be made). ##### `is_external_data_changed() -> bool` Check if external data has changed. @@ -931,7 +968,7 @@ proof = ProofMechanism( #### Validation and Processing ##### `LawfulBasisValidator` -Validates lawful basis attachments and extension usage. +Validates lawful basis attachments and extension usage. `Vcon.is_valid()` runs it on the body of every `lawful_basis` attachment. An unknown proof type, hash algorithm or canonicalization method is a warning, not an error, because the draft's lists are open. ```python from vcon.extensions.lawful_basis import LawfulBasisValidator @@ -978,7 +1015,7 @@ The WTF (World Transcription Format) extension provides standardized representat #### Core Classes ##### `WTFAttachment` -Main class representing a WTF transcription attachment. +Main class representing a WTF transcription document (the body of a `wtf_transcription` analysis entry; `WTFAttachment.from_dict(entry["body"])` reads one back). ```python from vcon.extensions.wtf import WTFAttachment, Transcript, Segment, Word, Speaker, Quality, Metadata @@ -1432,11 +1469,11 @@ video_dialog.add_video_data( inline=True ) -# Extract metadata +# Extract metadata (needs pip install "vcon[video]" and the ffmpeg binary) metadata = video_dialog.extract_video_metadata() -# Generate thumbnail -thumbnail = video_dialog.generate_thumbnail(timestamp=10.0) +# Generate thumbnail (JPEG bytes; generate_thumbnail() dispatches here for video) +thumbnail = video_dialog.generate_video_thumbnail(timestamp=10.0) vcon.add_dialog(video_dialog, session=0) ``` @@ -1591,8 +1628,8 @@ dialog = Dialog( ) vcon.add_dialog(dialog, session=0) -# Add WTF transcription attachment -vcon.add_wtf_transcription_attachment( +# Add WTF transcription (stored as analysis, per the WTF draft) +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, this is a test transcription.", "language": "en", @@ -1625,18 +1662,18 @@ vcon.add_wtf_transcription_attachment( "audio_quality": "high", "background_noise": 0.1 }, - party_index=0, dialog_index=0 ) -# Find WTF attachments -attachments = vcon.find_wtf_attachments(party_index=0) -print(f"Found {len(attachments)} WTF attachments") +# Find WTF transcriptions +transcriptions = [a for a in vcon.analysis if a["type"] == "wtf_transcription"] +print(f"Found {len(transcriptions)} WTF transcriptions") # Export to SRT format -if attachments: +entry = vcon.find_analysis_by_type("wtf_transcription") +if entry: from vcon.extensions.wtf import WTFAttachment - wtf_attachment = WTFAttachment.from_dict(attachments[0]["body"]) + wtf_attachment = WTFAttachment.from_dict(entry["body"]) srt_content = wtf_attachment.export_to_srt() print("SRT Export:") print(srt_content) @@ -1685,7 +1722,7 @@ whisper_adapter = WhisperAdapter() wtf_attachment = whisper_adapter.convert(whisper_data) # Add to vCon -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript=wtf_attachment.transcript.to_dict(), segments=[segment.to_dict() for segment in wtf_attachment.segments], metadata=wtf_attachment.metadata.to_dict(), @@ -1741,7 +1778,7 @@ vcon.add_lawful_basis_attachment( ) # Add transcription -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, I need help with my account.", "language": "en", @@ -1764,7 +1801,6 @@ vcon.add_wtf_transcription_attachment( "provider": "whisper", "model": "whisper-1" }, - party_index=0, dialog_index=0 ) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf7e263..42c28e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,63 @@ # Changelog +## [1.0.4] - 2026-11-18 + +### Fixed +- `is_valid()` reports a malformed `content_hash` on a Dialog, Attachment, + Analysis, `redacted_from` or `amended_from`. A ContentHash is + `-`; for `sha512` and `sha256` the + digest length is checked too, which catches hex digests and padded values. +- `is_valid()` checks the body of every `lawful_basis` attachment with the + lawful basis validator (required `lawful_basis`, `expiration` and + `purpose_grants`, and the fields of each grant and proof mechanism). + Proof types, hash algorithms and canonicalization methods outside the ones + the draft defines are now warnings, not errors, since the draft's lists are + open; warnings from nested grants and proof mechanisms are no longer lost. +- Loading a vCon keeps `created_at` exactly as written. It used to be + rewritten through `isoformat()` (`Z` became `+00:00`, fractions were padded), + which changed the document, and an unparseable value made `Vcon()` raise + instead of `is_valid()` reporting it. +- A vCon without `analysis`, `parties` or `dialog` (all optional) no longer + raises `KeyError` in `add_analysis()`, `add_party()`, `add_dialog()`, + `find_analysis_by_type()`, `find_dialog()`, `find_dialogs_by_type()` or + `find_party_index()`. +- `add_inline_data()` accepts bytes (encoded to base64url) as well as a + base64url string, and its `content_hash` is over the decoded content, the + same as `calculate_content_hash()`. +- The video helpers work. They imported the PyPI package `ffmpeg`, an empty + module, so `extract_video_metadata()`, the video thumbnail and + `transcode_video()` always failed. They now use ffmpeg-python from the new + `video` extra (`pip install "vcon[video]"`, plus the ffmpeg binary) and raise + a clear `ImportError` without it. `get_video_format_from_mediatype()` + defaults to the Dialog's mediatype, `transcode_video()` overwrites its temp + output and records the original format correctly. +- `Dialog` defined `generate_thumbnail()` twice, so the video version was + unreachable. It is now `generate_video_thumbnail()`, the image version is + `generate_image_thumbnail()`, and `generate_thumbnail()` calls whichever fits + the Dialog. +- Docstring examples that raised (no party or Session before an attachment) + now run. + +### Changed +- JWS signing and verification use joserfc instead of the deprecated + `authlib.jose`, so `import vcon` no longer prints a deprecation warning. + `sign()` and `verify()` are unchanged and interoperate with 1.0.3 in both + directions; they now also accept EC and Ed25519 key objects. `authlib` is no + longer a dependency; `joserfc` is. +- The `ffmpeg` dependency is gone; `ffmpeg-python` is the optional `video` + extra. +- `get_validation_warnings()` reports a `url` without a `content_hash` (a MUST + in core-05 section 2.4; it will be an `is_valid()` error in 1.1) and an + `encoding: "json"` body that is a serialized JSON string. +- `add_tag()` takes `party` (default 0) and raises `ValueError` for an index + that does not exist. On a vCon with no parties it still writes party 0 but + warns (`DeprecationWarning`), because the result fails `is_valid()`; it will + raise in 1.1. + +### Deprecated +- `add_wtf_transcription_attachment()`: draft-howe-vcon-wtf-extension stores + transcriptions as analysis. Use `add_wtf_transcription_analysis()`. + ## [1.0.3] - 2026-11-18 ### Fixed diff --git a/GUIDE.md b/GUIDE.md index 5bf7860..688f405 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -138,6 +138,14 @@ The `post_to_url` method enables sending a vCon to a URL endpoint: ### Tags ```python +# A new tags attachment names the party that adds the tags (core-05), so +# add a party first. On a vCon with no parties add_tag() still writes party 0 +# but emits a DeprecationWarning (it will raise ValueError in vcon 1.1). +# party= picks a party index other than the default 0; an index out of +# range raises ValueError. +vcon = Vcon.build_new() +vcon.add_party(Party(name="Support Desk")) + # Add a tag vcon.add_tag("category", "support") @@ -193,9 +201,9 @@ index = vcon.find_party_index("tel", "+1234567890") ### Adding Dialog Entries ```python # A Session lists the receivers (0.5.0); Dialog parties are the contributors -vcon.add_session(Session(start="2024-03-21T10:00:00Z", parties=[0, 1])) +session = vcon.add_session(Session(start="2024-03-21T10:00:00Z", parties=[0, 1])) -# Add a text dialog to Session 0 +# Add a text dialog to that Session (add_session() returns its index) dialog = Dialog( type="text", start="2024-03-21T10:00:00Z", @@ -204,14 +212,15 @@ dialog = Dialog( body="Hello, how can I help?", encoding="none", ) -vcon.add_dialog(dialog, session=0) +vcon.add_dialog(dialog, session=session) ``` ### Working with Media ```python -# Add inline data +# Add inline data: bytes are base64url-encoded for you; a str must already +# be base64url. content_hash is computed over the decoded content. dialog.add_inline_data( - body="base64_encoded_content", + body=b"raw audio bytes", filename="recording.wav", mediatype="audio/wav" ) @@ -232,7 +241,7 @@ vcon.add_attachment( body="content", encoding="none", party=0, - session=0 + session=session ) # Find attachment @@ -407,11 +416,13 @@ The WTF (World Transcription Format) extension provides standardized representat - **Provider Adapters**: Automatic conversion from provider-specific formats - **Analysis Tools**: Keyword extraction, confidence analysis, and transcription comparison -#### Adding WTF Transcription Attachments +#### Adding WTF Transcriptions + +The WTF draft stores a transcription as analysis: `add_wtf_transcription_analysis()` writes an analysis entry with type `"wtf_transcription"` and the WTF document as a JSON body. (`add_wtf_transcription_attachment()` wrote it to attachments and is deprecated; it emits a `DeprecationWarning`.) ```python -# Add WTF transcription attachment -vcon.add_wtf_transcription_attachment( +# Add WTF transcription analysis +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, this is a test transcription.", "language": "en", @@ -444,29 +455,29 @@ vcon.add_wtf_transcription_attachment( "audio_quality": "high", "background_noise": 0.1 }, - party_index=0, dialog_index=0 ) ``` -#### Finding WTF Attachments +#### Finding WTF Transcriptions ```python -# Find all WTF attachments -attachments = vcon.find_wtf_attachments() +# Find the first WTF transcription and read its body +entry = vcon.find_analysis_by_type("wtf_transcription") +wtf_body = Vcon.decoded_body(entry) -# Find attachments for a specific party -party_attachments = vcon.find_wtf_attachments(party_index=0) +# Find all WTF transcriptions +transcriptions = [a for a in vcon.analysis if a["type"] == "wtf_transcription"] ``` #### Exporting Transcriptions ```python -# Find WTF attachments and export to SRT -attachments = vcon.find_wtf_attachments(party_index=0) -if attachments: +# Find the WTF transcription and export to SRT +entry = vcon.find_analysis_by_type("wtf_transcription") +if entry: from vcon.extensions.wtf import WTFAttachment - wtf_attachment = WTFAttachment.from_dict(attachments[0]["body"]) + wtf_attachment = WTFAttachment.from_dict(entry["body"]) # Export to SRT format srt_content = wtf_attachment.export_to_srt() @@ -500,7 +511,7 @@ whisper_adapter = WhisperAdapter() wtf_attachment = whisper_adapter.convert(whisper_data) # Add to vCon -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript=wtf_attachment.transcript.to_dict(), segments=[segment.to_dict() for segment in wtf_attachment.segments], metadata=wtf_attachment.metadata.to_dict(), @@ -675,7 +686,7 @@ vcon.add_lawful_basis_attachment( ) # Add transcription -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, I need help with my account.", "language": "en", @@ -698,7 +709,6 @@ vcon.add_wtf_transcription_attachment( "provider": "whisper", "model": "whisper-1" }, - party_index=0, dialog_index=0 ) @@ -732,6 +742,8 @@ vcon.sign(private_key) is_valid = vcon.verify(public_key) ``` +`sign()` and `verify()` use joserfc and accept RSA, EC and Ed25519 keys, as `cryptography` key objects or PEM (`alg` RS\*, PS\*, ES\* or EdDSA). + ### Validation ```python # Validate vCon object @@ -744,6 +756,8 @@ is_valid, errors = Vcon.validate_file("conversation.json") is_valid, errors = Vcon.validate_json(json_string) ``` +Besides the structure rules, `is_valid()` reports a malformed `content_hash` (it must be `-`: 86 characters for sha512, 43 for sha256), an unparseable `created_at`, and problems in the body of every `lawful_basis` attachment (missing `lawful_basis`, `expiration`, `purpose_grants` and so on). `vcon.get_validation_warnings()` returns findings that do not make the vCon invalid: a `url` without a `content_hash` on a dialog, attachment or analysis entry (a warning in 1.0.x, an `is_valid()` error from vcon 1.1), an `encoding: "json"` body that is a serialized JSON string, and lawful-basis warnings (an unknown proof type, hash algorithm or canonicalization method is a warning, not an error). Loading a vCon keeps `created_at` exactly as written. + ### UUID Generation ```python # Generate UUID8 from domain name diff --git a/LLM_GUIDE.md b/LLM_GUIDE.md index 840e1ef..a3b429c 100644 --- a/LLM_GUIDE.md +++ b/LLM_GUIDE.md @@ -36,8 +36,9 @@ pip install -e . ## Requirements - Python 3.12+ -- Core dependencies: authlib, uuid6, requests, pydash, python-dateutil -- Media and document dependencies: mutagen, ffmpeg (ffmpeg-python), pillow, pypdf +- Core dependencies: joserfc (JWS signing), uuid6, requests, pydash, python-dateutil +- Media and document dependencies: mutagen, pillow, pypdf +- Optional video support: `pip install "vcon[video]"` (ffmpeg-python) plus the ffmpeg binary on `PATH`, needed by `extract_video_metadata()`, `generate_video_thumbnail()` and `transcode_video()` ## Core Classes and Usage Patterns @@ -269,10 +270,10 @@ Events and a Session), and Dialog parameters such as `transfer`, `party_history` ### 4. Working with Tags -Tags are key-value pairs for simple metadata. +Tags are key-value pairs for simple metadata. The tags attachment names the party that adds the tags: `add_tag(name, value, party=None)` uses party 0 by default. Always add a party before the first tag: on a vCon with no parties `add_tag()` still writes party 0 (so the vCon fails `is_valid()`) and emits a `DeprecationWarning`, and from vcon 1.1 it will raise `ValueError`. A `party` index that is out of range raises `ValueError`. ```python -# Add tags +# Add tags (the vCon already has parties) vcon.add_tag("customer_id", "12345") vcon.add_tag("interaction_id", "INT-001") @@ -485,11 +486,13 @@ The WTF extension provides standardized representation of speech-to-text transcr - **Provider Adapters**: Automatic conversion from provider-specific formats - **Analysis Tools**: Keyword extraction, confidence analysis, and transcription comparison -#### Adding WTF Transcription Attachments +#### Adding WTF Transcriptions + +The WTF draft stores a transcription as analysis. Use `add_wtf_transcription_analysis()`, which writes an analysis entry with type `"wtf_transcription"` and the WTF document as a JSON body. `add_wtf_transcription_attachment()` is deprecated (it emits a `DeprecationWarning`); do not generate new code with it. ```python -# Add WTF transcription attachment -vcon.add_wtf_transcription_attachment( +# Add WTF transcription analysis +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, this is a test transcription.", "language": "en", @@ -522,7 +525,6 @@ vcon.add_wtf_transcription_attachment( "audio_quality": "high", "background_noise": 0.1 }, - party_index=0, dialog_index=0 ) @@ -530,24 +532,25 @@ vcon.add_wtf_transcription_attachment( vcon.add_extension("wtf_transcription") ``` -#### Finding WTF Attachments +#### Finding WTF Transcriptions ```python -# Find all WTF attachments -attachments = vcon.find_wtf_attachments() +# Find the first WTF transcription and read its body +entry = vcon.find_analysis_by_type("wtf_transcription") +wtf_body = Vcon.decoded_body(entry) -# Find attachments for a specific party -party_attachments = vcon.find_wtf_attachments(party_index=0) +# Find all WTF transcriptions +transcriptions = [a for a in vcon.analysis if a["type"] == "wtf_transcription"] ``` #### Exporting Transcriptions ```python -# Find WTF attachments and export to SRT -attachments = vcon.find_wtf_attachments(party_index=0) -if attachments: +# Find the WTF transcription and export to SRT +entry = vcon.find_analysis_by_type("wtf_transcription") +if entry: from vcon.extensions.wtf import WTFAttachment - wtf_attachment = WTFAttachment.from_dict(attachments[0]["body"]) + wtf_attachment = WTFAttachment.from_dict(entry["body"]) # Export to SRT format srt_content = wtf_attachment.export_to_srt() @@ -581,7 +584,7 @@ whisper_adapter = WhisperAdapter() wtf_attachment = whisper_adapter.convert(whisper_data) # Add to vCon -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript=wtf_attachment.transcript.to_dict(), segments=[segment.to_dict() for segment in wtf_attachment.segments], metadata=wtf_attachment.metadata.to_dict(), @@ -821,6 +824,8 @@ vcon.sign(private_key) is_valid = vcon.verify(public_key) ``` +JWS signing uses joserfc. `sign(key, alg=...)` and `verify(key)` accept RSA, EC and Ed25519 keys as `cryptography` key objects or PEM (`alg` RS\*/PS\* for RSA, ES\* for EC, EdDSA for Ed25519). + ### Validation ```python @@ -829,6 +834,9 @@ is_valid, errors = vcon.is_valid() if not is_valid: print("Validation errors:", errors) +# SHOULD-level findings (not errors) +warnings = vcon.get_validation_warnings() + # Validate a file is_valid, errors = Vcon.validate_file("conversation.json") @@ -836,6 +844,13 @@ is_valid, errors = Vcon.validate_file("conversation.json") is_valid, errors = Vcon.validate_json(json_string) ``` +`is_valid()` also reports: +- a malformed `content_hash`: it must be `-` (86 characters for sha512, 43 for sha256); use `compute_content_hash()` or `calculate_content_hash()` rather than writing one by hand +- an unparseable `created_at` (loading keeps `created_at` exactly as written and no longer reformats or rejects it) +- errors in the body of every `lawful_basis` attachment (missing `lawful_basis`, `expiration`, `purpose_grants` and so on) + +`get_validation_warnings()` adds a `url` without a `content_hash` on a dialog, attachment or analysis entry (a MUST in core-05: a warning in 1.0.x, an `is_valid()` error from vcon 1.1, so always set `content_hash` with a `url`), an `encoding: "json"` body that is a serialized JSON string (pass the JSON value itself), and lawful-basis warnings; an unknown proof type, hash algorithm or canonicalization method is a warning, not an error. + ## Common Patterns and Best Practices ### 1. Creating a Complete Conversation @@ -907,6 +922,8 @@ audio_dialog = Dialog( encoding="base64url", filename="recording.mp3" ) +# Or let the Dialog encode raw bytes and set content_hash for you: +# audio_dialog.add_inline_data(audio_data, "recording.mp3", "audio/mp3") vcon.add_dialog(audio_dialog, session=0) ``` @@ -934,6 +951,8 @@ if dialog.is_inline_data(): ### 4. Video Content Handling +`extract_video_metadata()`, `generate_video_thumbnail()` and `transcode_video()` need `pip install "vcon[video]"` (ffmpeg-python) and the ffmpeg binary on `PATH`. + ```python # Add video data with metadata (a "recording"; the mediatype says it is video) video_dialog = Dialog( @@ -958,8 +977,8 @@ video_dialog.add_video_data( # Extract video metadata using FFmpeg metadata = video_dialog.extract_video_metadata() -# Generate thumbnail -thumbnail_data = video_dialog.generate_thumbnail( +# Generate a JPEG thumbnail (bytes); generate_thumbnail() dispatches here for video +thumbnail_data = video_dialog.generate_video_thumbnail( timestamp=10.0, # Time in seconds width=320, height=240, @@ -992,8 +1011,8 @@ image_dialog.add_image_data( mediatype="image/jpeg" # Optional, auto-detected if not provided ) -# Generate thumbnail -thumbnail_b64 = image_dialog.generate_thumbnail(max_size=(200, 200)) +# Generate a thumbnail (base64url str); generate_thumbnail() dispatches here for images +thumbnail_b64 = image_dialog.generate_image_thumbnail(max_size=(200, 200)) # Check if dialog has image content if image_dialog.is_image(): @@ -1198,8 +1217,8 @@ def create_extension_enabled_conversation(): party_index=0 ) - # Add transcription - vcon.add_wtf_transcription_attachment( + # Add transcription (stored as analysis, per the WTF draft) + vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, I need help with my account.", "language": "en", @@ -1222,7 +1241,6 @@ def create_extension_enabled_conversation(): "provider": "whisper", "model": "whisper-1" }, - party_index=0, dialog_index=0 ) @@ -1599,7 +1617,7 @@ def add_privacy_compliance(vcon, party_index, purposes, expiration_days=365): #### Converting Provider Transcription to WTF ```python -def convert_provider_transcription(vcon, provider_data, provider_type, party_index=0, dialog_index=0): +def convert_provider_transcription(vcon, provider_data, provider_type, dialog_index=0): """Convert provider-specific transcription data to WTF format.""" from vcon.extensions.wtf import WhisperAdapter, DeepgramAdapter, AssemblyAIAdapter @@ -1618,11 +1636,10 @@ def convert_provider_transcription(vcon, provider_data, provider_type, party_ind wtf_attachment = adapter.convert(provider_data) # Add to vCon - vcon.add_wtf_transcription_attachment( + vcon.add_wtf_transcription_analysis( transcript=wtf_attachment.transcript.to_dict(), segments=[segment.to_dict() for segment in wtf_attachment.segments], metadata=wtf_attachment.metadata.to_dict(), - party_index=party_index, dialog_index=dialog_index ) @@ -1642,14 +1659,14 @@ def check_privacy_permissions(vcon, party_index, purposes): #### Exporting Transcriptions ```python -def export_transcriptions(vcon, party_index=None, format="srt"): +def export_transcriptions(vcon, format="srt"): """Export transcriptions from vCon to various formats.""" - attachments = vcon.find_wtf_attachments(party_index) + entries = [a for a in vcon.analysis if a["type"] == "wtf_transcription"] exports = [] - for attachment in attachments: + for entry in entries: from vcon.extensions.wtf import WTFAttachment - wtf_attachment = WTFAttachment.from_dict(attachment["body"]) + wtf_attachment = WTFAttachment.from_dict(entry["body"]) if format.lower() == "srt": content = wtf_attachment.export_to_srt() @@ -1659,9 +1676,8 @@ def export_transcriptions(vcon, party_index=None, format="srt"): raise ValueError(f"Unsupported format: {format}") exports.append({ - "party_index": attachment.get("party"), - "dialog_index": attachment.get("dialog"), - "session_index": attachment.get("session"), + "dialog": entry.get("dialog"), + "sessions": entry.get("sessions"), "format": format, "content": content }) diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 95a505f..b2d70b3 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -1,5 +1,47 @@ # Migration Guide +## Upgrading to library 1.0.4 + +1.0.4 is a fix release on vCon 0.5.0. Most code runs unchanged; check these: + +| Before 1.0.4 | 1.0.4 | +| --- | --- | +| `add_wtf_transcription_attachment()` | deprecated (`DeprecationWarning`): the WTF draft stores a transcription as analysis. Use `add_wtf_transcription_analysis(transcript, segments, metadata, dialog_index=None, session_index=None, **kwargs)`; read it back with `vcon.find_analysis_by_type("wtf_transcription")` instead of `find_wtf_attachments()` | +| `add_tag()` on a vCon with no parties wrote `party: 0` silently | still writes party 0, but emits a `DeprecationWarning` (the vCon fails `is_valid()`); it will raise `ValueError` in 1.1. Add a party before the first tag. New `party=` argument (default 0); an index out of range raises `ValueError` | +| `is_valid()` did not check `content_hash` or lawful-basis bodies | errors for a malformed `content_hash` (`-`, 86 characters for sha512, 43 for sha256) and for problems in a `lawful_basis` attachment body. Unknown lawful-basis proof types, hash algorithms and canonicalization methods are warnings | +| no check for `url` without `content_hash` | reported by `get_validation_warnings()`; an `is_valid()` error from 1.1 | +| (no check) | `get_validation_warnings()` reports an `encoding: "json"` body that is a serialized JSON string | +| loading rewrote `created_at` into Python's ISO format (and an unparseable value crashed `Vcon()`) | `created_at` is kept exactly as written; `is_valid()` reports an unparseable value | +| `Dialog.add_inline_data()` took a str and hashed the base64url text | also takes `bytes` (encoded for you); `content_hash` is over the decoded content | +| `Dialog.generate_thumbnail()` was always the image version | dispatches to `generate_image_thumbnail(max_size)` or `generate_video_thumbnail(timestamp, width, height, quality)` | +| `ffmpeg` dependency (the wrong package: video helpers failed) | optional: `pip install "vcon[video]"` (ffmpeg-python) plus the ffmpeg binary | +| `authlib` for JWS | `joserfc`; `sign()`/`verify()` are unchanged and also accept EC and Ed25519 keys | + +```python +from vcon import Vcon +from vcon.party import Party +from vcon.session import Session + +vcon = Vcon.build_new() +vcon.add_party(Party(name="Alice")) # before add_tag() +vcon.add_session(Session(start="2024-01-01T00:00:00Z", parties=[0])) +vcon.add_tag("category", "support") + +# Was: vcon.add_wtf_transcription_attachment(...) and vcon.find_wtf_attachments() +vcon.add_wtf_transcription_analysis( + transcript={"text": "Hello", "language": "en", "duration": 1.0, "confidence": 0.9}, + segments=[{"id": 0, "start": 0.0, "end": 1.0, "text": "Hello", "confidence": 0.9}], + metadata={"created_at": "2024-01-01T00:00:00Z", "processed_at": "2024-01-01T00:00:05Z", + "provider": "whisper", "model": "whisper-1"}, + session_index=0, +) +entry = vcon.find_analysis_by_type("wtf_transcription") +wtf_body = Vcon.decoded_body(entry) + +is_valid, errors = vcon.is_valid() +warnings = vcon.get_validation_warnings() +``` + ## Migrating to vCon 0.5.0 (library 1.0.0) Library 1.0.0 implements `draft-ietf-vcon-vcon-core-05` (syntax `"0.5.0"`). Readers accept 0.4.0 and 0.5.0; diff --git a/README.md b/README.md index ac18c74..21b1c3c 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ print(f"Can record: {can_record}") ### Transcription with WTF Extension ```python # Add transcription -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, I need help with my account.", "language": "en", @@ -130,15 +130,14 @@ vcon.add_wtf_transcription_attachment( "provider": "whisper", "model": "whisper-1" }, - party_index=0, dialog_index=0 ) # Export to SRT format -attachments = vcon.find_wtf_attachments(party_index=0) -if attachments: +entry = vcon.find_analysis_by_type("wtf_transcription") +if entry: from vcon.extensions.wtf import WTFAttachment - wtf_attachment = WTFAttachment.from_dict(attachments[0]["body"]) + wtf_attachment = WTFAttachment.from_dict(Vcon.decoded_body(entry)) srt_content = wtf_attachment.export_to_srt() print("SRT Export:") print(srt_content) @@ -185,7 +184,7 @@ vcon.add_lawful_basis_attachment( ) # Add transcription -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, I need help with my account.", "language": "en", @@ -208,7 +207,6 @@ vcon.add_wtf_transcription_attachment( "provider": "whisper", "model": "whisper-1" }, - party_index=0, dialog_index=0 ) @@ -377,7 +375,7 @@ attachments = vcon.find_lawful_basis_attachments(party_index=0) ### WTF Extension (Transcription Support) ```python # Add standardized transcription -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript={ "text": "Hello, this is a test transcription.", "language": "en", @@ -408,15 +406,14 @@ vcon.add_wtf_transcription_attachment( "provider": "whisper", "model": "whisper-1" }, - party_index=0, dialog_index=0 ) # Export to subtitle formats -attachments = vcon.find_wtf_attachments(party_index=0) -if attachments: +entry = vcon.find_analysis_by_type("wtf_transcription") +if entry: from vcon.extensions.wtf import WTFAttachment - wtf_attachment = WTFAttachment.from_dict(attachments[0]["body"]) + wtf_attachment = WTFAttachment.from_dict(Vcon.decoded_body(entry)) # Export to SRT format srt_content = wtf_attachment.export_to_srt() @@ -445,11 +442,10 @@ whisper_adapter = WhisperAdapter() wtf_attachment = whisper_adapter.convert(whisper_data) # Add to vCon -vcon.add_wtf_transcription_attachment( +vcon.add_wtf_transcription_analysis( transcript=wtf_attachment.transcript.to_dict(), segments=[segment.to_dict() for segment in wtf_attachment.segments], metadata=wtf_attachment.metadata.to_dict(), - party_index=0, session_index=0 ) ``` @@ -458,6 +454,8 @@ vcon.add_wtf_transcription_attachment( ```bash pip install vcon +pip install "vcon[image]" # image and PDF helpers (Pillow, pypdf) +pip install "vcon[video]" # video metadata, thumbnails and transcoding (ffmpeg-python; needs the ffmpeg binary) ``` ## Basic Usage @@ -701,8 +699,8 @@ processing_results = vcon.process_extensions() # Check specific permissions can_record = vcon.check_lawful_basis_permission("recording", party_index=0) -# Export transcriptions -attachments = vcon.find_wtf_attachments(party_index=0) +# Find transcriptions +transcripts = [a for a in vcon.analysis if a["type"] == "wtf_transcription"] ``` ## Documentation diff --git a/docs/source/installation.rst b/docs/source/installation.rst index f73c7ab..d264c26 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -17,8 +17,13 @@ installs: pip install "vcon[image]" -Some video features call the ``ffmpeg`` binary, which must be installed -separately and on your ``PATH``. +The video helpers (metadata, thumbnails, transcoding) need ffmpeg-python, +which the ``video`` extra installs, and the ``ffmpeg`` binary on your +``PATH``: + +.. code-block:: bash + + pip install "vcon[video]" From source ----------- @@ -46,5 +51,6 @@ Dependencies ------------ The runtime dependencies are listed in ``pyproject.toml`` and installed -automatically: authlib, uuid6, requests, pydash, python-dateutil, mutagen, -and ffmpeg. Pillow and pypdf come with the ``image`` extra. +automatically: joserfc (JWS signing), uuid6, requests, pydash, +python-dateutil and mutagen. Pillow and pypdf come with the ``image`` extra, +ffmpeg-python with the ``video`` extra. diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 8cf0d29..60ea14e 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -139,7 +139,9 @@ vCon has exactly one and raises ``ValueError`` otherwise. ) Tags are whole-vCon metadata. ``add_tag()`` lists every Session, and adds an -empty placeholder Session when the vCon has none. +empty placeholder Session when the vCon has none. The tags attachment needs a +valid ``party`` (default 0, or pass ``party=``), so add a party first; on a +vCon with no parties ``add_tag()`` warns, and from 1.1 it will raise. .. code-block:: python @@ -182,10 +184,19 @@ Reading and validating is_valid, errors = Vcon.validate_file("conversation.vcon.json") +Besides the structure and references, ``is_valid()`` checks that every +``content_hash`` has the form ``-`` and +the body of every ``lawful_basis`` attachment. A ``url`` without a +``content_hash`` is reported by ``get_validation_warnings()`` in 1.0.x and +will be an error from 1.1. Loading keeps every value as written, including +timestamps, so an invalid ``created_at`` is reported by ``is_valid()`` rather +than raised. + Signing ------- -``sign()`` uses RS256 by default. ``sign()`` and ``verify()`` reject the JWS +``sign()`` uses RS256 by default and accepts RSA, EC and Ed25519 keys (RS*, +PS*, ES* and EdDSA), as cryptography key objects or PEM. ``sign()`` and ``verify()`` reject the JWS ``alg`` value ``"none"`` with ``AlgorithmNotPermittedError``. .. code-block:: python diff --git a/poetry.lock b/poetry.lock index f27974c..0e4b4dd 100644 --- a/poetry.lock +++ b/poetry.lock @@ -24,22 +24,6 @@ files = [ {file = "attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"}, ] -[[package]] -name = "authlib" -version = "1.7.2" -description = "The ultimate Python library in building OAuth and OpenID Connect servers and clients." -optional = false -python-versions = ">=3.10" -groups = ["main"] -files = [ - {file = "authlib-1.7.2-py2.py3-none-any.whl", hash = "sha256:3e1faedc9d87e7d56a164eca3ccb6ace0d61b94abe83e92242f8dc8bba9b4a9f"}, - {file = "authlib-1.7.2.tar.gz", hash = "sha256:2cea25fefcd4e7173bdf1372c0afc265c8034b23a8cd5dcb6a9164b826c64231"}, -] - -[package.dependencies] -cryptography = "*" -joserfc = ">=1.6.0" - [[package]] name = "babel" version = "2.16.0" @@ -438,16 +422,24 @@ files = [ ] [[package]] -name = "ffmpeg" -version = "1.4" -description = "ffmpeg python package url [https://github.com/jiashaokun/ffmpeg]" -optional = false +name = "ffmpeg-python" +version = "0.2.0" +description = "Python bindings for FFmpeg - with complex filtering support" +optional = true python-versions = "*" groups = ["main"] +markers = "extra == \"video\"" files = [ - {file = "ffmpeg-1.4.tar.gz", hash = "sha256:6931692c890ff21d39938433c2189747815dca0c60ddc7f9bb97f199dba0b5b9"}, + {file = "ffmpeg-python-0.2.0.tar.gz", hash = "sha256:65225db34627c578ef0e11c8b1eb528bb35e024752f6f10b78c011f6f64c4127"}, + {file = "ffmpeg_python-0.2.0-py3-none-any.whl", hash = "sha256:ac441a0404e053f8b6a1113a77c0f452f1cfc62f6344a769475ffdc0f56c23c5"}, ] +[package.dependencies] +future = "*" + +[package.extras] +dev = ["Sphinx (==2.1.0)", "future (==0.17.1)", "numpy (==1.16.4)", "pytest (==4.6.1)", "pytest-mock (==1.10.4)", "tox (==3.12.1)"] + [[package]] name = "flake8" version = "7.1.2" @@ -465,6 +457,19 @@ mccabe = ">=0.7.0,<0.8.0" pycodestyle = ">=2.12.0,<2.13.0" pyflakes = ">=3.2.0,<3.3.0" +[[package]] +name = "future" +version = "1.0.0" +description = "Clean single-source support for Python 3 and 2" +optional = true +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" +groups = ["main"] +markers = "extra == \"video\"" +files = [ + {file = "future-1.0.0-py3-none-any.whl", hash = "sha256:929292d34f5872e70396626ef385ec22355a1fae8ad29e1a734c3e43f9fbc216"}, + {file = "future-1.0.0.tar.gz", hash = "sha256:bd2968309307861edae1458a4f8a4f3598c03be43b97521076aebf5d94c07b05"}, +] + [[package]] name = "idna" version = "3.15" @@ -1371,8 +1376,9 @@ files = [ [extras] image = ["pillow", "pypdf"] +video = ["ffmpeg-python"] [metadata] lock-version = "2.1" python-versions = "^3.12" -content-hash = "55cca0e4301450d0fd21e42f42856fb7a728473d731d7459deb4e8b5825c37ee" +content-hash = "7fc2de44d4743e2016fdd45b0f3e5252e81ff47575b073a82c12546c4fbb062c" diff --git a/pyproject.toml b/pyproject.toml index ecd9e05..b5ecf3d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "vcon" -version = "1.0.3" +version = "1.0.4" description = "The vCon library - vCon 0.5.0 (draft-ietf-vcon-vcon-core-05) specification implementation" authors = ["Thomas McCarthy-Howe "] license = "MIT" @@ -28,13 +28,13 @@ packages = [ [tool.poetry.dependencies] python = "^3.12" -authlib = "^1.6.12" +joserfc = "^1.6.8" uuid6 = "^2024.7.10" requests = "^2.33.0" pydash = "^8.0.3" python-dateutil = "^2.9.0.post0" mutagen = "^1.47.0" -ffmpeg = "^1.4" +ffmpeg-python = { version = "^0.2.0", optional = true } pypdf = "^6.10.2" pillow = "^12.2.0" @@ -54,4 +54,5 @@ requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" [tool.poetry.extras] -image = ["Pillow", "pypdf"] \ No newline at end of file +image = ["Pillow", "pypdf"] +video = ["ffmpeg-python"] \ No newline at end of file diff --git a/setup.py b/setup.py index ab95a28..b772c63 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name="vcon", - version="1.0.3", + version="1.0.4", 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 344eddf..1898f9b 100644 --- a/src/vcon/dialog.py +++ b/src/vcon/dialog.py @@ -11,6 +11,24 @@ logger = logging.getLogger(__name__) + +def _import_ffmpeg(): + """Import ffmpeg-python for the video helpers, with a clear error if it is missing. + + The PyPI package named ``ffmpeg`` is an unrelated empty module; the video + helpers need ``ffmpeg-python`` (the ``video`` extra) and the ffmpeg binary. + """ + try: + import ffmpeg + except ImportError: + ffmpeg = None + if ffmpeg is None or not hasattr(ffmpeg, "probe"): + raise ImportError( + "The video helpers need ffmpeg-python: pip install 'vcon[video]', " + "and the ffmpeg binary on PATH." + ) + return ffmpeg + MIME_TYPES = [ "text/plain", "audio/x-wav", @@ -222,7 +240,8 @@ class Dialog: ] - # Include the required types for tests to pass + # recording, text and incomplete are the core-05 types; audio and video + # are deprecated aliases accepted on construction (they become recording). VALID_TYPES = [ "recording", "text", @@ -482,12 +501,16 @@ def add_external_data(self, url: str, filename: str, mediatype: str) -> None: raw_content = response.content self.content_hash = compute_content_hash(raw_content) - def add_inline_data(self, body: str, filename: str, mediatype: str) -> None: + def add_inline_data(self, body: Union[str, bytes], filename: str, mediatype: str) -> None: """ Add inline data to the dialog. - :param body: the body of the inline data - :type body: str + The Dialog is written with ``encoding: "base64url"``. Pass raw ``bytes`` + and they are encoded; a ``str`` is taken to be base64url already. The + ``content_hash`` is over the decoded content. + + :param body: the content as bytes, or as a base64url string + :type body: bytes or str :param filename: the filename of the inline data :type filename: str :param mediatype: the mediatype of the inline data @@ -495,11 +518,13 @@ def add_inline_data(self, body: str, filename: str, mediatype: str) -> None: :return: None :rtype: None """ + if isinstance(body, (bytes, bytearray)): + body = b64url_encode(bytes(body)) self.body = body self.mediatype = mediatype self.filename = filename self.encoding = "base64url" - self.content_hash = compute_content_hash(self.body.encode()) + self.content_hash = compute_content_hash(self._content_bytes()) def is_external_data(self) -> bool: """ @@ -696,7 +721,7 @@ def extract_video_metadata(self, video_path=None) -> dict: Returns: Dictionary containing detailed video metadata """ - import ffmpeg + ffmpeg = _import_ffmpeg() # Create temporary file if working with inline data temp_file = None @@ -800,7 +825,7 @@ def _calculate_frame_rate(self, frame_rate_str): except (ValueError, ZeroDivisionError): return 0 - def generate_thumbnail(self, timestamp=0.0, width=320, height=240, quality=90) -> bytes: + def generate_video_thumbnail(self, timestamp=0.0, width=320, height=240, quality=90) -> bytes: """ Generate a high-quality thumbnail from the video at the specified timestamp. @@ -813,7 +838,7 @@ def generate_thumbnail(self, timestamp=0.0, width=320, height=240, quality=90) - Returns: Binary thumbnail data in JPEG format """ - import ffmpeg + ffmpeg = _import_ffmpeg() if not self.is_video(): raise ValueError("Cannot generate thumbnail for non-video content") @@ -935,12 +960,12 @@ def add_streaming_video_reference(self, reference_id, mediatype, metadata=None) self.meta["video"] = metadata - def get_video_format_from_mediatype(self, mediatype) -> str: + def get_video_format_from_mediatype(self, mediatype: Optional[str] = None) -> str: """ Get the video format name from a MIME type. Args: - mediatype: MIME type of the video + mediatype: MIME type of the video (default: this Dialog's mediatype) Returns: Format name (mp4, mov, etc.) @@ -957,6 +982,8 @@ def get_video_format_from_mediatype(self, mediatype) -> str: 'video/ogg': 'ogg' } + if mediatype is None: + mediatype = getattr(self, "mediatype", None) return mediatype_to_format.get(mediatype, 'unknown') def has_thumbnail(self) -> bool: @@ -1018,7 +1045,7 @@ def transcode_video(self, target_format, codec=None, bit_rate=None, width=None, Returns: None - updates the dialog's content in place """ - import ffmpeg + ffmpeg = _import_ffmpeg() if not self.is_video(): raise ValueError("Cannot transcode non-video content") @@ -1044,6 +1071,7 @@ def transcode_video(self, target_format, codec=None, bit_rate=None, width=None, else: raise ValueError("Cannot transcode: no video content available") + original_format = self.get_video_format_from_mediatype() # Setup output file temp_output = tempfile.NamedTemporaryFile(delete=False, suffix=f".{target_format}") temp_output.close() @@ -1063,7 +1091,7 @@ def transcode_video(self, target_format, codec=None, bit_rate=None, width=None, output_params['b:v'] = bit_rate # Run transcoding - ffmpeg.output(stream, temp_output.name, **output_params).run(quiet=True) + ffmpeg.output(stream, temp_output.name, **output_params).overwrite_output().run(quiet=True) # Read the transcoded file with open(temp_output.name, "rb") as f: @@ -1101,7 +1129,7 @@ def transcode_video(self, target_format, codec=None, bit_rate=None, width=None, self.metadata["video"] = metadata self.metadata["video"]["transcoded"] = { - "original_format": self.get_video_format_from_mediatype(), + "original_format": original_format, "target_format": target_format, "codec": codec, "bit_rate": bit_rate, @@ -1265,7 +1293,20 @@ def extract_image_metadata(self, image_data: bytes, mediatype: str) -> None: # PIL not installed self.metadata["image"]["note"] = "Install Pillow for enhanced image metadata" - def generate_thumbnail(self, max_size: Tuple[int, int] = (200, 200)) -> Optional[str]: + def generate_thumbnail(self, *args, **kwargs): + """ + Generate a thumbnail for an image or a video Dialog. + + For an image this calls :meth:`generate_image_thumbnail` (``max_size``, + returns a base64url string or None). For a video it calls + :meth:`generate_video_thumbnail` (``timestamp``, ``width``, ``height``, + ``quality``; returns JPEG bytes). + """ + if self.is_video(): + return self.generate_video_thumbnail(*args, **kwargs) + return self.generate_image_thumbnail(*args, **kwargs) + + def generate_image_thumbnail(self, max_size: Tuple[int, int] = (200, 200)) -> Optional[str]: """ Generate a thumbnail for the image and return it as a base64-encoded string. diff --git a/src/vcon/extensions/lawful_basis/validation.py b/src/vcon/extensions/lawful_basis/validation.py index 69c20b7..8e85c0a 100644 --- a/src/vcon/extensions/lawful_basis/validation.py +++ b/src/vcon/extensions/lawful_basis/validation.py @@ -93,9 +93,9 @@ def validate_attachment(self, attachment: Dict[str, Any]) -> ValidationResult: # Validate required fields body_result = self._validate_lawful_basis_body(body) + result.warnings.extend(body_result.warnings) if not body_result.is_valid: result.errors.extend(body_result.errors) - result.warnings.extend(body_result.warnings) result.is_valid = False return result @@ -168,6 +168,7 @@ def _validate_lawful_basis_body(self, body: Dict[str, Any]) -> ValidationResult: # Validate optional fields if "content_hash" in body: hash_result = self._validate_content_hash(body["content_hash"]) + result.warnings.extend(f"Content hash: {w}" for w in hash_result.warnings) if not hash_result.is_valid: result.add_error(f"Content hash validation failed: {', '.join(hash_result.errors)}") result.is_valid = False @@ -179,6 +180,7 @@ def _validate_lawful_basis_body(self, body: Dict[str, Any]) -> ValidationResult: else: for i, proof in enumerate(proof_mechanisms): proof_result = self._validate_proof_mechanism(proof) + result.warnings.extend(f"Proof mechanism {i}: {w}" for w in proof_result.warnings) if not proof_result.is_valid: result.add_error(f"Proof mechanism {i}: {', '.join(proof_result.errors)}") result.is_valid = False @@ -234,13 +236,13 @@ def _validate_content_hash(self, content_hash: Dict[str, Any]) -> ValidationResu if "algorithm" in content_hash: algorithm = content_hash["algorithm"] if algorithm not in self.supported_hash_algorithms: - result.add_error(f"Unsupported hash algorithm: {algorithm}") + result.add_warning(f"Hash algorithm {algorithm!r} is not one this library can verify") # Validate canonicalization if "canonicalization" in content_hash: canonicalization = content_hash["canonicalization"] if canonicalization not in self.supported_canonicalization: - result.add_error(f"Unsupported canonicalization method: {canonicalization}") + result.add_warning(f"Canonicalization method {canonicalization!r} is not one this library can apply") # Validate hash value format if "value" in content_hash: @@ -263,7 +265,7 @@ def _validate_proof_mechanism(self, proof: Dict[str, Any]) -> ValidationResult: if "proof_type" in proof: proof_type = proof["proof_type"] if proof_type not in self.supported_proof_types: - result.add_error(f"Unsupported proof type: {proof_type}") + result.add_warning(f"Proof type {proof_type!r} is not one of the types the draft defines") # Validate timestamp if "timestamp" in proof: diff --git a/src/vcon/validation.py b/src/vcon/validation.py index 8b936c0..fc73338 100644 --- a/src/vcon/validation.py +++ b/src/vcon/validation.py @@ -6,6 +6,7 @@ from __future__ import annotations +import json import re from typing import Any, Dict, List, Set, Tuple @@ -57,6 +58,62 @@ _REDACTED_REF_RE = re.compile(r"__REDACTED_REF_(\d{1,5})(?!\d)") +# ContentHash token (section 2.2): "-". +_CONTENT_HASH_RE = re.compile(r"^([a-z0-9]+)-([A-Za-z0-9_-]+)$") +# Unpadded base64url length of the digests this library knows. +_DIGEST_B64_LENGTHS = {"sha512": 86, "sha256": 43} + + +def content_hash_problems(value: Any) -> List[str]: + """Return why ``value`` is not a ContentHash or ContentHash[] (empty if it is).""" + tokens = value if isinstance(value, list) else [value] + if isinstance(value, list) and not value: + return ["must not be an empty array"] + problems = [] + for token in tokens: + if not isinstance(token, str): + problems.append(f"{token!r} is not a string") + continue + m = _CONTENT_HASH_RE.match(token) + if not m: + problems.append(f"{token!r} is not of the form '-'") + continue + expected = _DIGEST_B64_LENGTHS.get(m.group(1)) + if expected is not None and len(m.group(2)) != expected: + problems.append( + f"{token!r} has a {m.group(1)} digest of {len(m.group(2))} base64url characters, " + f"expected {expected}" + ) + return problems + + +def _check_content(obj: Dict[str, Any], label: str, errors: List[str], warnings: List[str], + check_url: bool = True) -> None: + """Integrity and body-form checks shared by Dialog, Attachment, Analysis and the + redacted_from / amended_from references (section 2.4).""" + if check_url and "url" in obj and "content_hash" not in obj: + # A MUST in section 2.4. Reported as a warning in 1.0.x so producers + # that only hold a carrier URL keep validating; an error from 1.1. + warnings.append( + f"{label} has a url but no content_hash (an external reference MUST have both; " + "this will be an error in vcon 1.1)." + ) + if "content_hash" in obj: + for problem in content_hash_problems(obj["content_hash"]): + errors.append(f"{label} has an invalid content_hash: {problem}.") + if obj.get("encoding") == "json" and isinstance(obj.get("body"), str): + body = obj["body"].strip() + if body[:1] in ("{", "["): + try: + json.loads(body) + except ValueError: + pass + else: + warnings.append( + f"{label} has encoding 'json' and a body that is a serialized JSON string; " + "the body should be the JSON value itself (section 2.3.2)." + ) + def mediatype_ok(mediatype: Any, known: List[str]) -> bool: """True if ``mediatype`` is acceptable for a Dialog. @@ -231,6 +288,7 @@ def validate_vcon_dict( errors.append("redacted_from is missing required field: type") if "url" in rf and "content_hash" not in rf: errors.append("redacted_from with url must include content_hash.") + _check_content(rf, "redacted_from", errors, warnings, check_url=False) af = vcon.get("amended_from") if "amended_from" in vcon: if not isinstance(af, dict): @@ -240,6 +298,7 @@ def validate_vcon_dict( errors.append("amended_from must include uuid, or an external reference (url).") if "url" in af and "content_hash" not in af: errors.append("amended_from with url must include content_hash.") + _check_content(af, "amended_from", errors, warnings, check_url=False) # --- extensions / critical ------------------------------------------- ext_listed = vcon.get("extensions", []) @@ -355,6 +414,10 @@ def validate_vcon_dict( f"Dialog at index {i} redacted_segments[{n}] requires start and end." ) + for i, dialog in enumerate(dialogs): + if isinstance(dialog, dict) and dialog.get("type") != "incomplete": + _check_content(dialog, f"Dialog at index {i}", errors, warnings) + # --- sessions --------------------------------------------------------- if (dialog_count or events) and not sessions: errors.append( @@ -417,6 +480,8 @@ def validate_vcon_dict( has_external = "url" in attachment and "content_hash" in attachment if not (has_inline or has_external or redacted): errors.append(f"Attachment at index {i} must include body+encoding or url+content_hash.") + _check_content(attachment, f"Attachment at index {i}", errors, warnings, + check_url=has_inline or redacted) if "encoding" in attachment and attachment["encoding"] not in CORE_ENCODINGS and not ext_listed: errors.append(f"Attachment at index {i} has invalid encoding: {attachment['encoding']}") if "body" in attachment and attachment["body"] != "" and "mediatype" not in attachment: @@ -460,6 +525,7 @@ def validate_vcon_dict( errors.append(f"Analysis at index {i} is missing required field: encoding") if "encoding" in analysis and analysis["encoding"] not in CORE_ENCODINGS and not ext_listed: errors.append(f"Analysis at index {i} has invalid encoding: {analysis['encoding']}") + _check_content(analysis, f"Analysis at index {i}", errors, warnings) for key, count, noun in ( ("dialog", dialog_count, "dialog"), ("sessions", session_count, "session"), diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index 615a033..c7e5c3c 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -11,8 +11,8 @@ from datetime import timezone from pydash import get as _get import base64 -from authlib.jose import JsonWebSignature -from authlib.jose.errors import BadSignatureError +from joserfc import jwk, jws +from joserfc.errors import BadSignatureError from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization import requests @@ -108,6 +108,31 @@ ) +def _jwk_key_type(alg: str) -> str: + """The JWK key type an algorithm needs (RS/PS: RSA, ES: EC, EdDSA: OKP).""" + if alg.startswith(("RS", "PS")): + return "RSA" + if alg.startswith("ES"): + return "EC" + return "OKP" + + +def _import_jwk(key: Any, alg: str, private: bool): + """Import a cryptography key object or PEM bytes/str as a joserfc key.""" + if hasattr(key, "private_bytes") and private: + key = key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + elif hasattr(key, "public_bytes") and not private: + key = key.public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + return jwk.import_key(key, _jwk_key_type(alg)) + + class AlgorithmNotPermittedError(ValueError): """A JWS used ``alg`` "none" (forbidden by core-05) or an unsupported algorithm.""" @@ -370,11 +395,9 @@ def __init__( if isinstance(vcon_dict["created_at"], datetime): vcon_dict["created_at"] = vcon_dict["created_at"].isoformat() logger.debug("Converted datetime created_at to ISO format") - elif isinstance(vcon_dict["created_at"], str): - vcon_dict["created_at"] = parser.parse( - vcon_dict["created_at"] - ).isoformat() - logger.debug("Parsed string created_at to ISO format") + # A string is kept exactly as written: rewriting it would change + # the document (and break a signature over it). An unparseable + # value is left for is_valid() to report. else: vcon_dict["created_at"] = datetime.now(timezone.utc).isoformat() logger.debug("Set default created_at timestamp") @@ -636,6 +659,8 @@ def tags(self) -> Optional[Dict[str, Any]]: Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> vcon.add_tag("category", "meeting") >>> tags = vcon.tags >>> print(tags["body"]) # Prints ["category:meeting"] @@ -660,6 +685,8 @@ def get_tag(self, tag_name: str) -> Optional[str]: Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> vcon.add_tag("category", "meeting") >>> value = vcon.get_tag("category") >>> print(value) # Prints "meeting" @@ -729,19 +756,30 @@ def _resolve_attachment_scope( "(add a Session first with add_session() if the vCon has none)." ) - def add_tag(self, tag_name: str, tag_value: str) -> None: + def add_tag(self, tag_name: str, tag_value: str, party: Optional[int] = None) -> None: """ Add a tag to the vCon. This method adds a tag with the specified name and value to the vCon's tags attachment. If no tags attachment exists, it creates one. + Core-05 requires the attachment's ``party`` to be a valid party index + (the party that adds the tags). It defaults to 0. On a vCon with no + parties this still writes party 0 but warns (DeprecationWarning), + because the result fails ``is_valid()``; from vcon 1.1 it will raise. + Args: tag_name: The name of the tag tag_value: The value to associate with the tag + party: Party index for a new tags attachment (default 0) + + Raises: + ValueError: If ``party`` is given (or the vCon has parties) and it + is not a valid party index Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Acme Corp")) >>> vcon.add_tag("category", "meeting") >>> vcon.add_tag("priority", "high") """ @@ -749,16 +787,35 @@ def add_tag(self, tag_name: str, tag_value: str) -> None: tags_attachment = self.find_attachment_by_purpose("tags") if not tags_attachment: logger.debug("Creating new tags attachment") + n_parties = len(self.vcon_dict.get("parties") or []) + if party is None and n_parties == 0: + # Kept for compatibility: the result fails is_valid() (party 0 + # does not exist). Raises ValueError from vcon 1.1. + warnings.warn( + "add_tag() on a vCon with no parties writes party 0, which does not exist, " + "so the vCon fails is_valid(). Add the party that adds the tags first. " + "This will raise ValueError in vcon 1.1.", + DeprecationWarning, + stacklevel=2, + ) + party = 0 + else: + party = 0 if party is None else party + if not (isinstance(party, int) and not isinstance(party, bool) and 0 <= party < n_parties): + raise ValueError( + f"add_tag() needs a valid party index for the tags attachment (core-05 section 4.6); " + f"got {party!r} but the vCon has {n_parties} parties." + ) tags_attachment = { "purpose": "tags", "body": [], "encoding": "json", "mediatype": "application/json", "start": self.vcon_dict.get("created_at"), - "party": 0, + "party": party, } tags_attachment.update(self._resolve_attachment_scope(whole_vcon=True)) - self.vcon_dict["attachments"].append(tags_attachment) + self.vcon_dict.setdefault("attachments", []).append(tags_attachment) else: # Normalize a legacy (pre-0.10.0 / -02 convention) JSON-string # body to the -04 list-valued body in place, preserving @@ -906,6 +963,8 @@ def add_lawful_basis_attachment( Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> vcon.add_lawful_basis_attachment( ... lawful_basis="consent", ... expiration="2026-01-01T00:00:00Z", @@ -949,7 +1008,7 @@ def add_lawful_basis_attachment( attachment.setdefault("mediatype", "application/json") attachment.setdefault("start", self.vcon_dict.get("created_at")) - self.vcon_dict["attachments"].append(attachment) + self.vcon_dict.setdefault("attachments", []).append(attachment) # Add extension to extensions list if not already present if "lawful_basis" not in self.get_extensions(): @@ -973,6 +1032,9 @@ def add_wtf_transcription_attachment( """ Add a WTF transcription attachment to the vCon. + Deprecated: draft-howe-vcon-wtf-extension stores transcriptions as + analysis (section 6.1). Use :meth:`add_wtf_transcription_analysis`. + Scoped by ``dialog_index`` and/or ``session_index`` as given; with neither, the only Session when the vCon has exactly one, else ``ValueError`` (see ``add_attachment``). @@ -988,6 +1050,8 @@ def add_wtf_transcription_attachment( Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> vcon.add_wtf_transcription_attachment( ... transcript={"text": "Hello world", "language": "en", "duration": 2.0, "confidence": 0.95}, ... segments=[{"id": 0, "start": 0.0, "end": 2.0, "text": "Hello world", "confidence": 0.95}], @@ -995,6 +1059,12 @@ def add_wtf_transcription_attachment( ... "provider": "whisper", "model": "whisper-1"} ... ) """ + warnings.warn( + "add_wtf_transcription_attachment() is deprecated: draft-howe-vcon-wtf-extension " + "stores transcriptions as analysis. Use add_wtf_transcription_analysis().", + DeprecationWarning, + stacklevel=2, + ) if not EXTENSIONS_AVAILABLE: raise RuntimeError("Extensions not available") @@ -1018,7 +1088,7 @@ def add_wtf_transcription_attachment( attachment.setdefault("mediatype", "application/json") attachment.setdefault("start", self.vcon_dict.get("created_at")) - self.vcon_dict["attachments"].append(attachment) + self.vcon_dict.setdefault("attachments", []).append(attachment) # Add extension to extensions list if not already present if "wtf_transcription" not in self.get_extensions(): @@ -1043,10 +1113,10 @@ def add_wtf_transcription_analysis( """ Add a WTF transcription as an analysis entry (vs. an attachment). - Use ``add_wtf_transcription_attachment`` for canonical placement - (matches the speckit example, attachments[]). Use this method if your - pipeline treats transcripts as derived analysis output and prefers - analysis[] placement. + This is the placement draft-howe-vcon-wtf-extension requires + (section 6.1: transcription results MUST be stored as analysis). + ``add_wtf_transcription_attachment`` writes to attachments[] and is + deprecated. Emits the analysis entry defined by draft-howe-vcon-wtf-extension (section 5.3): ``type="wtf_transcription"``, ``vendor`` and ``product`` @@ -1235,6 +1305,8 @@ def decoded_body(entry: Optional[Dict[str, Any]]) -> Any: Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> vcon.add_tag("category", "meeting") >>> Vcon.decoded_body(vcon.tags) # ["category:meeting"] """ @@ -1255,12 +1327,14 @@ def find_attachment_by_purpose(self, purpose: str) -> Optional[Dict[str, Any]]: Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> vcon.add_attachment("metadata", {"version": "1.0"}) >>> metadata = vcon.find_attachment_by_purpose("metadata") """ logger.debug(f"Searching for attachment of purpose: {purpose}") attachment = next( - (a for a in self.vcon_dict["attachments"] if a["purpose"] == purpose), None + (a for a in self.vcon_dict.get("attachments") or [] if a.get("purpose") == purpose), None ) if attachment: logger.debug(f"Found attachment of purpose: {purpose}") @@ -1314,6 +1388,8 @@ def add_attachment( Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> attachment = vcon.add_attachment("metadata", {"version": "1.0"}, "json") >>> print(attachment.purpose) # Prints "metadata" """ @@ -1345,7 +1421,7 @@ def add_attachment( # Process attachment dict according to property handling mode processed_attachment = self._process_properties(attachment_dict, _ALLOWED_ATTACHMENT_PROPERTIES) - self.vcon_dict["attachments"].append(processed_attachment) + self.vcon_dict.setdefault("attachments", []).append(processed_attachment) logger.info(f"Added new attachment of purpose {purpose}") return attachment @@ -1399,7 +1475,7 @@ def add_image( attachment.party = party attachment.dialog = dialog attachment.session = session - self.vcon_dict["attachments"].append(attachment.to_dict()) + self.vcon_dict.setdefault("attachments", []).append(attachment.to_dict()) logger.info(f"Added new image attachment of purpose {purpose}") return attachment @@ -1423,7 +1499,7 @@ def find_analysis_by_type(self, type: str) -> Optional[Dict[str, Any]]: """ logger.debug(f"Searching for analysis of type: {type}") analysis = next( - (a for a in self.vcon_dict["analysis"] if a["type"] == type), None + (a for a in self.vcon_dict.get("analysis") or [] if a.get("type") == type), None ) if analysis: logger.debug(f"Found analysis of type: {type}") @@ -1553,7 +1629,7 @@ def add_analysis( # Process analysis dict according to property handling mode processed_analysis = self._process_properties(analysis, _ALLOWED_ANALYSIS_PROPERTIES) - self.vcon_dict["analysis"].append(processed_analysis) + self.vcon_dict.setdefault("analysis", []).append(processed_analysis) logger.info(f"Added analysis of type {type} from vendor {vendor}") def add_party(self, party: Party) -> None: @@ -1576,7 +1652,7 @@ def add_party(self, party: Party) -> None: party_dict = party.to_dict() processed_party = self._process_properties(party_dict, _ALLOWED_PARTY_PROPERTIES) - self.vcon_dict["parties"].append(processed_party) + self.vcon_dict.setdefault("parties", []).append(processed_party) logger.info("Added party") @@ -1604,7 +1680,7 @@ def find_party_index(self, by: str, val: str) -> Optional[int]: index = next( ( ind - for ind, party in enumerate(self.vcon_dict["parties"]) + for ind, party in enumerate(self.vcon_dict.get("parties") or []) if _get(party, by) == val ), None, @@ -1638,7 +1714,7 @@ def find_dialog(self, by: str, val: str) -> Optional[Dialog]: """ logger.debug(f"Searching for dialog with {by}={val}") dialog = next( - (dialog for dialog in self.vcon_dict["dialog"] if dialog and _get(dialog, by) == val), + (dialog for dialog in self.vcon_dict.get("dialog") or [] if dialog and _get(dialog, by) == val), None, ) if dialog: @@ -1660,7 +1736,7 @@ def find_dialogs_by_type(self, type: str) -> List[Dict[str, Any]]: >>> vcon = Vcon.build_new() >>> incomplete = vcon.find_dialogs_by_type("incomplete") """ - return [dialog for dialog in self.vcon_dict["dialog"] if dialog.get("type") == type] + return [dialog for dialog in self.vcon_dict.get("dialog") or [] if dialog.get("type") == type] def add_dialog(self, dialog: Dialog, session: Optional[int] = None) -> int: """ @@ -1697,7 +1773,7 @@ def add_dialog(self, dialog: Dialog, session: Optional[int] = None) -> int: if not isinstance(session, int) or not 0 <= session < len(sessions): raise ValueError(f"Invalid session index: {session}") - self.vcon_dict["dialog"].append(processed_dialog) + self.vcon_dict.setdefault("dialog", []).append(processed_dialog) index = len(self.vcon_dict["dialog"]) - 1 if session is not None: self.vcon_dict["sessions"][session].setdefault("dialog", []).append(index) @@ -1935,6 +2011,8 @@ def attachments(self) -> List[Dict[str, Any]]: Example: >>> vcon = Vcon.build_new() + >>> vcon.add_party(Party(name="Alice")) + >>> vcon.add_session() >>> vcon.add_attachment("metadata", {"version": "1.0"}) >>> attachments = vcon.attachments >>> print(attachments[0]["purpose"]) # Prints "metadata" @@ -2082,21 +2160,9 @@ def sign(self, private_key: Union[rsa.RSAPrivateKey, bytes], alg: str = "RS256") self._check_jws_alg(alg) try: payload = self.to_json() - jws = JsonWebSignature(algorithms=list(PERMITTED_JWS_ALGORITHMS)) protected = {"alg": alg, "typ": "JWS"} - - # Convert private key to PEM format if it's not already - if isinstance(private_key, rsa.RSAPrivateKey): - pem = private_key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.NoEncryption(), - ) - else: - pem = private_key - - signed = jws.serialize_compact(protected, payload, pem) - signed_str = signed.decode("utf-8") + key = _import_jwk(private_key, alg, private=True) + signed_str = jws.serialize_compact(protected, payload, key, algorithms=[alg]) header, payload, signature = signed_str.split(".") self.vcon_dict["signatures"] = [{"protected": header, "signature": signature}] @@ -2171,20 +2237,14 @@ def verify(self, public_key: Union[rsa.RSAPublicKey, bytes]) -> bool: logger.error("Cannot verify: no alg in the JWS protected header or header") return False + alg = declared[0] + if alg not in PERMITTED_JWS_ALGORITHMS: + logger.error(f"Cannot verify: JWS alg {alg!r} is not supported") + return False try: - jws = JsonWebSignature(algorithms=list(PERMITTED_JWS_ALGORITHMS)) signed_data = f"{self.vcon_dict['signatures'][0]['protected']}.{self.vcon_dict['payload']}.{self.vcon_dict['signatures'][0]['signature']}" - - # Convert public key to PEM format if it's not already - if isinstance(public_key, rsa.RSAPublicKey): - pem = public_key.public_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PublicFormat.SubjectPublicKeyInfo, - ) - else: - pem = public_key - - jws.deserialize_compact(signed_data, pem) + key = _import_jwk(public_key, alg, private=False) + jws.deserialize_compact(signed_data, key, algorithms=[alg]) logger.info("Successfully verified vCon signature") return True except BadSignatureError: @@ -2227,8 +2287,10 @@ def is_valid(self) -> Tuple[bool, List[str]]: Session exists when there are Dialogs or Events, that attachments have ``party`` and ``dialog`` or ``session``, that ``redacted_from`` and ``amended_from`` are exclusive, that ``extensions`` lists every extension - in use (and every ``critical`` entry), and that every - ``__REDACTED_REF_#`` has a ``redacted_strings`` entry. + in use (and every ``critical`` entry), that every + ``__REDACTED_REF_#`` has a ``redacted_strings`` entry, that every ``url`` + has a ``content_hash`` and every ``content_hash`` is well formed, and + the body of every ``lawful_basis`` attachment. SHOULD-level findings are not errors; see :meth:`get_validation_warnings`. @@ -2237,7 +2299,7 @@ def is_valid(self) -> Tuple[bool, List[str]]: is valid and False otherwise, and the second element is a list of error messages. """ logger.debug("Validating vCon") - errors, _warnings = validate_vcon_dict(self.vcon_dict, Dialog.MIME_TYPES) + errors, _warnings = self._validate_all() for error in errors: logger.error(error) if len(errors) == 0: @@ -2248,9 +2310,30 @@ def is_valid(self) -> Tuple[bool, List[str]]: def get_validation_warnings(self) -> List[str]: """SHOULD-level findings (for example SHOULD NOT parameters on Events).""" - _errors, warnings = validate_vcon_dict(self.vcon_dict, Dialog.MIME_TYPES) + _errors, warnings = self._validate_all() return warnings + def _validate_all(self) -> Tuple[List[str], List[str]]: + """Core rules plus the body of every lawful_basis attachment.""" + errors, warnings = validate_vcon_dict(self.vcon_dict, Dialog.MIME_TYPES) + if EXTENSIONS_AVAILABLE: + from .extensions.lawful_basis.validation import LawfulBasisValidator + validator = LawfulBasisValidator() + attachments = self.vcon_dict.get("attachments") + for i, attachment in enumerate(attachments if isinstance(attachments, list) else []): + if not isinstance(attachment, dict) or attachment.get("purpose") != "lawful_basis": + continue + if isinstance(self.vcon_dict.get("redacted_from"), dict) and "body" not in attachment: + continue + # Scope (party, dialog/session) is checked by the core rules above. + result = validator.validate_attachment(attachment) + errors.extend(f"Attachment at index {i} (lawful_basis): {e}" for e in result.errors) + warnings.extend( + f"Attachment at index {i} (lawful_basis): {w}" for w in result.warnings + if "no party" not in w and "no session" not in w + ) + return errors, warnings + @staticmethod def validate_file(file_path: str) -> tuple[bool, list[str]]: """ diff --git a/tests/test_core05_changes.py b/tests/test_core05_changes.py index 795fd72..3854bd8 100644 --- a/tests/test_core05_changes.py +++ b/tests/test_core05_changes.py @@ -45,7 +45,7 @@ def test_url_needs_content_hash(self): v = _base() v.vcon_dict["amended_from"] = {"url": "https://example.com/v.json"} assert any("content_hash" in e for e in v.is_valid()[1]) - v.vcon_dict["amended_from"] = {"url": "https://example.com/v.json", "content_hash": "sha512-abc"} + v.vcon_dict["amended_from"] = {"url": "https://example.com/v.json", "content_hash": "sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A"} assert v.is_valid()[0] def test_amended_from_needs_uuid_or_url(self): @@ -128,6 +128,7 @@ def test_no_placeholder_session_is_invented(self): def test_tags_describe_the_whole_vcon(self): v = Vcon.build_new() + v.add_party(Party(name="Acme")) v.add_tag("k", "v") assert v.sessions == [{}] assert v.vcon_dict["attachments"][0]["session"] == [0] @@ -136,6 +137,19 @@ def test_tags_describe_the_whole_vcon(self): w.add_tag("k", "v") assert w.vcon_dict["attachments"][0]["session"] == [0, 1] + def test_tags_need_a_party(self): + v = Vcon.build_new() + with pytest.warns(DeprecationWarning, match="no parties"): + v.add_tag("k", "v") + assert v.get_tag("k") == "v" + assert any("invalid party index" in e for e in v.is_valid()[1]) + w = _base() + with pytest.raises(ValueError): + w.add_tag("k", "v", party=7) + w.add_tag("k", "v", party=1) + assert w.vcon_dict["attachments"][0]["party"] == 1 + assert w.is_valid() == (True, []) + def test_attachment_class_has_session_and_no_dialog_default(self): a = Attachment("p", body="b", session=[0]) d = a.to_dict() @@ -177,7 +191,7 @@ def test_empty_dialog_is_valid_and_keeps_indices(self): def test_parties_may_contain_nulls_and_lists(self): v = _base() v.add_dialog( - Dialog(type="recording", start=T, parties=[[0, 1], None, 1], mediatype="audio/wav", url="https://e.com/a.wav", content_hash="sha512-x"), + Dialog(type="recording", start=T, parties=[[0, 1], None, 1], mediatype="audio/wav", url="https://e.com/a.wav", content_hash="sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A"), session=0, ) assert v.is_valid() == (True, []) @@ -218,7 +232,7 @@ def test_redacted_segments(self): v = _base() v.add_dialog( Dialog(type="recording", start=T, parties=[0], mediatype="audio/wav", url="https://e.com/a.wav", - content_hash="sha512-x", redacted_segments=[{"start": T, "end": "2026-01-01T00:00:05Z"}]), + content_hash="sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A", redacted_segments=[{"start": T, "end": "2026-01-01T00:00:05Z"}]), session=0, ) assert v.is_valid() == (True, []) @@ -286,7 +300,9 @@ class TestExtensionsEnforcement: def test_lawful_basis_in_use_must_be_listed(self): v = _base() v.vcon_dict["attachments"].append( - {"purpose": "lawful_basis", "start": T, "party": 0, "session": [0], "body": {}, "encoding": "json", "mediatype": "application/json"} + {"purpose": "lawful_basis", "start": T, "party": 0, "session": [0], "encoding": "json", "mediatype": "application/json", + "body": {"lawful_basis": "consent", "expiration": None, + "purpose_grants": [{"purpose": "recording", "granted": True, "granted_at": T}]}} ) valid, errors = v.is_valid() assert not valid @@ -418,7 +434,7 @@ class TestLegacyMediaDialogTypes: def test_constructor_normalizes_to_recording(self, kind): with pytest.warns(DeprecationWarning, match="not a core-05 type"): d = Dialog(type=kind, start=T, parties=[0], mediatype=f"{kind}/mp4" if kind == "video" else "audio/wav", - url="https://e.com/x", content_hash="sha512-x") + url="https://e.com/x", content_hash="sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A") assert d.to_dict()["type"] == "recording" def test_video_helpers_emit_recording(self): @@ -429,7 +445,7 @@ def test_video_helpers_emit_recording(self): def test_read_is_a_warning_not_an_error(self): v = _base() v.vcon_dict["dialog"].append({"type": "video", "start": T, "parties": [0], "mediatype": "video/mp4", - "url": "https://e.com/v.mp4", "content_hash": "sha512-x"}) + "url": "https://e.com/v.mp4", "content_hash": "sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A"}) v.vcon_dict["sessions"][0]["dialog"] = [0] assert v.is_valid() == (True, []) assert any("type 'video'" in w for w in v.get_validation_warnings()) diff --git a/tests/test_core05_examples.py b/tests/test_core05_examples.py index 85ea2df..9b738a1 100644 --- a/tests/test_core05_examples.py +++ b/tests/test_core05_examples.py @@ -86,7 +86,7 @@ def test_library_built_vcon_with_every_object_kind_validates(): vcon.vcon_dict["sessions"][0]["sessions"] = [{"session": 1, "type": "child", "description": "consult"}] vcon.add_dialog( Dialog(type="recording", start="2026-01-01T00:00:00Z", duration=60, parties=[[0], [1]], - mediatype="audio/wav", url="https://example.com/a.wav", content_hash="sha512-abc"), + mediatype="audio/wav", url="https://example.com/a.wav", content_hash="sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A"), session=0, ) vcon.add_dialog(Dialog(type="text", start="2026-01-01T00:00:10Z", parties=[1], body="hello", mediatype="text/plain", encoding="none"), session=1) diff --git a/tests/test_dialog.py b/tests/test_dialog.py index 9fbb800..e524333 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -4,6 +4,7 @@ compute_content_hash, parse_content_hash_algorithm, b64url_decode, + b64url_encode, ) import hashlib import base64 @@ -266,11 +267,12 @@ def test_valid_sha512_content_hash(self): # Add inline data dialog.add_inline_data("example_body", "example_filename", "text/plain") - # Check that the content hash is the spec-compliant sha512 form - expected_content_hash = compute_content_hash("example_body".encode()) + # A str body is base64url already; the hash is over the decoded content + expected_content_hash = compute_content_hash(b64url_decode("example_body")) assert expected_content_hash.startswith("sha512-") assert "=" not in dialog.content_hash # no base64 padding assert dialog.content_hash == expected_content_hash + assert dialog.verify_content_hash(dialog.content_hash) # Sets the encoding to "base64url" def test_encoding_base64url(self): @@ -928,10 +930,12 @@ def test_spec_example_hash_is_well_formed(): def test_add_inline_data_emits_sha512(): dialog = Dialog(type="text", start="2023-06-01T10:00:00Z", parties=[0]) - dialog.add_inline_data("body text", "note.txt", "text/plain") + dialog.add_inline_data(b"body text", "note.txt", "text/plain") + assert dialog.body == b64url_encode(b"body text") assert dialog.content_hash.startswith("sha512-") assert "=" not in dialog.content_hash assert dialog.content_hash == compute_content_hash(b"body text") + assert dialog.verify_content_hash(dialog.content_hash) def test_add_external_data_emits_sha512(mocker): diff --git a/tests/test_fixes_1_0_4.py b/tests/test_fixes_1_0_4.py new file mode 100644 index 0000000..9986d6c --- /dev/null +++ b/tests/test_fixes_1_0_4.py @@ -0,0 +1,181 @@ +"""Regression tests for the 1.0.4 fixes.""" + +import shutil +import subprocess +import sys + +import pytest +from cryptography.hazmat.primitives.asymmetric import ec, ed25519, rsa + +from vcon import Vcon, Session, compute_content_hash +from vcon.dialog import Dialog, b64url_encode +from vcon.party import Party +from vcon.validation import content_hash_problems + +T = "2026-01-01T00:00:00Z" +H = compute_content_hash(b"example content") + + +def _base(): + v = Vcon.build_new() + v.add_party(Party(name="Alice")) + v.add_session(Session(start=T, parties=[0])) + return v + + +def _recording(**kw): + return Dialog(type="recording", start=T, parties=[0], mediatype="audio/x-wav", **kw) + + +class TestContentHash: + def test_url_needs_content_hash(self): + v = _base() + v.add_dialog(_recording(url="https://example.com/a.wav"), session=0) + assert v.is_valid() == (True, []) # a warning in 1.0.x, an error from 1.1 + assert any("has a url but no content_hash" in w for w in v.get_validation_warnings()) + + def test_well_formed_hash_passes(self): + v = _base() + v.add_dialog(_recording(url="https://example.com/a.wav", content_hash=H), session=0) + assert v.is_valid() == (True, []) + + @pytest.mark.parametrize("bad", ["sha512-abc", "abc", "sha512-", "SHA512-x", "sha256-" + "A" * 44, 5, []]) + def test_malformed_hash_is_an_error(self, bad): + assert content_hash_problems(bad) + v = _base() + v.add_dialog(_recording(url="https://example.com/a.wav", content_hash=bad), session=0) + assert any("invalid content_hash" in e for e in v.is_valid()[1]) + + def test_hash_array_and_unknown_algorithm(self): + assert content_hash_problems([H, compute_content_hash(b"x", "sha256")]) == [] + assert content_hash_problems("blake3-abcdef") == [] + + def test_attachment_and_analysis_are_checked(self): + v = _base() + v.add_attachment("doc", url="https://example.com/d.pdf", party=0, session=0) + v.add_analysis(type="summary", vendor="v", url="https://example.com/s.json", + content_hash="sha512-x", sessions=0, body=None) + errors = v.is_valid()[1] + assert any(e.startswith("Attachment at index 0 must include") for e in errors) + assert any(e.startswith("Analysis at index 0 has an invalid content_hash") for e in errors) + + +def test_serialized_json_body_is_a_warning(): + def with_body(body): + v = _base() + v.vcon_dict["analysis"].append( + {"type": "summary", "vendor": "v", "body": body, "encoding": "json", "sessions": 0}) + return v + v = with_body('{"a": 1}') + assert v.is_valid() == (True, []) + assert any("serialized JSON string" in w for w in v.get_validation_warnings()) + w = with_body("plain words") # a JSON string value is allowed + assert not any("serialized JSON string" in x for x in w.get_validation_warnings()) + + +class TestLawfulBasisBody: + def _attach(self, body): + v = _base() + v.add_extension("lawful_basis") + v.vcon_dict["attachments"].append({ + "purpose": "lawful_basis", "start": T, "party": 0, "session": [0], + "encoding": "json", "mediatype": "application/json", "body": body, + }) + return v + + def test_missing_body_fields_are_errors(self): + ok, errors = self._attach({"lawful_basis": "consent"}).is_valid() + assert not ok + assert any("(lawful_basis): Missing required field: purpose_grants" in e for e in errors) + + def test_complete_body_is_valid(self): + v = self._attach({"lawful_basis": "consent", "expiration": None, + "purpose_grants": [{"purpose": "recording", "granted": True, "granted_at": T}]}) + assert v.is_valid() == (True, []) + + def test_unknown_proof_type_is_a_warning(self): + v = self._attach({ + "lawful_basis": "consent", "expiration": None, + "purpose_grants": [{"purpose": "recording", "granted": True, "granted_at": T}], + "proof_mechanisms": [{"proof_type": "biometric_hold", "timestamp": T, "proof_data": {}}], + }) + assert v.is_valid() == (True, []) + assert any("biometric_hold" in w for w in v.get_validation_warnings()) + + def test_library_helper_output_is_valid(self): + v = _base() + v.add_lawful_basis_attachment( + lawful_basis="consent", expiration="2030-01-01T00:00:00Z", + purpose_grants=[{"purpose": "recording", "granted": True, "granted_at": T}], + party_index=0, session_index=0, + ) + assert v.is_valid() == (True, []) + + +def test_add_inline_data_accepts_bytes(): + d = Dialog(type="recording", start=T, parties=[0]) + d.add_inline_data(b"\x00\x01raw", "a.wav", "audio/x-wav") + assert d.body == b64url_encode(b"\x00\x01raw") + assert d.content_hash == compute_content_hash(b"\x00\x01raw") + assert d.verify_content_hash(d.content_hash) + + +def test_wtf_attachment_helper_is_deprecated(): + v = _base() + with pytest.warns(DeprecationWarning, match="add_wtf_transcription_analysis"): + v.add_wtf_transcription_attachment( + transcript={"text": "hi", "language": "en", "duration": 1.0, "confidence": 0.9}, + segments=[{"id": 0, "start": 0.0, "end": 1.0, "text": "hi", "confidence": 0.9}], + metadata={"created_at": T, "processed_at": T, "provider": "whisper", "model": "whisper-1"}, + party_index=0, session_index=0, + ) + + +@pytest.mark.parametrize("alg,key", [ + ("RS256", rsa.generate_private_key(public_exponent=65537, key_size=2048)), + ("PS512", rsa.generate_private_key(public_exponent=65537, key_size=2048)), + ("ES256", ec.generate_private_key(ec.SECP256R1())), + ("EdDSA", ed25519.Ed25519PrivateKey.generate()), +]) +def test_sign_and_verify_with_key_objects(alg, key): + v = _base() + v.sign(key, alg=alg) + assert v.verify(key.public_key()) + other = type(key) is ed25519.Ed25519PrivateKey and ed25519.Ed25519PrivateKey.generate() + if other: + assert not v.verify(other.public_key()) + + +def test_import_does_not_warn(): + out = subprocess.run([sys.executable, "-W", "error", "-c", "import vcon"], + capture_output=True, text=True) + assert out.returncode == 0, out.stderr + + +class TestVideoHelpers: + def test_missing_ffmpeg_python_has_a_clear_error(self, monkeypatch): + import vcon.dialog as dialog_module + monkeypatch.setitem(sys.modules, "ffmpeg", None) + with pytest.raises(ImportError, match=r"vcon\[video\]"): + dialog_module._import_ffmpeg() + + def test_generate_thumbnail_dispatches(self, monkeypatch): + d = Dialog(type="recording", start=T, parties=[0], mediatype="video/mp4") + monkeypatch.setattr(Dialog, "generate_video_thumbnail", lambda self, *a, **k: b"video") + monkeypatch.setattr(Dialog, "generate_image_thumbnail", lambda self, *a, **k: "image") + assert d.generate_thumbnail(timestamp=1.0) == b"video" + d.mediatype = "image/jpeg" + assert d.generate_thumbnail() == "image" + + @pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="needs the ffmpeg binary") + def test_real_video(self, tmp_path): + pytest.importorskip("ffmpeg").probe # ffmpeg-python, not the empty "ffmpeg" package + clip = tmp_path / "clip.mp4" + subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", + "testsrc=duration=1:size=160x120:rate=10", "-pix_fmt", "yuv420p", str(clip)], + check=True) + d = Dialog(type="recording", start=T, parties=[0]) + d.add_video_data(clip.read_bytes(), filename="clip.mp4") + meta = d.extract_video_metadata() + assert (meta["width"], meta["height"]) == (160, 120) + assert d.generate_thumbnail(timestamp=0.5)[:3] == b"\xff\xd8\xff" diff --git a/tests/test_fixes_1_0_3.py b/tests/test_fixes_1_0_x.py similarity index 72% rename from tests/test_fixes_1_0_3.py rename to tests/test_fixes_1_0_x.py index 7889237..bab11c1 100644 --- a/tests/test_fixes_1_0_3.py +++ b/tests/test_fixes_1_0_x.py @@ -103,3 +103,30 @@ def test_import_does_not_configure_root_logging(): out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True, check=True) assert out.stdout.split() == [str(logging.WARNING), "0"] + + +def test_vcon_without_optional_arrays_accepts_writes_and_reads(): + """A loaded vCon may omit analysis, attachments, parties and dialog (all optional).""" + v = Vcon({"vcon": "0.5.0", "uuid": "01928e10-193e-8231-b9a2-279e0d16bc46", + "created_at": "2024-01-01T00:00:00Z"}) + for key in ("analysis", "parties", "dialog"): + v.vcon_dict.pop(key, None) + assert v.find_analysis_by_type("x") is None + assert v.find_dialogs_by_type("text") == [] + assert v.find_party_index("name", "x") is None + v.add_party(Party(name="A")) + s = v.add_session(Session(start="2024-01-01T00:00:00Z", parties=[0])) + v.add_dialog(Dialog(type="text", start="2024-01-01T00:00:00Z", parties=[0], body="hi", + encoding="none", mediatype="text/plain"), session=s) + v.add_analysis(type="summary", vendor="v", body={"s": 1}, encoding="json", sessions=s) + assert v.find_analysis_by_type("summary")["body"] == {"s": 1} + assert v.is_valid() == (True, []) + + +def test_created_at_is_kept_as_written(): + raw = "2026-10-24T01:29:10.590Z" + v = Vcon({"vcon": "0.5.0", "uuid": "01928e10-193e-8231-b9a2-279e0d16bc46", "created_at": raw}) + assert v.created_at == raw + bad = Vcon({"vcon": "0.5.0", "uuid": "01928e10-193e-8231-b9a2-279e0d16bc46", "created_at": "{{now}}"}) + ok, errors = bad.is_valid() + assert not ok and any("created_at" in e for e in errors) diff --git a/tests/test_migration_0_4_0.py b/tests/test_migration_0_4_0.py index f2c323a..6f89aac 100644 --- a/tests/test_migration_0_4_0.py +++ b/tests/test_migration_0_4_0.py @@ -44,7 +44,7 @@ def v04(**kw): def rec(**kw): d = {"type": "recording", "start": T0, "duration": 10, "parties": [0, 1], - "mediatype": "audio/x-wav", "url": "https://e.com/a.wav", "content_hash": "sha512-x"} + "mediatype": "audio/x-wav", "url": "https://e.com/a.wav", "content_hash": "sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A"} d.update(kw) return d @@ -578,7 +578,7 @@ def test_every_reference_in_the_result_resolves(self): class TestT11T12Renames: def test_redacted_to_redacted_from(self): - r = {"uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46", "type": "PII Redaction", "url": "https://e.com/u", "content_hash": "sha512-x"} + r = {"uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46", "type": "PII Redaction", "url": "https://e.com/u", "content_hash": "sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A"} out, _ = migrate(v04(redacted=r)) assert out["redacted_from"] == r and "redacted" not in out diff --git a/tests/test_vcon.py b/tests/test_vcon.py index d29d835..e657392 100644 --- a/tests/test_vcon.py +++ b/tests/test_vcon.py @@ -36,7 +36,7 @@ '"meta":{"role":"customer"}}],"dialog":[{"type":"recording",' '"start":"2024-10-20T15:02:54.888840","duration":52.68,"parties":[0,1],' '"mediatype":"audio/x-wav","filename":"bb1489ad-0b45-47a0-bca6-de124da39a3a.mp3",' - '"body":"","encoding":"base64url","content_hash":"JBzeZEPDNVm8iPEeout0UK-B2Fp6JzeQxqy70SvM_MU=",' + '"body":"","encoding":"base64url","content_hash":"sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A",' '"disposition":"ANSWERED"}],"attachments":[{"purpose":"generation_info","body":' '{"agent_name":"David Scott","customer_name":"Diane Allen",' '"business":"Auto Repair Shop","problem":"billing","emotion":"disappointed",' @@ -208,6 +208,7 @@ def test_build_new() -> None: def test_tags() -> None: vcon = Vcon.build_new() + vcon.add_party(Party(name="Acme")) assert vcon.tags is None vcon.add_tag("test_tag", "test_value") @@ -287,6 +288,7 @@ def test_uuid8_domain_name() -> None: def test_get_tag() -> None: vcon = Vcon.build_new() + vcon.add_party(Party(name="Acme")) vcon.add_tag("test_tag", "test_value") assert vcon.get_tag("test_tag") == "test_value" assert vcon.get_tag("nonexistent_tag") is None @@ -371,7 +373,7 @@ def test_properties() -> None: "filename": "bb1489ad-0b45-47a0-bca6-de124da39a3a.mp3", "body": "", "encoding": "base64url", - "content_hash": "JBzeZEPDNVm8iPEeout0UK-B2Fp6JzeQxqy70SvM_MU=", + "content_hash": "sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A", "disposition": "ANSWERED", } @@ -442,6 +444,7 @@ def test_find_dialog() -> None: def test_add_special_character_tag() -> None: # Given vcon = Vcon.build_new() + vcon.add_party(Party(name="Acme")) # When vcon.add_tag("special_tag!@#", "special_value") diff --git a/tests/test_wtf_extension.py b/tests/test_wtf_extension.py index 64da630..d04700d 100644 --- a/tests/test_wtf_extension.py +++ b/tests/test_wtf_extension.py @@ -652,7 +652,7 @@ def test_add_wtf_transcription_analysis_session_scope_is_valid(self): 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) + content_hash="sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A"), session=s) vcon.add_wtf_transcription_analysis(**self._payload(), session_index=s) entry = vcon.vcon_dict["analysis"][0] assert entry["sessions"] in (0, [0])