Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ import cv2
|
|
| 4 |
import numpy as np
|
| 5 |
from PIL import Image
|
| 6 |
import spaces
|
| 7 |
-
import
|
| 8 |
import os
|
| 9 |
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 10 |
import warnings
|
|
@@ -16,17 +16,17 @@ tokenizer = None
|
|
| 16 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
model_loaded = False
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
global model, tokenizer, model_loaded
|
| 22 |
|
| 23 |
try:
|
| 24 |
-
print("π Loading
|
| 25 |
|
| 26 |
-
|
| 27 |
-
model_name = "DAMO-NLP-SG/Video-LLaMA"
|
| 28 |
|
| 29 |
-
# Configure quantization
|
| 30 |
quantization_config = BitsAndBytesConfig(
|
| 31 |
load_in_4bit=True,
|
| 32 |
bnb_4bit_compute_dtype=torch.float16,
|
|
@@ -42,145 +42,85 @@ def load_videollama_model():
|
|
| 42 |
use_fast=False
|
| 43 |
)
|
| 44 |
|
| 45 |
-
# Add padding token if not present
|
| 46 |
if tokenizer.pad_token is None:
|
| 47 |
tokenizer.pad_token = tokenizer.eos_token
|
| 48 |
|
| 49 |
-
# Load model
|
| 50 |
-
print("Loading model...")
|
| 51 |
model = AutoModelForCausalLM.from_pretrained(
|
| 52 |
model_name,
|
| 53 |
quantization_config=quantization_config,
|
| 54 |
device_map="auto",
|
| 55 |
torch_dtype=torch.float16,
|
| 56 |
trust_remote_code=True,
|
| 57 |
-
low_cpu_mem_usage=True
|
|
|
|
| 58 |
)
|
| 59 |
|
| 60 |
model_loaded = True
|
| 61 |
-
|
| 62 |
-
|
|
|
|
| 63 |
|
| 64 |
except Exception as e:
|
| 65 |
model_loaded = False
|
| 66 |
-
error_msg = f"β
|
| 67 |
print(error_msg)
|
| 68 |
-
print("π Falling back to basic video analysis...")
|
| 69 |
return error_msg
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
"""Extract
|
| 73 |
try:
|
| 74 |
cap = cv2.VideoCapture(video_path)
|
|
|
|
| 75 |
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 76 |
-
|
| 77 |
-
duration = total_frames / fps if fps > 0 else 0
|
| 78 |
-
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 79 |
-
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 80 |
|
| 81 |
if total_frames == 0:
|
| 82 |
-
return [],
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
# Get evenly spaced frame indices
|
| 85 |
-
frame_indices = np.linspace(0, total_frames-1, min(max_frames, total_frames), dtype=int)
|
| 86 |
frames = []
|
| 87 |
-
|
| 88 |
|
| 89 |
-
for
|
| 90 |
-
cap.set(cv2.CAP_PROP_POS_FRAMES,
|
| 91 |
ret, frame = cap.read()
|
| 92 |
if ret:
|
| 93 |
# Convert BGR to RGB
|
| 94 |
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 95 |
-
# Resize
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
new_height = int(height * scale)
|
| 100 |
frame_rgb = cv2.resize(frame_rgb, (new_width, new_height))
|
| 101 |
|
| 102 |
frames.append(Image.fromarray(frame_rgb))
|
| 103 |
-
|
| 104 |
-
timestamps.append(timestamp)
|
| 105 |
|
| 106 |
cap.release()
|
| 107 |
|
| 108 |
video_info = {
|
| 109 |
-
"total_frames": total_frames,
|
| 110 |
-
"fps": fps,
|
| 111 |
"duration": duration,
|
| 112 |
-
"
|
| 113 |
-
"
|
|
|
|
|
|
|
| 114 |
}
|
| 115 |
|
| 116 |
-
return frames, video_info
|
| 117 |
|
| 118 |
except Exception as e:
|
| 119 |
print(f"Error extracting frames: {e}")
|
| 120 |
-
return [],
|
| 121 |
-
|
| 122 |
-
def generate_basic_analysis(video_info, question, frames):
|
| 123 |
-
"""Generate basic video analysis when model is not available"""
|
| 124 |
-
|
| 125 |
-
analysis_parts = []
|
| 126 |
-
|
| 127 |
-
# Video technical info
|
| 128 |
-
analysis_parts.append("πΉ **Video Information:**")
|
| 129 |
-
analysis_parts.append(f"- Duration: {video_info.get('duration', 0):.1f} seconds")
|
| 130 |
-
analysis_parts.append(f"- Resolution: {video_info.get('resolution', 'Unknown')}")
|
| 131 |
-
analysis_parts.append(f"- Frame rate: {video_info.get('fps', 0):.1f} FPS")
|
| 132 |
-
analysis_parts.append(f"- Total frames: {video_info.get('total_frames', 0)}")
|
| 133 |
-
analysis_parts.append(f"- Analyzed frames: {len(frames)}")
|
| 134 |
-
|
| 135 |
-
# Basic visual analysis
|
| 136 |
-
analysis_parts.append("\nπ¨ **Basic Visual Analysis:**")
|
| 137 |
-
|
| 138 |
-
if frames:
|
| 139 |
-
# Analyze first frame for basic info
|
| 140 |
-
first_frame = np.array(frames[0])
|
| 141 |
-
avg_brightness = np.mean(first_frame)
|
| 142 |
-
color_variance = np.var(first_frame)
|
| 143 |
-
|
| 144 |
-
analysis_parts.append(f"- Average brightness: {'Bright' if avg_brightness > 127 else 'Dark'}")
|
| 145 |
-
analysis_parts.append(f"- Color variance: {'High contrast' if color_variance > 1000 else 'Low contrast'}")
|
| 146 |
-
|
| 147 |
-
# Simple color analysis
|
| 148 |
-
r_avg = np.mean(first_frame[:,:,0])
|
| 149 |
-
g_avg = np.mean(first_frame[:,:,1])
|
| 150 |
-
b_avg = np.mean(first_frame[:,:,2])
|
| 151 |
-
|
| 152 |
-
dominant_color = "Red-tinted" if r_avg > max(g_avg, b_avg) + 20 else \
|
| 153 |
-
"Green-tinted" if g_avg > max(r_avg, b_avg) + 20 else \
|
| 154 |
-
"Blue-tinted" if b_avg > max(r_avg, g_avg) + 20 else \
|
| 155 |
-
"Balanced colors"
|
| 156 |
-
analysis_parts.append(f"- Color tone: {dominant_color}")
|
| 157 |
-
|
| 158 |
-
# Question-specific response
|
| 159 |
-
analysis_parts.append(f"\nβ **Your Question:** '{question}'")
|
| 160 |
-
analysis_parts.append("\nπ€ **Analysis Response:**")
|
| 161 |
-
|
| 162 |
-
# Generate contextual response based on question keywords
|
| 163 |
-
question_lower = question.lower()
|
| 164 |
-
|
| 165 |
-
if any(word in question_lower for word in ['what', 'describe', 'see']):
|
| 166 |
-
analysis_parts.append("Based on the extracted frames, this video contains visual content that has been processed and analyzed. ")
|
| 167 |
-
|
| 168 |
-
if any(word in question_lower for word in ['action', 'activity', 'doing', 'happening']):
|
| 169 |
-
analysis_parts.append("The video appears to show some form of activity or movement across the analyzed timepoints. ")
|
| 170 |
-
|
| 171 |
-
if any(word in question_lower for word in ['people', 'person', 'human']):
|
| 172 |
-
analysis_parts.append("The analysis would need to examine the frames for human presence and activities. ")
|
| 173 |
-
|
| 174 |
-
if any(word in question_lower for word in ['object', 'thing', 'item']):
|
| 175 |
-
analysis_parts.append("Object detection and identification would require deeper model analysis. ")
|
| 176 |
-
|
| 177 |
-
analysis_parts.append("\nβ οΈ **Note:** This is a basic analysis. For detailed AI-powered video understanding, the VideoLLaMA3 model needs to be properly loaded and configured.")
|
| 178 |
-
|
| 179 |
-
return "\n".join(analysis_parts)
|
| 180 |
|
| 181 |
@spaces.GPU
|
| 182 |
def analyze_video_with_ai(video_file, question, progress=gr.Progress()):
|
| 183 |
-
"""
|
| 184 |
|
| 185 |
if video_file is None:
|
| 186 |
return "β Please upload a video file first."
|
|
@@ -188,96 +128,174 @@ def analyze_video_with_ai(video_file, question, progress=gr.Progress()):
|
|
| 188 |
if not question.strip():
|
| 189 |
return "β Please enter a question about the video."
|
| 190 |
|
|
|
|
|
|
|
|
|
|
| 191 |
try:
|
| 192 |
-
progress(0.1, desc="
|
| 193 |
|
| 194 |
-
# Extract frames
|
| 195 |
-
frames, video_info
|
| 196 |
|
| 197 |
-
if not frames:
|
| 198 |
-
return "β Could not
|
| 199 |
|
| 200 |
-
progress(0.
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
| 218 |
|
| 219 |
-
#
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
-
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
except Exception as e:
|
| 227 |
-
|
|
|
|
|
|
|
| 228 |
|
| 229 |
def create_interface():
|
| 230 |
"""Create the Gradio interface"""
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
except:
|
| 236 |
-
print("Model loading failed, using basic analysis mode")
|
| 237 |
-
|
| 238 |
-
with gr.Blocks(title="VideoLLama3 Analyzer", theme=gr.themes.Soft()) as demo:
|
| 239 |
-
gr.Markdown("# π₯ VideoLLama3 Video Analysis Tool")
|
| 240 |
-
gr.Markdown("Upload a video and ask questions about its content!")
|
| 241 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
with gr.Row():
|
| 243 |
with gr.Column(scale=1):
|
| 244 |
video_input = gr.Video(
|
| 245 |
-
label="Upload Video (MP4, AVI, MOV)",
|
| 246 |
-
height=
|
| 247 |
)
|
| 248 |
question_input = gr.Textbox(
|
| 249 |
-
label="Ask
|
| 250 |
-
placeholder="What is happening in this video?",
|
| 251 |
-
lines=3
|
|
|
|
| 252 |
)
|
| 253 |
-
analyze_btn = gr.Button("π Analyze Video", variant="primary", size="lg")
|
| 254 |
|
| 255 |
with gr.Column(scale=1):
|
| 256 |
output = gr.Textbox(
|
| 257 |
-
label="Analysis Results",
|
| 258 |
-
lines=
|
| 259 |
-
max_lines=
|
|
|
|
| 260 |
)
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
"What activities are happening in this video?",
|
| 265 |
-
"Describe the people or objects you see.",
|
| 266 |
-
"What is the setting or location?",
|
| 267 |
-
"Summarize the main events.",
|
| 268 |
-
"What emotions or mood does this convey?"
|
| 269 |
-
]
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
|
| 276 |
with gr.Row():
|
| 277 |
-
for
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
|
|
|
| 281 |
analyze_btn.click(
|
| 282 |
analyze_video_with_ai,
|
| 283 |
inputs=[video_input, question_input],
|
|
@@ -286,7 +304,18 @@ def create_interface():
|
|
| 286 |
)
|
| 287 |
|
| 288 |
gr.Markdown("---")
|
| 289 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
return demo
|
| 292 |
|
|
|
|
| 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
|
|
|
|
| 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,
|
|
|
|
| 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."
|
|
|
|
| 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],
|
|
|
|
| 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 |
|