merve HF staff commited on
Commit
add40fc
1 Parent(s): 26a5909

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import VideoLlavaForConditionalGeneration, VideoLlavaProcessor, TextIteratorStreamer
3
+ from threading import Thread
4
+ import re
5
+ import time
6
+ from PIL import Image
7
+ import torch
8
+ import cv2
9
+ import spaces
10
+
11
+ model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", torch_dtype=torch.float16, device_map="cuda")
12
+ processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
13
+ #model.to("cuda")
14
+
15
+ def replace_video_with_images(text, frames):
16
+ return text.replace("<video>", "<image>" * frames)
17
+
18
+ import cv2
19
+ from PIL import Image
20
+
21
+ def sample_frames(video_file, num_frames):
22
+ video = cv2.VideoCapture(video_file)
23
+ total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
24
+ interval = max(1, total_frames // num_frames)
25
+ frames = []
26
+
27
+ for i in range(0, total_frames, interval):
28
+ video.set(cv2.CAP_PROP_POS_FRAMES, i)
29
+ ret, frame = video.read()
30
+ if not ret:
31
+ continue
32
+ pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
33
+ frames.append(pil_img)
34
+ if len(frames) == num_frames:
35
+ break
36
+
37
+ video.release()
38
+ return frames
39
+
40
+ @spaces.GPU
41
+ def bot_streaming(message, history):
42
+
43
+ txt = message.text
44
+ ext_buffer = f"USER: {txt} ASSISTANT: "
45
+
46
+ if message.files:
47
+ if len(message.files) == 1:
48
+ image = [message.files[0].path]
49
+ # interleaved images or video
50
+ elif len(message.files) > 1:
51
+ image = [msg.path for msg in message.files]
52
+ else:
53
+
54
+ def has_file_data(lst):
55
+ return any(isinstance(item, FileData) for sublist in lst if isinstance(sublist, tuple) for item in sublist)
56
+
57
+ def extract_paths(lst):
58
+ return [item.path for sublist in lst if isinstance(sublist, tuple) for item in sublist if isinstance(item, FileData)]
59
+
60
+ latest_text_only_index = -1
61
+
62
+ for i, item in enumerate(history):
63
+ if all(isinstance(sub_item, str) for sub_item in item):
64
+ latest_text_only_index = i
65
+
66
+ image = [path for i, item in enumerate(history) if i < latest_text_only_index and has_file_data(item) for path in extract_paths(item)]
67
+
68
+ if message.files is None:
69
+ gr.Error("You need to upload an image or video for LLaVA to work.")
70
+
71
+ video_extensions = ("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg")
72
+ image_extensions = Image.registered_extensions()
73
+ image_extensions = tuple([ex for ex, f in image_extensions.items()])
74
+ image_list = []
75
+ video_list = []
76
+
77
+ print("media", image)
78
+ if len(image) == 1:
79
+ if image[0].endswith(video_extensions):
80
+
81
+ video_list = sample_frames(image[0], 12)
82
+
83
+ prompt = f"USER: <video> {message.text} ASSISTANT:"
84
+ elif image[0].endswith(image_extensions):
85
+ image_list.append(Image.open(image[0]).convert("RGB"))
86
+ prompt = f"USER: <image> {message.text} ASSISTANT:"
87
+
88
+ elif len(image) > 1:
89
+ user_prompt = message.text
90
+
91
+ for img in image:
92
+ if img.endswith(image_extensions):
93
+ img = Image.open(img).convert("RGB")
94
+ image_list.append(img)
95
+
96
+ elif img.endswith(video_extensions):
97
+ video_list.append(sample_frames(img, 7))
98
+ print(len(video_list[-1]))
99
+ #for frame in sample_frames(img, 6):
100
+ #video_list.append(frame)
101
+
102
+ print("video_list", video_list)
103
+ image_tokens = ""
104
+ video_tokens = ""
105
+
106
+ if image_list != []:
107
+ image_tokens = "<image>" * len(image_list)
108
+ if video_list != []:
109
+
110
+ toks = len(video_list)
111
+ video_tokens = "<video>" * toks
112
+
113
+
114
+
115
+ prompt = f"USER: {image_tokens}{video_tokens} {user_prompt} ASSISTANT:"
116
+
117
+ print(prompt)
118
+ if image_list != [] and video_list != []:
119
+ inputs = processor(prompt, images=image_list, videos=video_list, return_tensors="pt").to("cuda",torch.float16)
120
+ elif image_list != [] and video_list == []:
121
+ inputs = processor(prompt, images=image_list, return_tensors="pt").to("cuda", torch.float16)
122
+ elif image_list == [] and video_list != []:
123
+ inputs = processor(prompt, videos=video_list, return_tensors="pt").to("cuda", torch.float16)
124
+
125
+
126
+ streamer = TextIteratorStreamer(processor, **{"max_new_tokens": 200, "skip_special_tokens": True, "clean_up_tokenization_spaces":True})
127
+ generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=100)
128
+ generated_text = ""
129
+
130
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
131
+ thread.start()
132
+
133
+
134
+
135
+ buffer = ""
136
+ for new_text in streamer:
137
+
138
+ buffer += new_text
139
+
140
+ generated_text_without_prompt = buffer[len(ext_buffer):][:-1]
141
+ time.sleep(0.01)
142
+ yield generated_text_without_prompt
143
+
144
+
145
+ demo = gr.ChatInterface(fn=bot_streaming, title="VideoLLaVA", examples=[
146
+ {"text": "The input contains two videos, are the cats in this video and this video doing the same thing?", "files":["./cats_1.mp4", "./cats_2.mp4"]},
147
+ {"text": "There are two images in the input. What is the relationship between this image and this image?", "files":["./rococo_1.jpg", "./rococo_2.jpg"]},
148
+ {"text": "What is the cat doing?", "files":["./cat.mp4"]},
149
+ {"text": "How to make this pastry?", "files":["./baklava.png"]}],
150
+ textbox=gr.MultimodalTextbox(file_count="multiple"),
151
+ description="Try [Video-LLaVA](https://huggingface.co/docs/transformers/main/en/model_doc/video_llava) in this demo. Upload an image or a video, and start chatting about it, or simply try one of the examples below. If you don't upload an image, you will receive an error. ",
152
+ stop_btn="Stop Generation", multimodal=True)
153
+ demo.launch(debug=True)