cosmo3769 commited on
Commit
4a620fb
·
verified ·
1 Parent(s): 2f46675

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
3
+ from PIL import Image
4
+ import cv2
5
+ import torch
6
+
7
+ # Load model and processor
8
+ mix_model_id = "google/paligemma-3b-mix-224"
9
+ mix_model = PaliGemmaForConditionalGeneration.from_pretrained(mix_model_id)
10
+ mix_processor = AutoProcessor.from_pretrained(mix_model_id)
11
+
12
+ # Define function to extract frames from the video
13
+ def extract_frames(video_path, frame_interval=1):
14
+ # Open the video file
15
+ vidcap = cv2.VideoCapture(video_path)
16
+ frames = []
17
+ success, image = vidcap.read()
18
+ count = 0
19
+
20
+ while success:
21
+ # Capture a frame at the specified interval
22
+ if count % frame_interval == 0:
23
+ frames.append(image)
24
+ success, image = vidcap.read()
25
+ count += 1
26
+
27
+ vidcap.release()
28
+ return frames
29
+
30
+ # Define function to generate captions for a video
31
+ def process_video(video, prompt):
32
+ # Use video directly as the path (video is passed as a string)
33
+ frames = extract_frames(video, frame_interval=10) # Extract frames at intervals
34
+
35
+ captions = []
36
+
37
+ for frame in frames:
38
+ # Convert frame to PIL Image and process it (assuming mix_processor handles PIL Image)
39
+ image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
40
+ inputs = mix_processor(image.convert("RGB"), prompt, return_tensors="pt")
41
+
42
+ try:
43
+ # Generate output from the model for each frame
44
+ output = mix_model.generate(**inputs, max_new_tokens=20)
45
+
46
+ # Decode and store the output for the frame
47
+ decoded_output = mix_processor.decode(output[0], skip_special_tokens=True)
48
+ captions.append(decoded_output[len(prompt):]) # Remove prompt part from the output
49
+ except IndexError as e:
50
+ print(f"IndexError: {e}")
51
+ captions.append("Error processing frame")
52
+
53
+ # Combine all frame captions into a coherent video description
54
+ return " ".join(captions)
55
+
56
+ # Define Gradio interface for video captioning
57
+ inputs = [
58
+ gr.Video(label="Upload Video"),
59
+ gr.Textbox(label="Prompt", placeholder="Enter your question")
60
+ ]
61
+ outputs = gr.Textbox(label="Generated Caption")
62
+
63
+ # Create the Gradio app for video captioning
64
+ demo = gr.Interface(fn=process_video, inputs=inputs, outputs=outputs, title="Video Captioning with Mix PaliGemma Model",
65
+ description="Upload a video and get captions based on your prompt.")
66
+
67
+ # Launch the app
68
+ demo.launch(debug=True)