# Tutorials This section offers detailed, step-by-step tutorials that guide you through using TransparentMeta to embed cryptographically signed metadata into audio files, verify their authenticity, and ensure compliance with AI transparency regulations. Each tutorial includes in-depth explanations of what happens under the hood, with frequent Python code snippets and commentary to help you fully understand and master the process. --- ## Video tutorials If you prefer learning by watching, our video tutorials on YouTube provide a comprehensive walkthrough of key TransparentMeta features. These videos cover most of the topics presented in this section and offer practical, hands-on demonstrations of how to integrate and use TransparentMeta effectively. Watch the full video series here: [TransparentMeta YouTube Playlist](https://www.youtube.com/playlist?list=PL-a9rWjvfqdRqYS1E6oJlC39TOz_N3yDJ) --- ## Generating a cryptographic key pair To securely embed transparency metadata into audio files, TransparentMeta relies on **cryptographic signing**. This requires generating a pair of cryptographic keys: - A **private key** used to sign metadata before embedding it into audio files. - A corresponding **public key** used to verify the authenticity of the signed metadata. ### Why is this necessary? The cryptographic signature guarantees that the metadata has not been tampered with and confirms it was generated by a trusted party holding the private key. Without this, anyone could alter or fake transparency metadata, defeating the purpose of transparency and compliance. ### Key management best practices - The **private key must be kept secret and stored securely**, as it is used to sign all metadata. Loss or compromise of the private key could allow malicious actors to generate forged metadata. - The **public key is meant to be shared** with anyone who needs to verify metadata authenticity, such as platforms, regulators, or consumers. ### Centralized verification service For most users of TransparentMeta, the primary task is **writing** metadata (i.e., signing with the private key). Verification of metadata is often done downstream by platforms or services. To simplify this process, Transparent Audio plans to provide a **centralized verification service**. In this future model: - Transparent Audio securely manages private keys for clients. - Platforms query this central service to verify metadata authenticity rather than contacting each metadata generator individually. - This approach ensures higher security and operational efficiency, with a centralized source of truth for metadata verification. That said, users retain the freedom to generate and manage their own private/public key pairs if preferred. ### Let's generate a key pair First, import the necessary functions from TransparentMeta: ```python import logging from examples.config import private_key_path, public_key_path from transparentmeta.crypto.key_management import ( generate_key_pair, save_private_key_to_pem_file, save_public_key_to_pem_file, ) from transparentmeta.logger_config import configure_logging ``` Next, generate a new Ed25519 private/public key pair. This key pair will be used to sign and verify metadata. ```python private_key, public_key = generate_key_pair() ``` `generate_key_pair()` under the hood uses the `cryptography` library. Save the private key to a PEM file. This key must be stored securely, as it is used to cryptographically sign your metadata. ```python save_private_key_to_pem_file(private_key, private_key_path) ``` Save the public key to a PEM file. You can distribute this key to platforms or services that will verify your metadata signatures. ```python save_public_key_to_pem_file(public_key, public_key_path) ``` After running the above code, your key files will be saved at the configured paths. --- ## Writing metadata to an audio file This tutorial demonstrates how to embed structured, cryptographically signed metadata into an audio file using TransparentMeta. ### Step 1: Prepare the environment and load the private key First, import necessary modules and configure logging to ensure detailed traceability during the metadata embedding process. Then, load your Ed25519 private key from a PEM file. This private key will be used to cryptographically sign the metadata. ```python from datetime import datetime, timezone from pathlib import Path from transparentmeta.crypto.key_management import load_private_key_from_pem_file from transparentmeta.entity.metadata import AIUsageLevel from transparentmeta.sdk import build_transparent_metadata_writer private_key = load_private_key_from_pem_file(Path("path/to/your/private_key.pem")) ``` ### Step 2: Build the TransparentMetadataWriter instance Use the loaded private key to instantiate a `TransparentMetadataWriter`. This provides the high-level interface for signing and embedding metadata into audio files. ```python transparent_metadata_writer = build_transparent_metadata_writer(private_key) ``` ### Step 3: Define your metadata dictionary Create a dictionary with all relevant metadata fields you want to embed. Fields include: - Company or entity generating the metadata - Model version or AI system version - Timestamp of metadata creation (use UTC time) - AI usage level from `AIUsageLevel` enum (e.g., AI-assisted) - Content and user identifiers - Private key ID (for key management) - Optional additional info, such as attribution ```python metadata = { "company": "Transparent Audio", "model": "v2.1", "created_at": datetime.now(timezone.utc), "ai_usage_level": AIUsageLevel.AI_ASSISTED, "content_id": "12345", "user_id": "user_67890", "private_key_id": "dummy_private_key_id", "additional_info": { "attribution": { "lyrics": "John Doe", "composer": "Jane Smith", "singer": "HAL 9000", } }, } ``` ### Step 4: Write the signed metadata to the audio file Use the `write` method of the metadata writer to embed the signed metadata into the audio file at the path `test_audio_path`. ```python transparent_metadata_writer.write(Path("path/to/my/audio/file"), metadata) ``` This operation modifies the audio file by embedding your metadata and its cryptographic signature in two ID3v2 custom tags called `transparency` and `signature`. The method validates the metadata, creates the signature, and writes both securely into the audio file. It's very high-level, so you don't need to care about the underlying details of how the metadata is signed or stored. ### When writing fails The writing process can fail for several reasons, such as: - The audio file does not exist or is not accessible. - The metadata dictionary is invalid or incomplete. - The audio file is not in a supported format. - The audio file is read-only or corrupted. In these cases, TransparentMeta raises custom exceptions with detailed error messages, and stops execution. You can catch and handle these exceptions as needed to ensure robust error management. --- ## Reading metadata from an audio file This tutorial explains how to extract and verify transparency metadata embedded in an audio file using TransparentMeta. Verification uses a public Ed25519 key corresponding to the private key that signed the metadata. ### Step 1: Prepare the environment and load the public key Import the necessary modules. Then load your Ed25519 public key from a PEM file. This key will be used to verify the metadata signature. Remember this key must match the private key used to sign the metadata, otherwise verification will fail. ```python from pathlib import Path from transparentmeta.crypto.key_management import load_public_key_from_pem_file from transparentmeta.sdk import build_transparent_metadata_reader public_key = load_public_key_from_pem_file(Path("path/to/your/public_key.pem")) ``` ### Step 2: Build the TransparentMetadataReader instance Create a `TransparentMetadataReader` using the loaded public key. This instance handles reading and verifying metadata from audio files. `TransparentMetadataReader` provides a high-level interface for reading and verifying metadata. ```python transparent_metadata_reader = build_transparent_metadata_reader(public_key) ``` ### Step 3: Read and verify metadata from the audio file Call the `read` method on your `TransparentMetadataReader`, passing the path of the audio file. This returns a `ReadResult` object that contains: - The extracted metadata (if present and readable) - Verification status of the signature (`True` if success, `False` if not) - Any errors encountered during reading or verification ```python read_result = transparent_metadata_reader.read(Path("path/to/my/audio/file")) print(read_result) ``` The `read` method performs the following steps under the hood: 1. Reads the custom ID3v2 tags `transparency` and `signature` from the audio file. 2. Verifies the signature against the metadata using the public key. 3. Returns a `ReadResult` object containing the metadata and verification status. Again, you don't need to worry about the low-level details of how the metadata is signed or verified. The `TransparentMetadataReader` handles all the complexity for you. ### Understanding the `ReadResult` object `ReadResult` encapsulates all relevant information about the reading and verification operation without raising exceptions on verification failure. It has the following attributes: - `metadata`: The extracted `Metadata` object or `None` if missing or unreadable. - `is_success`: Boolean flag indicating if the metadata reading and verification process completed successfully (note: a completed process may still have a verification failure). - `error`: Optional error message if reading failed (e.g., file not found). Signature verification result is reflected within the metadata validity, but verification failure does not raise an exception. This design allows downstream consumers to inspect and handle verification failures gracefully. ### When verification fails Verification can fail due to several reasons: - Metadata doesn't exist: No metadata embedded in the audio file. - Metadata or signature tampered: The cryptographic signature does not match the metadata, indicating potential corruption or manipulation of the metadata or signature in the audio file. - Unsupported or corrupted file: Audio file cannot be parsed properly. In all these cases, the ReadResult provides detailed error information to guide handling. --- ## Using the custom TransparentMeta logger TransparentMeta includes a built-in logger to help you monitor internal SDK operations. Activating this logger provides insight into what the library is doing under the hood, which is invaluable for debugging and auditing your metadata processing. ### Why use the TransparentMeta logger? - It reports key events like component initialization, metadata read/write success, and verification results. - It can help diagnose problems by showing detailed traces of internal decisions, serialized data formats, and signature verification steps. - Enables you to track the SDK’s behavior in production or during development without modifying library code. ### Logging levels - INFO (default): Shows high-level messages useful for general monitoring — e.g., confirming operations succeeded, components started correctly. - DEBUG: Shows detailed trace information — perfect for debugging or gaining deep insight into the signing, writing, and verification process. ### How to enable TransparentMeta logging If you don’t already have your own logging setup, simply call `configure_logging()` at the start of your application to enable TransparentMeta’s default logger at the INFO level: ```python from transparentmeta.logger_config import configure_logging configure_logging() ``` To enable full debug-level tracing, pass the level argument: ```python import logging from transparentmeta.logger_config import configure_logging configure_logging(level=logging.DEBUG) ``` ### Important notes about the logger - If your application already configures logging, you **do not need to call** `configure_logging()`. TransparentMeta logs will propagate through the root logger and be handled by your existing setup. - Use the logger to quickly verify your integration is working. For example, loggers in the `transparentmeta.sdk.factory` namespace will output relevant messages when the SDK initializes or performs key operations.