VideoRAG

repository·main·Indexed 25 days ago

https://github.com/hkuds/videorag

A framework and application (Vimo) for Retrieval-Augmented Generation (RAG) applied to extreme long-context videos. It enables natural language conversations with video content spanning hundreds of hours using a dual-channel architecture featuring graph-driven knowledge indexing and hierarchical context encoding. The system supports multi-video analysis and is compatible with MP4, MKV, and AVI formats, requiring a GPU with at least 24GB of memory (e.g., RTX 3090).

Tokens
10K
Snippets
18
Records
53
Agent score
85%

What's inside VideoRAG

  1. Overview of Vimo Desktop

    main

    Vimo is a desktop application for chatting with videos using the VideoRAG framework. It is designed to handle extreme long-context video processing, allowing users to analyze videos ranging from short clips to hundreds of hours of content.

    Key Capabilities:

    • Drag & Drop Upload: Easy video ingestion.
    • Smart Conversations: Natural language querying of video content.
    • Multi-Format Support: Compatible with MP4, MKV, AVI, and more.
    • Extreme Long Videos: Supports processing of very long sequences.
    • Multi-Video Analysis: Ability to compare and analyze multiple videos simultaneously.
    • Cross-Platform: Available on macOS, Windows, and Linux.
  2. Install VideoRAG

    main

    To install VideoRAG, first create and activate a Conda environment with Python 3.11, then install the core dependencies including PyTorch, video processing utilities, and multi-modal libraries.

    # Create and activate conda environment
    conda create --name videorag python=3.11
    conda activate videorag
    
    # Core numerical and deep learning libraries
    pip install numpy==1.26.4
    pip install torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2
    pip install accelerate==0.30.1
    pip install bitsandbytes==0.43.1
    
    # Video processing utilities
    pip install moviepy==1.0.3
    pip install git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d
    pip install --no-deps git+https://github.com/facebookresearch/ImageBind.git@3fcf5c9039de97f6ff5528ee4a9dce903c5979b3
    
    # Multi-modal and vision libraries
    pip install timm ftfy regex einops fvcore eva-decord==0.6.1 iopath matplotlib types-regex cartopy
    
    # Audio processing and vector databases
    pip install ctranslate2==4.4.0 faster_whisper==1.0.3 neo4j hnswlib xxhash nano-vectordb
    
    # Language models and utilities
    pip install transformers==4.37.1
    pip install tiktoken openai tenacity
    pip install ollama==0.5.3
  3. Run Vimo from Source Code

    main

    To run Vimo from source, you must first set up and start the Python-based backend service, then launch the frontend application. This setup is verified for macOS with M1 chips.

    Important: Ensure the backend service is running before launching the frontend. Also, once a video is imported, do not move or rename the file, as this will disrupt video access in the current beta version.

  4. Set Up and Start Vimo Backend Service

    main

    Vimo uses a Python-based VideoRAG server. Create a Conda environment and install the required libraries for deep learning, video processing, multi-modal vision, audio, and the Flask server.

    conda create --name vimo python=3.11
    conda activate vimo
    
    # Core numerical and deep learning libraries
    pip install numpy==1.26.4 torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2
    
    # Video processing utilities
    pip install moviepy==1.0.3
    pip install git+https://github.com/Re-bin/pytorchvideo.git@58f50da4e4b7bf0b17b1211dc6b283ba42e522df
    pip install --no-deps git+https://github.com/facebookresearch/ImageBind.git@3fcf5c9039de97f6ff5528ee4a9dce903c5979b3
    
    # Multi-modal and vision libraries
    pip install timm ftfy regex einops fvcore eva-decord==0.6.1 iopath matplotlib types-regex cartopy
    
    # Audio processing and vector databases
    pip install neo4j hnswlib xxhash nano-vectordb
    
    # Language models and utilities
    pip install tiktoken openai tenacity dashscope
    
    # Server
    pip install flask psutil flask_cors setproctitle
    
    # Start the server
    cd python_backend
    python videorag_api.py
  5. Quick Start Vimo via Source Code

    main

    To run Vimo from source, you must set up both a Python backend and an Electron frontend.

    1. Backend: Set up the Python environment and start the VideoRAG server.
    2. Frontend: Launch the Electron frontend application.

    For complete installation and configuration steps, refer to the vimo-desktop package documentation.

  6. Download VideoRAG Model Checkpoints

    main

    Download the required checkpoints for MiniCPM-V, Whisper, and ImageBind into the repository's root folder. Ensure git-lfs is installed before cloning models.

    # Ensure git-lfs is installed
    git lfs install
    
    # Download MiniCPM-V model
    git lfs clone https://huggingface.co/openbmb/MiniCPM-V-2_6-int4
    
    # Download Whisper model
    git lfs clone https://huggingface.co/Systran/faster-distil-whisper-large-v3
    
    # Download ImageBind checkpoint
    mkdir .checkpoints
    cd .checkpoints
    wget https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth
    cd ../
  7. Configure Ollama Support

    main

    To use Ollama as the LLM backend, edit the ollama_config in videorag/_llm.py. You must specify the embedding model, embedding dimensions, and the names of the best and cheap models used for completion.

    ollama_config = LLMConfig(
        embedding_func_raw = ollama_embedding,
        embedding_model_name = "nomic-embed-text",
        embedding_dim = 768,
        embedding_max_token_size=8192,
        embedding_batch_num = 1,
        embedding_func_max_async = 1,
        query_better_than_threshold = 0.2,
        best_model_func_raw = ollama_complete ,
        best_model_name = "gemma2:latest", # need to be a solid instruct model
        best_model_max_token_size = 32768,
        best_model_max_async  = 1,
        cheap_model_func_raw = ollama_mini_complete,
        cheap_model_name = "olmo2",
        cheap_model_max_token_size = 32768,
        cheap_model_max_async = 1
    )
  8. Query the VideoRAG index

    main

    To perform a query against your video index, first load the caption model using load_caption_model(). Then, create a QueryParam object specifying the mode (e.g., mode="videorag") and use the query method. You can control whether references are included by setting param.wo_reference.

    from videorag import QueryParam
    
    # Load the necessary caption model
    videorag.load_caption_model(debug=False)
    
    # Configure query parameters
    param = QueryParam(mode="videorag")
    param.wo_reference = False
    
    # Execute query
    query = "What are the Lexington school construction options"
    response = videorag.query(query=query, param=param)
    print(response)
  9. Initialize and build a VideoRAG index

    main

    To build a searchable index from video files, initialize the VideoRAG class with a specific LLM configuration and a working directory. Use the insert_video method to process a list of video paths.

    Note: If running in an environment with nested event loops (like Jupyter), you may need to call nest_asyncio.apply(). For multiprocessing support, it is recommended to set the start method to 'spawn'.

  10. Query Videos with VideoRAG

    main

    Ask questions about indexed videos using VideoRAG.query. You can configure the query behavior using QueryParam. Setting param.wo_reference = True will prevent VideoRAG from adding video clip references to the response.

    import os
    import logging
    import warnings
    import multiprocessing
    
    warnings.filterwarnings("ignore")
    logging.getLogger("httpx").setLevel(logging.WARNING)
    
    # Please enter your openai key
    os.environ["OPENAI_API_KEY"] = ""
    
    from videorag._llm import *
    from videorag import VideoRAG, QueryParam
    
    if __name__ == '__main__':
        multiprocessing.set_start_method('spawn')
    
        query = 'What is the relationship between Iron Man and Spider-Man? How do they meet, and how does Iron Man help Spider-Man?'
        param = QueryParam(mode="videorag")
        # if param.wo_reference = False, VideoRAG will add reference to video clips in the response
        param.wo_reference = True
    
        videorag = videorag = VideoRAG(llm=openai_4o_mini_config, working_dir=f"./videorag-workdir")
        videorag.load_caption_model(debug=False)
        response = videorag.query(query=query, param=param)
        print(response)
  11. Index Videos with VideoRAG

    main

    Use VideoRAG.insert_video to extract and index knowledge from a list of video files. This process requires an OPENAI_API_KEY environment variable and a single GPU with at least 24GB of memory (e.g., RTX 3090).

    import os
    import logging
    import warnings
    import multiprocessing
    
    warnings.filterwarnings("ignore")
    logging.getLogger("httpx").setLevel(logging.WARNING)
    
    # Please enter your openai key
    os.environ["OPENAI_API_KEY"] = ""
    
    from videorag._llm import openai_4o_mini_config
    from videorag import VideoRAG, QueryParam
    
    if __name__ == '__main__':
        multiprocessing.set_start_method('spawn')
    
        # Please enter your video file path in this list; there is no limit on the length.
        video_paths = [
            'movies/Iron-Man.mp4',
            'movies/Spider-Man.mkv',
        ]
        videorag = VideoRAG(llm=openai_4o_mini_config, working_dir=f"./videorag-workdir")
        videorag.insert_video(video_path_list=video_paths)