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
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import spaces
|
| 7 |
+
import tempfile
|
| 8 |
+
import os
|
| 9 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 10 |
+
import warnings
|
| 11 |
+
warnings.filterwarnings("ignore")
|
| 12 |
+
|
| 13 |
+
# Global variables
|
| 14 |
+
model = None
|
| 15 |
+
tokenizer = None
|
| 16 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
+
model_loaded = False
|
| 18 |
+
|
| 19 |
+
@spaces.GPU
|
| 20 |
+
def load_videollama3_model():
|
| 21 |
+
"""Load VideoLLaMA3 model with proper configuration"""
|
| 22 |
+
global model, tokenizer, model_loaded
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
print("π Loading VideoLLaMA3-7B model...")
|
| 26 |
+
|
| 27 |
+
model_name = "DAMO-NLP-SG/VideoLLaMA3-7B"
|
| 28 |
+
|
| 29 |
+
# Configure quantization to fit in GPU memory
|
| 30 |
+
quantization_config = BitsAndBytesConfig(
|
| 31 |
+
load_in_4bit=True,
|
| 32 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 33 |
+
bnb_4bit_use_double_quant=True,
|
| 34 |
+
bnb_4bit_quant_type="nf4"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# Load tokenizer
|
| 38 |
+
print("Loading tokenizer...")
|
| 39 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 40 |
+
model_name,
|
| 41 |
+
trust_remote_code=True,
|
| 42 |
+
use_fast=False
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
if tokenizer.pad_token is None:
|
| 46 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 47 |
+
|
| 48 |
+
# Load model
|
| 49 |
+
print("Loading VideoLLaMA3 model (this may take several minutes)...")
|
| 50 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 51 |
+
model_name,
|
| 52 |
+
quantization_config=quantization_config,
|
| 53 |
+
device_map="auto",
|
| 54 |
+
torch_dtype=torch.float16,
|
| 55 |
+
trust_remote_code=True,
|
| 56 |
+
low_cpu_mem_usage=True,
|
| 57 |
+
attn_implementation="flash_attention_2"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
model_loaded = True
|
| 61 |
+
success_msg = "β
VideoLLaMA3-7B model loaded successfully! You can now analyze videos with AI."
|
| 62 |
+
print(success_msg)
|
| 63 |
+
return success_msg
|
| 64 |
+
|
| 65 |
+
except Exception as e:
|
| 66 |
+
model_loaded = False
|
| 67 |
+
error_msg = f"β Failed to load VideoLLaMA3: {str(e)}"
|
| 68 |
+
print(error_msg)
|
| 69 |
+
return error_msg
|
| 70 |
+
|
| 71 |
+
def extract_video_frames(video_path, max_frames=16, target_fps=1):
|
| 72 |
+
"""Extract frames from video for VideoLLaMA3 processing"""
|
| 73 |
+
try:
|
| 74 |
+
cap = cv2.VideoCapture(video_path)
|
| 75 |
+
original_fps = cap.get(cv2.CAP_PROP_FPS)
|
| 76 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 77 |
+
duration = total_frames / original_fps if original_fps > 0 else 0
|
| 78 |
+
|
| 79 |
+
if total_frames == 0:
|
| 80 |
+
return [], None
|
| 81 |
+
|
| 82 |
+
# Calculate frame sampling
|
| 83 |
+
frame_interval = max(1, int(original_fps / target_fps))
|
| 84 |
+
frame_indices = list(range(0, total_frames, frame_interval))[:max_frames]
|
| 85 |
+
|
| 86 |
+
frames = []
|
| 87 |
+
valid_indices = []
|
| 88 |
+
|
| 89 |
+
for idx in frame_indices:
|
| 90 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
|
| 91 |
+
ret, frame = cap.read()
|
| 92 |
+
if ret:
|
| 93 |
+
# Convert BGR to RGB
|
| 94 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 95 |
+
# Resize to reasonable size for processing
|
| 96 |
+
height, width = frame_rgb.shape[:2]
|
| 97 |
+
if max(height, width) > 720:
|
| 98 |
+
scale = 720 / max(height, width)
|
| 99 |
+
new_height, new_width = int(height * scale), int(width * scale)
|
| 100 |
+
frame_rgb = cv2.resize(frame_rgb, (new_width, new_height))
|
| 101 |
+
|
| 102 |
+
frames.append(Image.fromarray(frame_rgb))
|
| 103 |
+
valid_indices.append(idx)
|
| 104 |
+
|
| 105 |
+
cap.release()
|
| 106 |
+
|
| 107 |
+
video_info = {
|
| 108 |
+
"duration": duration,
|
| 109 |
+
"original_fps": original_fps,
|
| 110 |
+
"total_frames": total_frames,
|
| 111 |
+
"extracted_frames": len(frames),
|
| 112 |
+
"resolution": f"{width}x{height}"
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
return frames, video_info
|
| 116 |
+
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"Error extracting frames: {e}")
|
| 119 |
+
return [], None
|
| 120 |
+
|
| 121 |
+
@spaces.GPU
|
| 122 |
+
def analyze_video_with_ai(video_file, question, progress=gr.Progress()):
|
| 123 |
+
"""Analyze video using VideoLLaMA3 model"""
|
| 124 |
+
|
| 125 |
+
if video_file is None:
|
| 126 |
+
return "β Please upload a video file first."
|
| 127 |
+
|
| 128 |
+
if not question.strip():
|
| 129 |
+
return "β Please enter a question about the video."
|
| 130 |
+
|
| 131 |
+
if not model_loaded:
|
| 132 |
+
return "β VideoLLaMA3 model is not loaded. Please click 'Load VideoLLaMA3 Model' first and wait for it to complete."
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
progress(0.1, desc="Extracting video frames...")
|
| 136 |
+
|
| 137 |
+
# Extract frames from video
|
| 138 |
+
frames, video_info = extract_video_frames(video_file, max_frames=16)
|
| 139 |
+
|
| 140 |
+
if not frames or video_info is None:
|
| 141 |
+
return "β Could not process video. Please check the video format and try again."
|
| 142 |
+
|
| 143 |
+
progress(0.3, desc="Preparing AI input...")
|
| 144 |
+
|
| 145 |
+
# Create a detailed prompt for video analysis
|
| 146 |
+
system_prompt = "You are VideoLLaMA3, an advanced AI assistant specialized in video understanding. Analyze the video frames and provide detailed, accurate responses about the video content."
|
| 147 |
+
|
| 148 |
+
user_prompt = f"""I have a video with the following specifications:
|
| 149 |
+
- Duration: {video_info['duration']:.1f} seconds
|
| 150 |
+
- Original FPS: {video_info['original_fps']:.1f}
|
| 151 |
+
- Total frames: {video_info['total_frames']}
|
| 152 |
+
- Analyzed frames: {video_info['extracted_frames']}
|
| 153 |
+
- Resolution: {video_info['resolution']}
|
| 154 |
+
|
| 155 |
+
Question: {question}
|
| 156 |
+
|
| 157 |
+
Please analyze the video content and provide a comprehensive answer based on what you observe in the video frames."""
|
| 158 |
+
|
| 159 |
+
progress(0.5, desc="Processing with VideoLLaMA3...")
|
| 160 |
+
|
| 161 |
+
# Prepare conversation format
|
| 162 |
+
conversation = f"System: {system_prompt}\n\nHuman: {user_prompt}\n\nAssistant:"
|
| 163 |
+
|
| 164 |
+
# Tokenize input
|
| 165 |
+
inputs = tokenizer(
|
| 166 |
+
conversation,
|
| 167 |
+
return_tensors="pt",
|
| 168 |
+
max_length=2048,
|
| 169 |
+
truncation=True,
|
| 170 |
+
padding=True
|
| 171 |
+
).to(device)
|
| 172 |
+
|
| 173 |
+
progress(0.7, desc="Generating AI response...")
|
| 174 |
+
|
| 175 |
+
# Generate response
|
| 176 |
+
with torch.no_grad():
|
| 177 |
+
output_ids = model.generate(
|
| 178 |
+
**inputs,
|
| 179 |
+
max_new_tokens=512,
|
| 180 |
+
temperature=0.7,
|
| 181 |
+
do_sample=True,
|
| 182 |
+
top_p=0.9,
|
| 183 |
+
repetition_penalty=1.1,
|
| 184 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 185 |
+
eos_token_id=tokenizer.eos_token_id
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# Decode response
|
| 189 |
+
full_response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 190 |
+
|
| 191 |
+
# Extract just the assistant's response
|
| 192 |
+
if "Assistant:" in full_response:
|
| 193 |
+
ai_response = full_response.split("Assistant:")[-1].strip()
|
| 194 |
+
else:
|
| 195 |
+
ai_response = full_response.split(conversation)[-1].strip()
|
| 196 |
+
|
| 197 |
+
progress(0.9, desc="Formatting results...")
|
| 198 |
+
|
| 199 |
+
# Format the final response
|
| 200 |
+
formatted_response = f"""π₯ **VideoLLaMA3 AI Video Analysis**
|
| 201 |
+
|
| 202 |
+
β **Your Question:**
|
| 203 |
+
{question}
|
| 204 |
+
|
| 205 |
+
π€ **AI Analysis:**
|
| 206 |
+
{ai_response}
|
| 207 |
+
|
| 208 |
+
π **Video Information:**
|
| 209 |
+
β’ Duration: {video_info['duration']:.1f} seconds
|
| 210 |
+
β’ Frame Rate: {video_info['original_fps']:.1f} FPS
|
| 211 |
+
β’ Total Frames: {video_info['total_frames']:,}
|
| 212 |
+
β’ Analyzed Frames: {video_info['extracted_frames']}
|
| 213 |
+
β’ Resolution: {video_info['resolution']}
|
| 214 |
+
|
| 215 |
+
β‘ **Powered by:** VideoLLaMA3-7B (Multimodal AI)
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
progress(1.0, desc="Analysis complete!")
|
| 219 |
+
|
| 220 |
+
return formatted_response
|
| 221 |
+
|
| 222 |
+
except torch.cuda.OutOfMemoryError:
|
| 223 |
+
torch.cuda.empty_cache()
|
| 224 |
+
return "β GPU memory error. Please try with a shorter video or restart the space."
|
| 225 |
+
except Exception as e:
|
| 226 |
+
error_msg = f"β Error during video analysis: {str(e)}"
|
| 227 |
+
print(error_msg)
|
| 228 |
+
return error_msg
|
| 229 |
+
|
| 230 |
+
def create_interface():
|
| 231 |
+
"""Create the Gradio interface"""
|
| 232 |
+
|
| 233 |
+
with gr.Blocks(title="VideoLLaMA3 AI Analyzer", theme=gr.themes.Soft()) as demo:
|
| 234 |
+
gr.Markdown("# π₯ VideoLLaMA3 AI Video Analysis Tool")
|
| 235 |
+
gr.Markdown("Upload videos and get detailed AI-powered analysis using VideoLLaMA3-7B!")
|
| 236 |
+
|
| 237 |
+
# Model loading section
|
| 238 |
+
with gr.Row():
|
| 239 |
+
with gr.Column(scale=3):
|
| 240 |
+
model_status = gr.Textbox(
|
| 241 |
+
label="π€ Model Status",
|
| 242 |
+
value="Model not loaded - Click the button to load VideoLLaMA3-7B β",
|
| 243 |
+
interactive=False,
|
| 244 |
+
lines=2
|
| 245 |
+
)
|
| 246 |
+
with gr.Column(scale=1):
|
| 247 |
+
load_btn = gr.Button("π Load VideoLLaMA3 Model", variant="primary", size="lg")
|
| 248 |
+
|
| 249 |
+
load_btn.click(load_videollama3_model, outputs=model_status)
|
| 250 |
+
|
| 251 |
+
gr.Markdown("---")
|
| 252 |
+
|
| 253 |
+
# Main interface
|
| 254 |
+
with gr.Row():
|
| 255 |
+
with gr.Column(scale=1):
|
| 256 |
+
video_input = gr.Video(
|
| 257 |
+
label="πΉ Upload Video (MP4, AVI, MOV, WebM)",
|
| 258 |
+
height=350
|
| 259 |
+
)
|
| 260 |
+
question_input = gr.Textbox(
|
| 261 |
+
label="β Ask about the video",
|
| 262 |
+
placeholder="What is happening in this video? Describe it in detail.",
|
| 263 |
+
lines=3,
|
| 264 |
+
max_lines=5
|
| 265 |
+
)
|
| 266 |
+
analyze_btn = gr.Button("π Analyze Video with AI", variant="primary", size="lg")
|
| 267 |
+
|
| 268 |
+
with gr.Column(scale=1):
|
| 269 |
+
output = gr.Textbox(
|
| 270 |
+
label="π― AI Analysis Results",
|
| 271 |
+
lines=25,
|
| 272 |
+
max_lines=30,
|
| 273 |
+
show_copy_button=True
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# Example questions
|
| 277 |
+
gr.Markdown("### π‘ Example Questions (click to use):")
|
| 278 |
+
|
| 279 |
+
example_questions = [
|
| 280 |
+
"What is happening in this video? Describe the scene in detail.",
|
| 281 |
+
"Who are the people in this video and what are they doing?",
|
| 282 |
+
"Describe the setting, location, and environment shown.",
|
| 283 |
+
"What objects, animals, or items can you see in the video?",
|
| 284 |
+
"What is the mood, atmosphere, or emotion conveyed?",
|
| 285 |
+
"Summarize the key events that occur chronologically."
|
| 286 |
+
]
|
| 287 |
+
|
| 288 |
+
with gr.Row():
|
| 289 |
+
for i in range(0, len(example_questions), 2):
|
| 290 |
+
with gr.Column():
|
| 291 |
+
if i < len(example_questions):
|
| 292 |
+
btn1 = gr.Button(example_questions[i], size="sm")
|
| 293 |
+
btn1.click(lambda x=example_questions[i]: x, outputs=question_input)
|
| 294 |
+
if i+1 < len(example_questions):
|
| 295 |
+
btn2 = gr.Button(example_questions[i+1], size="sm")
|
| 296 |
+
btn2.click(lambda x=example_questions[i+1]: x, outputs=question_input)
|
| 297 |
+
|
| 298 |
+
# Connect the analyze button
|
| 299 |
+
analyze_btn.click(
|
| 300 |
+
analyze_video_with_ai,
|
| 301 |
+
inputs=[video_input, question_input],
|
| 302 |
+
outputs=output,
|
| 303 |
+
show_progress=True
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
gr.Markdown("---")
|
| 307 |
+
gr.Markdown("""
|
| 308 |
+
### π Instructions:
|
| 309 |
+
1. **First:** Click "Load VideoLLaMA3 Model" and wait for it to complete (~5-10 minutes)
|
| 310 |
+
2. **Then:** Upload your video file (keep it under 2 minutes for best results)
|
| 311 |
+
3. **Ask:** Type your question about the video content
|
| 312 |
+
4. **Analyze:** Click "Analyze Video with AI" to get detailed insights
|
| 313 |
+
|
| 314 |
+
π‘ **Tips:**
|
| 315 |
+
- Shorter videos (30s-2min) work best
|
| 316 |
+
- Ask specific questions for better results
|
| 317 |
+
- Try different question styles to explore the AI's capabilities
|
| 318 |
+
""")
|
| 319 |
+
|
| 320 |
+
return demo
|
| 321 |
+
|
| 322 |
+
if __name__ == "__main__":
|
| 323 |
+
demo = create_interface()
|
| 324 |
+
demo.launch()
|