Spaces:
Running
on
Zero
Running
on
Zero
Update demo.
Browse files
VideoLLaMA2/videollama2/__init__.py
CHANGED
|
@@ -48,9 +48,19 @@ def mm_infer(image_or_video, instruct, model, tokenizer, modal='video', **kwargs
|
|
| 48 |
modal_token = DEFAULT_IMAGE_TOKEN
|
| 49 |
elif modal == 'video':
|
| 50 |
modal_token = DEFAULT_VIDEO_TOKEN
|
|
|
|
|
|
|
| 51 |
else:
|
| 52 |
raise ValueError(f"Unsupported modal: {modal}")
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
if isinstance(instruct, str):
|
| 55 |
message = [{'role': 'user', 'content': modal_token + '\n' + instruct}]
|
| 56 |
elif isinstance(instruct, list):
|
|
@@ -76,11 +86,6 @@ def mm_infer(image_or_video, instruct, model, tokenizer, modal='video', **kwargs
|
|
| 76 |
input_ids = tokenizer_multimodal_token(prompt, tokenizer, modal_token, return_tensors='pt').unsqueeze(0).long().cuda()
|
| 77 |
attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
|
| 78 |
|
| 79 |
-
# 2. vision preprocess (load & transform image or video).
|
| 80 |
-
tensor = image_or_video.half().cuda()
|
| 81 |
-
|
| 82 |
-
tensor = [(tensor, modal_token)]
|
| 83 |
-
|
| 84 |
# 3. generate response according to visual signals and prompts.
|
| 85 |
keywords = [tokenizer.eos_token]
|
| 86 |
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
|
|
|
| 48 |
modal_token = DEFAULT_IMAGE_TOKEN
|
| 49 |
elif modal == 'video':
|
| 50 |
modal_token = DEFAULT_VIDEO_TOKEN
|
| 51 |
+
elif modal == 'text':
|
| 52 |
+
modal_token = ''
|
| 53 |
else:
|
| 54 |
raise ValueError(f"Unsupported modal: {modal}")
|
| 55 |
|
| 56 |
+
# 1. vision preprocess (load & transform image or video).
|
| 57 |
+
if modal == 'text':
|
| 58 |
+
tensor = None
|
| 59 |
+
else:
|
| 60 |
+
tensor = image_or_video.half().cuda()
|
| 61 |
+
tensor = [(tensor, modal_token)]
|
| 62 |
+
|
| 63 |
+
# 2. text preprocess (tag process & generate prompt).
|
| 64 |
if isinstance(instruct, str):
|
| 65 |
message = [{'role': 'user', 'content': modal_token + '\n' + instruct}]
|
| 66 |
elif isinstance(instruct, list):
|
|
|
|
| 86 |
input_ids = tokenizer_multimodal_token(prompt, tokenizer, modal_token, return_tensors='pt').unsqueeze(0).long().cuda()
|
| 87 |
attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
# 3. generate response according to visual signals and prompts.
|
| 90 |
keywords = [tokenizer.eos_token]
|
| 91 |
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
VideoLLaMA2/videollama2/eval/eval_video_oqa_activitynet.py
CHANGED
|
@@ -5,7 +5,7 @@ import time
|
|
| 5 |
import argparse
|
| 6 |
import traceback
|
| 7 |
from tqdm import tqdm
|
| 8 |
-
from
|
| 9 |
|
| 10 |
from openai import AzureOpenAI
|
| 11 |
|
|
@@ -71,12 +71,13 @@ def prompt_gpt(question, answer, pred, key, qa_set, output_dir):
|
|
| 71 |
json.dump(result_qa_pair, f)
|
| 72 |
|
| 73 |
|
| 74 |
-
def annotate(
|
| 75 |
"""
|
| 76 |
Evaluates question and answer pairs using GPT-3
|
| 77 |
Returns a score for correctness.
|
| 78 |
"""
|
| 79 |
-
|
|
|
|
| 80 |
for file in tqdm(caption_files):
|
| 81 |
key = file[:-5] # Strip file extension
|
| 82 |
qa_set = prediction_set[key]
|
|
@@ -86,8 +87,8 @@ def annotate(prediction_set, caption_files, output_dir, args):
|
|
| 86 |
try:
|
| 87 |
prompt_gpt(question, answer, pred, key, qa_set, output_dir)
|
| 88 |
except Exception as e:
|
| 89 |
-
traceback.print_exc()
|
| 90 |
prompt_gpt(question, answer, pred[:50], key, qa_set, output_dir)
|
|
|
|
| 91 |
|
| 92 |
time.sleep(1)
|
| 93 |
|
|
@@ -141,39 +142,29 @@ def main(args):
|
|
| 141 |
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
| 142 |
|
| 143 |
# Use a pool of workers to process the files in parallel.
|
| 144 |
-
with
|
| 145 |
-
|
| 146 |
|
| 147 |
except Exception as e:
|
| 148 |
print(f"Error: {e}")
|
| 149 |
|
| 150 |
-
#
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
content = json.load(json_file)
|
| 161 |
-
except:
|
| 162 |
-
print(json_file)
|
| 163 |
-
exit(0)
|
| 164 |
-
combined_contents[file_name[:-5]] = content
|
| 165 |
-
|
| 166 |
-
# Write combined content to a json file
|
| 167 |
-
with open(json_path, "w") as json_file:
|
| 168 |
-
json.dump(combined_contents, json_file)
|
| 169 |
-
print("All evaluation completed!")
|
| 170 |
|
| 171 |
# Calculate average score and accuracy
|
| 172 |
score_sum = 0
|
| 173 |
count = 0
|
| 174 |
yes_count = 0
|
| 175 |
no_count = 0
|
| 176 |
-
for key, result in tqdm(combined_contents
|
| 177 |
try:
|
| 178 |
# Computing score
|
| 179 |
count += 1
|
|
|
|
| 5 |
import argparse
|
| 6 |
import traceback
|
| 7 |
from tqdm import tqdm
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 9 |
|
| 10 |
from openai import AzureOpenAI
|
| 11 |
|
|
|
|
| 71 |
json.dump(result_qa_pair, f)
|
| 72 |
|
| 73 |
|
| 74 |
+
def annotate(task_arg):
|
| 75 |
"""
|
| 76 |
Evaluates question and answer pairs using GPT-3
|
| 77 |
Returns a score for correctness.
|
| 78 |
"""
|
| 79 |
+
prediction_set, caption_files, output_dir, args = task_arg
|
| 80 |
+
|
| 81 |
for file in tqdm(caption_files):
|
| 82 |
key = file[:-5] # Strip file extension
|
| 83 |
qa_set = prediction_set[key]
|
|
|
|
| 87 |
try:
|
| 88 |
prompt_gpt(question, answer, pred, key, qa_set, output_dir)
|
| 89 |
except Exception as e:
|
|
|
|
| 90 |
prompt_gpt(question, answer, pred[:50], key, qa_set, output_dir)
|
| 91 |
+
traceback.print_exc()
|
| 92 |
|
| 93 |
time.sleep(1)
|
| 94 |
|
|
|
|
| 142 |
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
| 143 |
|
| 144 |
# Use a pool of workers to process the files in parallel.
|
| 145 |
+
with ThreadPoolExecutor(max_workers=args.num_tasks) as executor:
|
| 146 |
+
list(tqdm(executor.map(annotate, task_args), total=len(task_args)))
|
| 147 |
|
| 148 |
except Exception as e:
|
| 149 |
print(f"Error: {e}")
|
| 150 |
|
| 151 |
+
# multiprocessing to combine json files
|
| 152 |
+
def combine_json(file_name):
|
| 153 |
+
file_path = os.path.join(output_dir, file_name)
|
| 154 |
+
with open(file_path, "r") as json_file:
|
| 155 |
+
content = json.load(json_file)
|
| 156 |
+
return (file_name[:-5], content)
|
| 157 |
+
|
| 158 |
+
files = os.listdir(output_dir)
|
| 159 |
+
with ThreadPoolExecutor(max_workers=64) as executor:
|
| 160 |
+
combined_contents = list(tqdm(executor.map(combine_json, files), total=len(files)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
# Calculate average score and accuracy
|
| 163 |
score_sum = 0
|
| 164 |
count = 0
|
| 165 |
yes_count = 0
|
| 166 |
no_count = 0
|
| 167 |
+
for key, result in tqdm(combined_contents):
|
| 168 |
try:
|
| 169 |
# Computing score
|
| 170 |
count += 1
|
VideoLLaMA2/videollama2/serve/gradio_web_server_adhoc.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
-
|
| 2 |
|
| 3 |
import os
|
|
|
|
| 4 |
|
| 5 |
import torch
|
| 6 |
import gradio as gr
|
|
@@ -79,7 +80,7 @@ class Chat:
|
|
| 79 |
|
| 80 |
self.model, self.processor, self.tokenizer = model_init(model_path, load_8bit=load_8bit, load_4bit=load_4bit)
|
| 81 |
|
| 82 |
-
|
| 83 |
@torch.inference_mode()
|
| 84 |
def generate(self, data: list, message, temperature, top_p, max_output_tokens):
|
| 85 |
# TODO: support multiple turns of conversation.
|
|
@@ -95,41 +96,62 @@ class Chat:
|
|
| 95 |
return response
|
| 96 |
|
| 97 |
|
| 98 |
-
|
| 99 |
def generate(image, video, message, chatbot, textbox_in, temperature, top_p, max_output_tokens, dtype=torch.float16):
|
| 100 |
data = []
|
| 101 |
|
| 102 |
-
image = image if image else "none"
|
| 103 |
-
video = video if video else "none"
|
| 104 |
-
assert not (os.path.exists(image) and os.path.exists(video))
|
| 105 |
-
|
| 106 |
processor = handler.processor
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
assert len(message) % 2 == 0, "The message should be a pair of user and system message."
|
| 115 |
|
| 116 |
-
message.append({'role': 'user', 'content': textbox_in})
|
| 117 |
-
text_en_out = handler.generate(data, message, temperature=temperature, top_p=top_p, max_output_tokens=max_output_tokens)
|
| 118 |
-
message.append({'role': 'assistant', 'content': text_en_out})
|
| 119 |
-
|
| 120 |
show_images = ""
|
| 121 |
-
if
|
| 122 |
show_images += f'<img src="./file={image}" style="display: inline-block;width: 250px;max-height: 400px;">'
|
| 123 |
-
if
|
| 124 |
show_images += f'<video controls playsinline width="500" style="display: inline-block;" src="./file={video}"></video>'
|
| 125 |
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
return (
|
| 129 |
-
gr.update(value=image if os.path.exists(image) else None, interactive=True),
|
| 130 |
-
gr.update(value=video if os.path.exists(video) else None, interactive=True),
|
| 131 |
-
message,
|
| 132 |
-
chatbot)
|
| 133 |
|
| 134 |
|
| 135 |
def regenerate(message, chatbot):
|
|
@@ -147,7 +169,7 @@ def clear_history(message, chatbot):
|
|
| 147 |
|
| 148 |
|
| 149 |
# BUG of Zero Environment
|
| 150 |
-
# 1. The environment is fixed to torch
|
| 151 |
# 2. The operation or tensor which requires cuda are limited in those functions wrapped via spaces.GPU
|
| 152 |
# 3. The function can't return tensor or other cuda objects.
|
| 153 |
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
|
| 3 |
import os
|
| 4 |
+
import re
|
| 5 |
|
| 6 |
import torch
|
| 7 |
import gradio as gr
|
|
|
|
| 80 |
|
| 81 |
self.model, self.processor, self.tokenizer = model_init(model_path, load_8bit=load_8bit, load_4bit=load_4bit)
|
| 82 |
|
| 83 |
+
@spaces.GPU(duration=120)
|
| 84 |
@torch.inference_mode()
|
| 85 |
def generate(self, data: list, message, temperature, top_p, max_output_tokens):
|
| 86 |
# TODO: support multiple turns of conversation.
|
|
|
|
| 96 |
return response
|
| 97 |
|
| 98 |
|
| 99 |
+
@spaces.GPU(duration=120)
|
| 100 |
def generate(image, video, message, chatbot, textbox_in, temperature, top_p, max_output_tokens, dtype=torch.float16):
|
| 101 |
data = []
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
processor = handler.processor
|
| 104 |
+
try:
|
| 105 |
+
if image is not None:
|
| 106 |
+
data.append((processor['image'](image).to(handler.model.device, dtype=dtype), '<image>'))
|
| 107 |
+
elif video is not None:
|
| 108 |
+
data.append((processor['video'](video).to(handler.model.device, dtype=dtype), '<video>'))
|
| 109 |
+
elif image is None and video is None:
|
| 110 |
+
data.append((None, '<text>'))
|
| 111 |
+
else:
|
| 112 |
+
raise NotImplementedError("Not support image and video at the same time")
|
| 113 |
+
except Exception as e:
|
| 114 |
+
traceback.print_exc()
|
| 115 |
+
return gr.update(value=None, interactive=True), gr.update(value=None, interactive=True), message, chatbot
|
| 116 |
|
| 117 |
assert len(message) % 2 == 0, "The message should be a pair of user and system message."
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
show_images = ""
|
| 120 |
+
if image is not None:
|
| 121 |
show_images += f'<img src="./file={image}" style="display: inline-block;width: 250px;max-height: 400px;">'
|
| 122 |
+
if video is not None:
|
| 123 |
show_images += f'<video controls playsinline width="500" style="display: inline-block;" src="./file={video}"></video>'
|
| 124 |
|
| 125 |
+
one_turn_chat = [textbox_in, None]
|
| 126 |
+
|
| 127 |
+
# 1. first run case
|
| 128 |
+
if len(chatbot) == 0:
|
| 129 |
+
one_turn_chat[0] += "\n" + show_images
|
| 130 |
+
# 2. not first run case
|
| 131 |
+
else:
|
| 132 |
+
previous_image = re.findall(r'<img src="./file=(.+?)"', chatbot[0][0])
|
| 133 |
+
previous_video = re.findall(r'<video controls playsinline width="500" style="display: inline-block;" src="./file=(.+?)"', chatbot[0][0])
|
| 134 |
+
if len(previous_image) > 0:
|
| 135 |
+
previous_image = previous_image[0]
|
| 136 |
+
# 2.1 new image append or pure text input will start a new conversation
|
| 137 |
+
if previous_image != image:
|
| 138 |
+
message.clear()
|
| 139 |
+
one_turn_chat[0] += "\n" + show_images if image is not None else ""
|
| 140 |
+
elif len(previous_video) > 0:
|
| 141 |
+
previous_video = previous_video[0]
|
| 142 |
+
# 2.2 new video append or pure text input will start a new conversation
|
| 143 |
+
if previous_video != video:
|
| 144 |
+
message.clear()
|
| 145 |
+
one_turn_chat[0] += "\n" + show_images if video is not None else ""
|
| 146 |
+
|
| 147 |
+
message.append({'role': 'user', 'content': textbox_in})
|
| 148 |
+
text_en_out = handler.generate(data, message, temperature=temperature, top_p=top_p, max_output_tokens=max_output_tokens)
|
| 149 |
+
message.append({'role': 'assistant', 'content': text_en_out})
|
| 150 |
+
|
| 151 |
+
one_turn_chat[1] = text_en_out
|
| 152 |
+
chatbot.append(one_turn_chat)
|
| 153 |
|
| 154 |
+
return gr.update(value=image, interactive=True), gr.update(value=video, interactive=True), message, chatbot
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
|
| 157 |
def regenerate(message, chatbot):
|
|
|
|
| 169 |
|
| 170 |
|
| 171 |
# BUG of Zero Environment
|
| 172 |
+
# 1. The environment is fixed to torch>=2.0,<=2.2, gradio>=4.x.x
|
| 173 |
# 2. The operation or tensor which requires cuda are limited in those functions wrapped via spaces.GPU
|
| 174 |
# 3. The function can't return tensor or other cuda objects.
|
| 175 |
|
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import spaces
|
| 2 |
|
| 3 |
import os
|
|
|
|
| 4 |
|
| 5 |
import torch
|
| 6 |
import gradio as gr
|
|
@@ -19,7 +20,6 @@ title_markdown = ("""
|
|
| 19 |
<div>
|
| 20 |
<h1 >VideoLLaMA 2: Advancing Spatial-Temporal Modeling and Audio Understanding in Video-LLMs</h1>
|
| 21 |
<h5 style="margin: 0;">If this demo please you, please give us a star β on Github or π on this space.</h5>
|
| 22 |
-
<h6 style="margin: 0;">Note that the current demo only supports <b>vision input</b> and <b>single-turn conversation</b>. More features will be available soon.</h6>
|
| 23 |
</div>
|
| 24 |
</div>
|
| 25 |
|
|
@@ -100,37 +100,58 @@ class Chat:
|
|
| 100 |
def generate(image, video, message, chatbot, textbox_in, temperature, top_p, max_output_tokens, dtype=torch.float16):
|
| 101 |
data = []
|
| 102 |
|
| 103 |
-
image = image if image else "none"
|
| 104 |
-
video = video if video else "none"
|
| 105 |
-
assert not (os.path.exists(image) and os.path.exists(video))
|
| 106 |
-
|
| 107 |
processor = handler.processor
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
assert len(message) % 2 == 0, "The message should be a pair of user and system message."
|
| 116 |
|
| 117 |
-
message.append({'role': 'user', 'content': textbox_in})
|
| 118 |
-
text_en_out = handler.generate(data, message, temperature=temperature, top_p=top_p, max_output_tokens=max_output_tokens)
|
| 119 |
-
message.append({'role': 'assistant', 'content': text_en_out})
|
| 120 |
-
|
| 121 |
show_images = ""
|
| 122 |
-
if
|
| 123 |
show_images += f'<img src="./file={image}" style="display: inline-block;width: 250px;max-height: 400px;">'
|
| 124 |
-
if
|
| 125 |
show_images += f'<video controls playsinline width="500" style="display: inline-block;" src="./file={video}"></video>'
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
chatbot)
|
| 134 |
|
| 135 |
|
| 136 |
def regenerate(message, chatbot):
|
|
@@ -148,26 +169,25 @@ def clear_history(message, chatbot):
|
|
| 148 |
|
| 149 |
|
| 150 |
# BUG of Zero Environment
|
| 151 |
-
# 1. The environment is fixed to torch
|
| 152 |
# 2. The operation or tensor which requires cuda are limited in those functions wrapped via spaces.GPU
|
| 153 |
# 3. The function can't return tensor or other cuda objects.
|
| 154 |
|
| 155 |
-
conv_mode = "llama_2"
|
| 156 |
model_path = 'DAMO-NLP-SG/VideoLLaMA2-7B-16F'
|
| 157 |
|
| 158 |
-
device = torch.device("cuda")
|
| 159 |
-
|
| 160 |
handler = Chat(model_path, load_8bit=False, load_4bit=True)
|
| 161 |
|
| 162 |
textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
|
| 163 |
|
| 164 |
theme = gr.themes.Default(primary_hue=plum_color)
|
|
|
|
| 165 |
theme.set(slider_color="#9C276A")
|
| 166 |
theme.set(block_title_text_color="#9C276A")
|
| 167 |
theme.set(block_label_text_color="#9C276A")
|
| 168 |
theme.set(button_primary_text_color="#9C276A")
|
| 169 |
# theme.set(button_secondary_text_color="*neutral_800")
|
| 170 |
|
|
|
|
| 171 |
with gr.Blocks(title='VideoLLaMA 2 π₯ππ₯', theme=theme, css=block_css) as demo:
|
| 172 |
gr.Markdown(title_markdown)
|
| 173 |
message = gr.State([])
|
|
@@ -235,16 +255,16 @@ with gr.Blocks(title='VideoLLaMA 2 π₯ππ₯', theme=theme, css=block_css) as
|
|
| 235 |
gr.Examples(
|
| 236 |
examples=[
|
| 237 |
[
|
| 238 |
-
f"{cur_dir}/examples/
|
| 239 |
"What happens in this image?",
|
| 240 |
],
|
| 241 |
[
|
| 242 |
f"{cur_dir}/examples/waterview.jpg",
|
| 243 |
-
"What
|
| 244 |
],
|
| 245 |
[
|
| 246 |
f"{cur_dir}/examples/desert.jpg",
|
| 247 |
-
"If there are factual errors in the questions, point
|
| 248 |
],
|
| 249 |
],
|
| 250 |
inputs=[image, textbox],
|
|
@@ -253,22 +273,22 @@ with gr.Blocks(title='VideoLLaMA 2 π₯ππ₯', theme=theme, css=block_css) as
|
|
| 253 |
gr.Examples(
|
| 254 |
examples=[
|
| 255 |
[
|
| 256 |
-
f"{cur_dir}/
|
| 257 |
"What happens in this video?",
|
| 258 |
],
|
| 259 |
[
|
| 260 |
-
f"{cur_dir}/
|
| 261 |
-
"
|
| 262 |
],
|
| 263 |
[
|
| 264 |
-
f"{cur_dir}/examples/
|
| 265 |
-
"
|
| 266 |
],
|
| 267 |
],
|
| 268 |
inputs=[video, textbox],
|
| 269 |
)
|
| 270 |
|
| 271 |
-
|
| 272 |
gr.Markdown(learn_more_markdown)
|
| 273 |
|
| 274 |
submit_btn.click(
|
|
|
|
| 1 |
import spaces
|
| 2 |
|
| 3 |
import os
|
| 4 |
+
import re
|
| 5 |
|
| 6 |
import torch
|
| 7 |
import gradio as gr
|
|
|
|
| 20 |
<div>
|
| 21 |
<h1 >VideoLLaMA 2: Advancing Spatial-Temporal Modeling and Audio Understanding in Video-LLMs</h1>
|
| 22 |
<h5 style="margin: 0;">If this demo please you, please give us a star β on Github or π on this space.</h5>
|
|
|
|
| 23 |
</div>
|
| 24 |
</div>
|
| 25 |
|
|
|
|
| 100 |
def generate(image, video, message, chatbot, textbox_in, temperature, top_p, max_output_tokens, dtype=torch.float16):
|
| 101 |
data = []
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
processor = handler.processor
|
| 104 |
+
try:
|
| 105 |
+
if image is not None:
|
| 106 |
+
data.append((processor['image'](image).to(handler.model.device, dtype=dtype), '<image>'))
|
| 107 |
+
elif video is not None:
|
| 108 |
+
data.append((processor['video'](video).to(handler.model.device, dtype=dtype), '<video>'))
|
| 109 |
+
elif image is None and video is None:
|
| 110 |
+
data.append((None, '<text>'))
|
| 111 |
+
else:
|
| 112 |
+
raise NotImplementedError("Not support image and video at the same time")
|
| 113 |
+
except Exception as e:
|
| 114 |
+
traceback.print_exc()
|
| 115 |
+
return gr.update(value=None, interactive=True), gr.update(value=None, interactive=True), message, chatbot
|
| 116 |
|
| 117 |
assert len(message) % 2 == 0, "The message should be a pair of user and system message."
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
show_images = ""
|
| 120 |
+
if image is not None:
|
| 121 |
show_images += f'<img src="./file={image}" style="display: inline-block;width: 250px;max-height: 400px;">'
|
| 122 |
+
if video is not None:
|
| 123 |
show_images += f'<video controls playsinline width="500" style="display: inline-block;" src="./file={video}"></video>'
|
| 124 |
|
| 125 |
+
one_turn_chat = [textbox_in, None]
|
| 126 |
+
|
| 127 |
+
# 1. first run case
|
| 128 |
+
if len(chatbot) == 0:
|
| 129 |
+
one_turn_chat[0] += "\n" + show_images
|
| 130 |
+
# 2. not first run case
|
| 131 |
+
else:
|
| 132 |
+
previous_image = re.findall(r'<img src="./file=(.+?)"', chatbot[0][0])
|
| 133 |
+
previous_video = re.findall(r'<video controls playsinline width="500" style="display: inline-block;" src="./file=(.+?)"', chatbot[0][0])
|
| 134 |
+
if len(previous_image) > 0:
|
| 135 |
+
previous_image = previous_image[0]
|
| 136 |
+
# 2.1 new image append or pure text input will start a new conversation
|
| 137 |
+
if previous_image != image:
|
| 138 |
+
message.clear()
|
| 139 |
+
one_turn_chat[0] += "\n" + show_images if image is not None else ""
|
| 140 |
+
elif len(previous_video) > 0:
|
| 141 |
+
previous_video = previous_video[0]
|
| 142 |
+
# 2.2 new video append or pure text input will start a new conversation
|
| 143 |
+
if previous_video != video:
|
| 144 |
+
message.clear()
|
| 145 |
+
one_turn_chat[0] += "\n" + show_images if video is not None else ""
|
| 146 |
+
|
| 147 |
+
message.append({'role': 'user', 'content': textbox_in})
|
| 148 |
+
text_en_out = handler.generate(data, message, temperature=temperature, top_p=top_p, max_output_tokens=max_output_tokens)
|
| 149 |
+
message.append({'role': 'assistant', 'content': text_en_out})
|
| 150 |
|
| 151 |
+
one_turn_chat[1] = text_en_out
|
| 152 |
+
chatbot.append(one_turn_chat)
|
| 153 |
+
|
| 154 |
+
return gr.update(value=image, interactive=True), gr.update(value=video, interactive=True), message, chatbot
|
|
|
|
| 155 |
|
| 156 |
|
| 157 |
def regenerate(message, chatbot):
|
|
|
|
| 169 |
|
| 170 |
|
| 171 |
# BUG of Zero Environment
|
| 172 |
+
# 1. The environment is fixed to torch>=2.0,<=2.2, gradio>=4.x.x
|
| 173 |
# 2. The operation or tensor which requires cuda are limited in those functions wrapped via spaces.GPU
|
| 174 |
# 3. The function can't return tensor or other cuda objects.
|
| 175 |
|
|
|
|
| 176 |
model_path = 'DAMO-NLP-SG/VideoLLaMA2-7B-16F'
|
| 177 |
|
|
|
|
|
|
|
| 178 |
handler = Chat(model_path, load_8bit=False, load_4bit=True)
|
| 179 |
|
| 180 |
textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
|
| 181 |
|
| 182 |
theme = gr.themes.Default(primary_hue=plum_color)
|
| 183 |
+
# theme.update_color("primary", plum_color.c500)
|
| 184 |
theme.set(slider_color="#9C276A")
|
| 185 |
theme.set(block_title_text_color="#9C276A")
|
| 186 |
theme.set(block_label_text_color="#9C276A")
|
| 187 |
theme.set(button_primary_text_color="#9C276A")
|
| 188 |
# theme.set(button_secondary_text_color="*neutral_800")
|
| 189 |
|
| 190 |
+
|
| 191 |
with gr.Blocks(title='VideoLLaMA 2 π₯ππ₯', theme=theme, css=block_css) as demo:
|
| 192 |
gr.Markdown(title_markdown)
|
| 193 |
message = gr.State([])
|
|
|
|
| 255 |
gr.Examples(
|
| 256 |
examples=[
|
| 257 |
[
|
| 258 |
+
f"{cur_dir}/examples/extreme_ironing.jpg",
|
| 259 |
"What happens in this image?",
|
| 260 |
],
|
| 261 |
[
|
| 262 |
f"{cur_dir}/examples/waterview.jpg",
|
| 263 |
+
"What are the things I should be cautious about when I visit here?",
|
| 264 |
],
|
| 265 |
[
|
| 266 |
f"{cur_dir}/examples/desert.jpg",
|
| 267 |
+
"If there are factual errors in the questions, point it out; if not, proceed answering the question. Whatβs happening in the desert?",
|
| 268 |
],
|
| 269 |
],
|
| 270 |
inputs=[image, textbox],
|
|
|
|
| 273 |
gr.Examples(
|
| 274 |
examples=[
|
| 275 |
[
|
| 276 |
+
f"{cur_dir}/../../assets/cat_and_chicken.mp4",
|
| 277 |
"What happens in this video?",
|
| 278 |
],
|
| 279 |
[
|
| 280 |
+
f"{cur_dir}/../../assets/sora.mp4",
|
| 281 |
+
"Please describe this video.",
|
| 282 |
],
|
| 283 |
[
|
| 284 |
+
f"{cur_dir}/examples/sample_demo_1.mp4",
|
| 285 |
+
"What does the baby do?",
|
| 286 |
],
|
| 287 |
],
|
| 288 |
inputs=[video, textbox],
|
| 289 |
)
|
| 290 |
|
| 291 |
+
gr.Markdown(tos_markdown)
|
| 292 |
gr.Markdown(learn_more_markdown)
|
| 293 |
|
| 294 |
submit_btn.click(
|