Dolphin Video Interaction Platform

repository·main·Indexed 42 days ago

https://github.com/kaleido-lab/dolphin

A general video interaction platform that utilizes Large Language Models (LLMs) to enable video understanding, processing, and generation via a chatbot interface. It supports various foundation models for tasks such as video captioning, text-to-video generation (ModelscopeT2V), structural feature extraction (Canny, Pose, Depth), and audio generation (Text2Audio), as well as video manipulation through a MoviepyInterface.

Tokens
8.2K
Snippets
23
Records
31
Agent score
54%

What's inside Dolphin

  1. Install and set up Dolphin

    main

    Dolphin requires Python 3.8. It is recommended to use conda to manage the environment.

    Follow these steps to set up the project:

    1. Create and activate a new conda environment with Python 3.8.
    2. Clone the repository.
    3. Install the required dependencies using pip.
    # Create and activate environment
    conda create -n dolphin python=3.8
    conda activate dolphin
    
    # Clone the repository
    git clone https://github.com/BUAA-PrismGroup/dolphin.git
    cd dolphin
    
    # Install dependencies
    pip install -r requirements.txt
    conda create -n dolphin python=3.8
    conda activate dolphin
    git clone https://github.com/BUAA-PrismGroup/dolphin.git
    cd dolphin
    pip install -r requirements.txt
  2. How to add a new Video Foundation Model

    main

    To extend Dolphin with a new video foundation model, follow these two steps:

    1. Implement the model in modules/

    Create a new Python package under the modules directory. Implement a class in the package's __init__.py file that includes an __init__ method and an inference function. For example, if adding face2video, create modules/face2video/__init__.py and define the FaceText2Video class.

    2. Register the model in configs/backend.yaml

    Add the model to the model_zoos section and define its corresponding tool in the tools section.

    Example configuration for FaceText2Video:

    model_zoos:
      FaceText2Video:  # foundation model class
        target: modules.face2video.FaceText2Video # path of the class in project
        params: # params passed to the class
          device: cuda:0
    tools:
      - name: Generate Video Condition On Face Video
        desc: "useful when you want to generate a new video from both the user description and a facial keypoints video..."
        instance: FaceText2Video
        func: inference
    model_zoos:
      FaceText2Video:
        target: modules.face2video.FaceText2Video
        params:
          device: cuda:0
    tools:
      - name: Generate Video Condition On Face Video
        desc: "..."
        instance: FaceText2Video
        func: inference
  3. How to add a new Large Language Model (LLM)

    main
    To support a new LLM, create a new Python file in the project root directory (e.g., video_moss.py or video_stablelm.py) and implement the necessary logic. Refer to the existing implementation in video_chatgpt.py for the required structure and integration patterns.
  4. Run Dolphin with custom model assignments

    main

    You can start Dolphin using video_chatgpt.py. Use the --load flag to specify which Video Foundation Model to use and which device (CPU or GPU) it should be loaded onto.

    Syntax for --load:

    • Format: ModelName_device (e.g., VideoCaptioning_cuda:0 or MoviepyInterface_cpu).
    • Multiple models are separated by commas (e.g., ModelA_cuda:0,ModelB_cpu).

    Examples:

    For CPU-only users:

    python video_chatgpt.py --load VideoCaptioning_cpu,ImageCaptioning_cpu,ModelscopeT2V_cpu

    For multi-GPU setups (e.g., 4x Tesla V100 32GB): You can rely on the default configuration in configs/backend.yaml or manually specify assignments via --load.

    python video_chatgpt.py
    # Example: Loading specific models to specific devices
    python video_chatgpt.py --load VideoCaptioning_cuda:0,MoviepyInterface_cpu
  5. Implement a custom model by subclassing BaseModel

    main

    To create a new model implementation in the face3d framework, you must subclass BaseModel and implement five core methods. This abstraction handles network initialization, data preprocessing, the forward pass, parameter optimization, and command-line option management.

    Required methods to implement:

    1. __init__(self, opt): Initialize the class. You must call BaseModel.__init__(self, opt) first. During initialization, you must define four lists:
      • self.loss_names (list of str): Training losses to plot/save.
      • self.model_names (list of str): Network names to display/save.
      • self.visual_names (list of str): Networks used for training visualization.
      • self.optimizers (list): Initialized optimizers (one per network, or grouped using itertools.chain).
    2. set_input(self, input): Unpack data from the dataloader and apply preprocessing. input is a dictionary containing data and metadata.
    3. forward(self): The core logic to produce intermediate results. This is called by both optimize_parameters and test.
    4. optimize_parameters(self): Logic to calculate losses, compute gradients, and update network weights. This is called every training iteration.
    5. modify_commandline_options(self, parser, is_train) (Optional): Add model-specific options to the provided parser. is_train (bool) indicates if the current phase is training or testing.
    from face3d.models.base_model import BaseModel
    
    class MyCustomModel(BaseModel):
        def __init__(self, opt):
            super().__init__(opt)  # Must call BaseModel.__init__
            self.loss_names = ['loss_a']
            self.model_names = ['net_G']
            self.visual_names = ['net_G']
            self.optimizers = [torch.optim.Adam(self.net_G.parameters())]
    
        def set_input(self, input):
            # Unpack data
            self.real_A = input['A']
    
        def forward(self):
            # Forward pass logic
            self.fake_B = self.net_G(self.real_A)
            self.loss_a = self.criterion(self.fake_B, self.real_B)
    
        def optimize_parameters(self):
            self.forward()
            self.loss_a.backward()
            self.optimizers[0].step()
    
        def modify_commandline_options(self, parser, is_train):
            parser.add_argument('--my_param', type=float, default=0.5)
            return parser
  6. How to implement a custom face3d model

    main

    To add a custom model to the face3d.models package, follow these steps:

    1. Create a new file named <model_name>_model.py in the modules/sadtalker/src/face3d/models/ directory.
    2. Define a class named <ModelName>Model (e.g., DummyModel) that inherits from BaseModel.
    3. Implement the following five required methods:
      • __init__(self, opt): Initialize the class. You must call BaseModel.__init__(self, opt) first. During initialization, you must define four specific attributes:
        • self.loss_names (list of str): Training losses to plot and save.
        • self.model_names (list of str): Names of the networks used in training.
        • self.visual_names (list of str): Images to display and save.
        • self.optimizers (list of optimizers): Initialized optimizers. You can use itertools.chain to group multiple networks into a single optimizer.
      • set_input(self): Unpack data from the dataset and apply preprocessing.
      • forward(self): Produce intermediate results.
      • optimize_parameters(self): Calculate loss, compute gradients, and update network weights.
      • modify_commandline_options(self, opt): (Optional) Add model-specific options and set default values.

    Once implemented, you can use your model by passing the --model <model_name> flag to the training or testing scripts.

  7. Reference: Foundation Model GPU memory usage

    main

    When planning your hardware setup, use the following memory requirements for the available foundation models:

    Foundation ModelGPU Memory (MB)
    VideoCaptioning13393
    ImageCaptioning8429
    MoviepyInterface0
    Video2Canny0
    Video2Pose1361
    Video2Depth1521
    CannyText2Video6659
    PoseText2Video6721
    DepthText2Video6773
    VideoPix2Pix5251
    ModelscopeT2V6535
    Text2Audio5797
  8. Generate linear and mel spectrograms

    main

    The module provides functions to generate spectrograms used in audio processing. These functions automatically handle pre-emphasis and normalization based on the global hparams configuration.

    • linearspectrogram(wav): Returns the linear spectrogram in dB scale.
    • melspectrogram(wav): Returns the mel-scaled spectrogram in dB scale.

    Note: The behavior of these functions (such as whether to use lws for STFT or apply signal normalization) is controlled by the hparams object.

    from modules.sadtalker.src.utils.audio import linearspectrogram, melspectrogram
    
    # Generate spectrograms
    linear_spec = linearspectrogram(wav)
    mel_spec = melspectrogram(wav)
  9. Generate video from text with ModelscopeT2V

    main

    Use ModelscopeT2V to generate a new video from a text description. You must specify the device (e.g., "cuda:1") during initialization.

    • ModelscopeT2V.inference: Takes a text description and returns the path to the generated video file.
    from modules.modelscope_t2v import ModelscopeT2V
    
    mst2v = ModelscopeT2V("cuda:1")
    text2video = mst2v.inference # input: description, output: new_video_path
    
    # Example:
    # path = text2video("a goldendoodle playing in a park")
  10. Calculate spectrogram frame padding

    main

    When using the lws (Local Wavelet Scattering) processor, specific padding logic is required to ensure the number of frames matches the signal length.

    • num_frames(length, fsize, fshift): Computes the expected number of time frames for a given signal length, FFT size (fsize), and frame shift (fshift).
    • pad_lr(x, fsize, fshift): Computes the required left and right padding amounts to satisfy the frame requirements for lws processing.
    from modules.sadtalker.src.utils.audio import num_frames, pad_lr
    
    # Calculate padding for LWS
    left_pad, right_pad = pad_lr(wav, fsize=1024, fshift=256)
    # Apply padding manually if needed
    padded_wav = np.pad(wav, (left_pad, right_pad), mode='constant')
  11. Use SynchronizedBatchNorm1d for temporal batch normalization

    main

    Use SynchronizedBatchNorm1d when you need to perform batch normalization over a 2D or 3D input (e.g., (N, C) or (N, C, L)) in a distributed training environment. Unlike standard PyTorch BatchNorm1d, this module reduces mean and standard-deviation across all devices during training, providing more accurate statistics for distributed mini-batches.

    In single-GPU or CPU-only scenarios, it behaves identically to the standard PyTorch implementation. It is often referred to as 'Temporal BatchNorm' when computing statistics on (N, L) slices.

    import torch
    from modules.sadtalker.src.facerender.sync_batchnorm.batchnorm import SynchronizedBatchNorm1d
    
    # With Learnable Parameters
    m = SynchronizedBatchNorm1d(100)
    
    # Without Learnable Parameters
    m = SynchronizedBatchNorm1d(100, affine=False)
    
    input = torch.randn(20, 100)
    output = m(input)
  12. Create a model instance with create_model()

    main

    The create_model function is the primary interface for instantiating models from train.py or test.py. It looks up the model class based on the model attribute in the provided options object and returns an instance of that class.

    To use it, ensure your options object (opt) has a model attribute matching the name of your model file (without the _model suffix).

    from models import create_model
    
    # Assuming 'opt' is a parsed argument object containing 'model'
    model = create_model(opt)