msclap (Contrastive Language-Audio Pretraining)

repository·main·Indexed 20 days ago

https://github.com/microsoft/clap

A model for learning acoustic concepts from natural language supervision to enable zero-shot inference for audio classification, retrieval, and captioning. The library provides the CLAP class for extracting text and audio embeddings, computing similarity, and generating audio captions using the 'clapcap' version. Supported model versions include '2022', '2023', and 'clapcap'.

Tokens
1.9K
Snippets
9
Records
10
Agent score
72%

What's inside msclap

  1. Install msclap

    main

    To use CLAP, ensure you have Python 3.8 or higher installed (Python 3.11 is recommended). You can install the package via PyPI or directly from the GitHub source.

    Install via PyPI

    pip install msclap

    Install latest git source

    pip install git+https://github.com/microsoft/CLAP.git
    pip install msclap
  2. Perform Zero-Shot Classification and Retrieval with CLAP

    main

    Use the CLAP class to perform zero-shot tasks such as classification and retrieval. You can choose between model versions '2022' or '2023'. If model_fp is not specified, the weights will be downloaded automatically.

    Workflow:

    1. Initialize CLAP with a specific version.
    2. Extract text embeddings using get_text_embeddings.
    3. Extract audio embeddings using get_audio_embeddings.
    4. Compute similarity using compute_similarity to find matches between audio and text.
    from msclap import CLAP
    
    # Load model (Choose between versions '2022' or '2023')
    # The model weight will be downloaded automatically if `model_fp` is not specified
    clap_model = CLAP(version = '2023', use_cuda=False)
    
    # Extract text embeddings
    text_embeddings = clap_model.get_text_embeddings(class_labels=['dog', 'barking'])
    
    # Extract audio embeddings
    audio_embeddings = clap_model.get_audio_embeddings(file_paths=['path/to/audio.wav'])
    
    # Compute similarity between audio and text embeddings 
    similarities = clap_model.compute_similarity(audio_embeddings, text_embeddings)
  3. Generate audio captions with clapcap

    main

    For audio captioning tasks, use the clapcap version of the model. This version uses the 2023 encoders specifically optimized for generating natural language descriptions of audio files.

    Workflow:

    1. Initialize CLAP with version='clapcap'.
    2. Use generate_caption with a list of audio file paths.
    from msclap import CLAP
    
    # Load model (Choose version 'clapcap')
    clap_model = CLAP(version = 'clapcap', use_cuda=False)
    
    # Generate audio captions
    captions = clap_model.generate_caption(file_paths=['path/to/audio.wav'])
  4. CLAP Class API Reference

    main

    The CLAP class is the primary interface for the library.

    Initialization

    CLAP(version: str, use_cuda: bool = False, model_fp: str = None)

    • version: Model version to use. Options: '2022', '2023', or 'clapcap'.
    • use_cuda: Whether to use CUDA for acceleration.
    • model_fp: Path to model weights. If not provided, weights are downloaded automatically.

    Methods

    • get_text_embeddings(class_labels: List[str]): Returns embeddings for the provided list of text labels.
    • get_audio_embeddings(file_paths: List[str]): Returns embeddings for the provided list of audio file paths.
    • compute_similarity(audio_embeddings, text_embeddings): Computes the similarity scores between audio and text embeddings.
    • generate_caption(file_paths: List[str]): (Available in 'clapcap' version) Generates text captions for the provided audio files.
  5. Extract audio embeddings

    main

    Use get_audio_embeddings to convert a list of audio file paths into their corresponding audio embeddings.

    Input: A list of file paths (strings). Output: A tensor of audio embeddings.

    Note: You can also use get_audio_embeddings_per_batch to process large datasets in chunks to manage memory.

    # audio_files is a list of paths
    audio_embeddings = wrapper.get_audio_embeddings(audio_files=['path/to/audio1.wav', 'path/to/audio2.wav'])
  6. Initialize the CLAPWrapper class

    main

    The CLAPWrapper class is the primary interface for the CLAP model, supporting zero-shot classification, retrieval, and embedding extraction. You can initialize it by specifying a model file path and a version. If model_fp is not provided, the weights will be automatically downloaded from the microsoft/msclap repository on Hugging Face.

    Supported versions:

    • '2022'
    • '2023'
    • 'clapcap' (used for caption generation tasks)
    from msclap import CLAPWrapper
    from pathlib import Path
    
    # Initialize with a specific version (e.g., '2023')
    # If model_fp is None, it downloads automatically
    wrapper = CLAPWrapper(model_fp=None, version='2023', use_cuda=True)
  7. Process audio and text in batches

    main

    For large-scale inference, use the per_batch variants of the embedding and classification methods to avoid memory exhaustion.

    • get_audio_embeddings_per_batch(audio_files, batch_size): A generator yielding audio embeddings for chunks of files.
    • get_text_embeddings_per_batch(class_labels, batch_size): A generator yielding text embeddings for chunks of labels.
    • classify_audio_files_per_batch(audio_files, class_labels, batch_size): A generator yielding classification results for batches of audio against all provided labels.
    # Example of batch processing audio
    for batch_embeddings in wrapper.get_audio_embeddings_per_batch(large_audio_list, batch_size=32):
        # process batch_embeddings
        pass
  8. Compute similarity between audio and text

    main

    Use compute_similarity to calculate the similarity scores between audio embeddings and text embeddings. This is typically used for retrieval or zero-shot classification.

    Input:

    • audio_embeddings: Tensor of audio embeddings.
    • text_embeddings: Tensor of text embeddings.

    Output: A similarity matrix (tensor) where scores represent the relationship between audio and text pairs.

    # audio_embeddings and text_embeddings are obtained via the respective getter methods
    similarity_matrix = wrapper.compute_similarity(audio_embeddings, text_embeddings)
  9. Use the CLAP class for model interaction

    main

    The CLAP class (exported from msclap) is the primary entrypoint for interacting with the Contrastive Language-Audio Pretraining model. It provides a high-level wrapper to load model weights, extract text embeddings, extract audio embeddings, and compute similarity between audio and text.

    from msclap import CLAP
    
    # Initialize the model
    model = CLAP()
  10. Extract text embeddings

    main

    Use get_text_embeddings to convert a list of text strings (class labels or queries) into their corresponding text embeddings.

    Input: A list of strings. Output: A tensor of text embeddings.

    # class_labels is a list of strings
    text_embeddings = wrapper.get_text_embeddings(class_labels=['a dog barking', 'a car engine'])