File size: 6,038 Bytes
fef0a8d
99eb93c
fef0a8d
 
4cab0f7
938f862
cb40697
294c109
7820541
45099c6
c750982
542f90d
fef0a8d
294c109
fef0a8d
 
 
 
 
f8a64f8
45099c6
5268082
e52a62d
0629ecb
4bd5128
294c109
 
4bd5128
96f2f76
 
 
 
 
 
 
 
7820541
409f566
 
 
 
7820541
 
4cab0f7
 
7820541
4cab0f7
 
 
 
 
 
 
45099c6
b5f3a95
 
c750982
 
 
 
409f566
 
c750982
b5f3a95
409f566
 
b5f3a95
 
 
409f566
b5f3a95
 
 
 
294c109
4cab0f7
 
 
 
 
 
294c109
b5f3a95
 
 
 
 
 
 
294c109
b5f3a95
 
 
4cab0f7
b5f3a95
 
 
 
 
 
 
 
e6f4055
f8a64f8
7820541
b5f3a95
 
 
 
 
 
 
 
 
 
 
 
294c109
b5f3a95
af21e2a
5268082
 
 
 
 
1b6a68d
b5f3a95
5268082
5a25e75
b5f3a95
 
 
5268082
294c109
5268082
 
 
46010b5
 
 
4cab0f7
5268082
 
eb3d2f3
5268082
 
eb3d2f3
5268082
 
 
5a25e75
5268082
 
 
5a25e75
5268082
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# Imports
import gradio as gr
import spaces
import torch
import os
import math
import tempfile
import librosa
from PIL import Image, ImageSequence
from decord import VideoReader, cpu
from moviepy.editor import VideoFileClip
from transformers import AutoModel, AutoTokenizer, AutoProcessor

# Variables
DEVICE = "auto"
if DEVICE == "auto":
    DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print(f"[SYSTEM] | Using {DEVICE} type compute device.")

DEFAULT_INPUT = "Describe in one short sentence."
MAX_FRAMES = 64

model_name = "openbmb/MiniCPM-o-2_6"

repo = AutoModel.from_pretrained(model_name, trust_remote_code=True, attn_implementation="sdpa", torch_dtype=torch.bfloat16).to(DEVICE)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)

css = '''
.gradio-container{max-width: 560px !important}
h1{text-align:center}
footer {
    visibility: hidden
}
'''

input_prefixes = {
    "Image": "(A image file called β–ˆ has been attached, describe the image content) ",
    "GIF": "(A GIF file called β–ˆ has been attached, describe the GIF content) ",
    "Video": "(A video with audio file called β–ˆ has been attached, describe the video content and the audio content embedded into the video) ",
    "Audio": "(A audio file called β–ˆ has been attached, describe the audio content) ",
}

filetypes = {
    "Image": [".jpg", ".jpeg", ".png", ".bmp"],
    "GIF": [".gif"],
    "Video": [".mp4", ".mov", ".avi", ".mkv"],
    "Audio": [".wav", ".mp3", ".flac", ".aac"],
}

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

def build_omni_chunks(path, prefix, instruction, sr=AUDIO_SR, seconds_per_unit=1):
    clip = VideoFileClip(path, audio_fps=sr)
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
        clip.audio.write_audiofile(tmp.name, fps=sr, codec="pcm_s16le", verbose=False, logger=None)
        audio_np, _ = librosa.load(tmp.name, sr=sr, mono=True)
    total_units = math.ceil(clip.duration / seconds_per_unit)
    content = []
    for i in range(total_units):
        t = min(i * seconds_per_unit, clip.duration - 1e-3)
        frame = Image.fromarray(clip.get_frame(t).astype("uint8")).convert("RGB")
        audio_chunk = audio_np[sr * i * seconds_per_unit : sr * (i + 1) * seconds_per_unit]
        content.extend(["<unit>", frame, audio_chunk])
    clip.close()
    os.remove(tmp.name)
    content.append(prefix + instruction)
    return content

def build_image_omni(path, prefix, instruction):
    image = Image.open(path).convert("RGB")
    return ["<unit>", image, prefix + instruction]

def encode_gif(path):
    img = Image.open(path)
    frames = [frame.copy().convert("RGB") for frame in ImageSequence.Iterator(img)]
    if len(frames) > MAX_FRAMES:
        frames = uniform_sample(frames, MAX_FRAMES)
    return frames

def build_gif_omni(path, prefix, instruction):
    frames = encode_gif(path)
    content = []
    for f in frames:
        content.extend(["<unit>", f])
    content.append(prefix + instruction)
    return content

def build_audio_omni(path, prefix, instruction, sr=AUDIO_SR):
    audio_np, _ = librosa.load(path, sr=sr, mono=True)
    return ["<unit>", audio_np, prefix + instruction]

@spaces.GPU(duration=60)
def generate(input, instruction=DEFAULT_INPUT, sampling=False, temperature=0.7, top_p=0.8, top_k=100, repetition_penalty=1.05, max_tokens=512):
    if not input: return "No input provided."
    
    extension = os.path.splitext(input)[1].lower()
    filetype = next((k for k, v in filetypes.items() if extension in v), None)
    
    if not filetype: return "Unsupported file type."
    
    filename = os.path.basename(input)
    prefix = input_prefixes[filetype].replace("β–ˆ", filename)
    if filetype == "Video":
        omni_content = build_omni_chunks(input, prefix, instruction)
    elif filetype == "Image":
        omni_content = build_image_omni(input, prefix, instruction)
    elif filetype == "GIF":
        omni_content = build_gif_omni(input, prefix, instruction)
    elif filetype == "Audio":
        omni_content = build_audio_omni(input, prefix, instruction)
    
    sys_msg = repo.get_sys_prompt(mode="omni", language="en")
    msgs = [sys_msg, {"role": "user", "content": omni_content}]
    
    params = {
        "msgs": msgs,
        "tokenizer": tokenizer,
        "sampling": sampling,
        "temperature": temperature,
        "top_p": top_p,
        "top_k": top_k,
        "repetition_penalty": repetition_penalty,
        "max_new_tokens": max_tokens,
        "omni_input": True,
    }
    
    output = repo.chat(**params)
    torch.cuda.empty_cache()
    gc.collect()
    return output

def cloud():
    print("[CLOUD] | Space maintained.")

# Initialize
with gr.Blocks(css=css) as main:
    with gr.Column():
        input = gr.File(label="Input", file_types=["image", "video", "audio"], type="filepath")
        instruction = gr.Textbox(lines=1, value=DEFAULT_INPUT, label="Instruction")
        sampling = gr.Checkbox(value=False, label="Sampling")
        temperature = gr.Slider(minimum=0.01, maximum=1.99, step=0.01, value=0.7, label="Temperature")
        top_p = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.8, label="Top P")
        top_k = gr.Slider(minimum=0, maximum=1000, step=1, value=100, label="Top K")
        repetition_penalty = gr.Slider(minimum=0.01, maximum=1.99, step=0.01, value=1.05, label="Repetition Penalty")
        max_tokens = gr.Slider(minimum=1, maximum=4096, step=1, value=512, label="Max Tokens")
        submit = gr.Button("β–Ά")
        maintain = gr.Button("☁️")

    with gr.Column():
        output = gr.Textbox(lines=1, value="", label="Output")

    submit.click(fn=generate, inputs=[input, instruction, sampling, temperature, top_p, top_k, repetition_penalty, max_tokens], outputs=[output], queue=False)
    maintain.click(cloud, inputs=[], outputs=[], queue=False)

main.launch(show_api=True)