Minicpm Video Understanding Model 사용하기

안녕하세요 이번에는 Video 인식 및 Video Contents 이해를 위해 Minicpm 모델을 사용하여 Video 내용을 인식시키는 예제를 보여드리고 Video Understanding이 가능한 MultiModal 모델인 Minicpm을 사용하는 법을 알려드리도록 하겠습니다.

우선 저희는 파이썬 3.11.3버전을 사용하도록 하겠습니다.

Python 3.11.3

다음과 같은 영상을 인식시켰을 경우 모델이 추론한 결과 입니다.

The video features a split-screen view with two distinct sections. On the left side, there is an animated animal character that resembles a cat or a small mammal. This character has orange and white fur, large ears, and appears to be in motion against a black background. The right side of the screen shows a 3D model of another animal character, which looks like a deer or similar creature. This 3D model is multicolored with shades of green, yellow, blue, and pink, set against a gray background.

As the video progresses, both characters remain on their respective sides without any significant changes in appearance or position. However, towards the end, the scene transitions smoothly into a new frame where only the 3D model remains visible. It continues to display its vibrant colors (green, yellow, blue, and pink) against the unchanged gray background. Throughout this sequence, no other elements appear, maintaining focus solely on these two contrasting representations: one dynamic and animated, the other static yet colorful.

해당 출력을 파파고로 번역한 결과입니다.

이 동영상은 두 개의 뚜렷한 섹션이 있는 분할 화면 보기를 특징으로 합니다. 왼쪽에는 고양이나 작은 포유류를 닮은 애니메이션 동물 캐릭터가 있습니다. 이 캐릭터는 주황색과 흰색 털, 큰 귀를 가지고 있으며 검은색 배경을 배경으로 움직이는 것처럼 보입니다. 화면 오른쪽에는 사슴이나 비슷한 생물처럼 보이는 다른 동물 캐릭터의 3D 모델이 표시됩니다. 이 3D 모델은 회색 배경을 배경으로 녹색, 노란색, 파란색, 분홍색의 음영으로 다양한 색상으로 구성되어 있습니다.

영상이 진행됨에 따라 두 캐릭터는 외형이나 위치에 큰 변화 없이 각자의 입장을 유지합니다. 그러나 마지막에는 3D 모델만 보이는 새로운 프레임으로 부드럽게 전환됩니다. 변하지 않은 회색 배경에 맞춰 선명한 색상(녹색, 노란색, 파란색, 분홍색)을 계속 표시합니다. 이 시퀀스 전반에 걸쳐 다른 요소는 나타나지 않으며, 하나는 역동적이고 애니메이션적이며 다른 하나는 정적이면서도 다채로운 두 가지 대조적인 표현에만 집중합니다.

conda create -n minicpm3 -y python==3.11.3


pip install -r clean_requirements.txt --extra-index-url https://download.pytorch.org/whl/cu124
Looking in indexes: https://pypi.org/simple, https://download.pytorch.org/whl/cu124

이렇게 설치하고

conda activate minicpm3
import torch

torch.cuda.empty_cache()  # ✅ 캐시 정리


import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
from decord import VideoReader, cpu  # pip install decord

model = AutoModel.from_pretrained(
    "openbmb/MiniCPM-o-2_6",
    trust_remote_code=True,
    attn_implementation="eager",
    torch_dtype=torch.float32,
)  # sdpa or flash_attention_2, no eager
# model = model.eval().cuda()
model = model.eval().to("cpu")
tokenizer = AutoTokenizer.from_pretrained(
    "openbmb/MiniCPM-o-2_6", trust_remote_code=True
)

MAX_NUM_FRAMES = 32  # if cuda OOM set a smaller number


def encode_video(video_path):
    def uniform_sample(l, n):
        gap = len(l) / n
        idxs = [int(i * gap + gap / 2) for i in range(n)]
        return [l[i] for i in idxs]

    vr = VideoReader(video_path, ctx=cpu(0))
    sample_fps = round(vr.get_avg_fps() / 1)  # FPS
    frame_idx = [i for i in range(0, len(vr), sample_fps)]
    if len(frame_idx) > MAX_NUM_FRAMES:
        frame_idx = uniform_sample(frame_idx, MAX_NUM_FRAMES)
    frames = vr.get_batch(frame_idx).asnumpy()
    frames = [Image.fromarray(v.astype("uint8")) for v in frames]
    print("num frames:", len(frames))
    return frames


video_path = "video_test.avi"
frames = encode_video(video_path)
question = "Describe the video"
msgs = [
    {"role": "user", "content": frames + [question]},
]

# Set decode params for video
params = {}
params["use_image_id"] = False
params["max_slice_nums"] = 1  # use 1 if cuda OOM and video resolution > 448*448

answer = model.chat(msgs=msgs, tokenizer=tokenizer, **params)
print(answer)

위의 코드를 실행해보면

The video features a side-by-side comparison of two distinct animated animals against contrasting backgrounds. On the left, an orange and white cat with large ears is set against a black background. The right side showcases a colorful, abstract representation of another animal on a gray background. Throughout the sequence, both images remain static without any movement or changes in their appearance. This setup creates a visual contrast between the detailed, realistic depiction of the cat and the vibrant, artistic rendering of the other animal.

다음과 같이 나오네요.

이 동영상은 대조적인 배경과 두 개의 뚜렷한 애니메이션 동물을 나란히 비교하는 내용을 담고 있습니다. 왼쪽에는 큰 귀를 가진 주황색과 흰색 고양이가 검은색 배경을 배경으로 설정되어 있습니다. 오른쪽에는 회색 배경에 다른 동물을 다채롭고 추상적으로 표현한 모습이 담겨 있습니다. 시퀀스 내내 두 이미지 모두 움직임이나 외형 변화 없이 정적으로 유지됩니다. 이 설정은 고양이의 세밀하고 사실적인 묘사와 다른 동물의 생동감 있고 예술적인 렌더링 사이에 시각적 대조를 이룹니다.

이렇게 Video Understanding을 손쉽게 구현해볼 수 있었습니다.