|
| 1 | +import numpy as np |
| 2 | +import cv2 |
| 3 | +import warnings |
| 4 | +import select |
| 5 | +import sys |
| 6 | +import openai |
| 7 | +import base64 |
| 8 | + |
| 9 | +warnings.filterwarnings("ignore") |
| 10 | + |
| 11 | +# Global variables for storing video frames and their respective times |
| 12 | +video_frames = [] |
| 13 | +frame_times = [] |
| 14 | +history_time = 0 |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | +client = openai.Client(api_key="EMPTY", base_url="xxx") |
| 19 | + |
| 20 | +def encode_image(frames): |
| 21 | + base64_frames = [] |
| 22 | + for frame in frames: |
| 23 | + # frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # Convert BGR to RGB |
| 24 | + _, buffer = cv2.imencode(".jpg", frame) |
| 25 | + buffer = base64.b64encode(buffer).decode("utf-8") |
| 26 | + base64_frames.append(buffer) |
| 27 | + return base64_frames |
| 28 | + |
| 29 | +# Function to send frames to the server and get a response |
| 30 | +def request_server(question, base64_frames): |
| 31 | + messages = [{"role": "user", "content": []}] |
| 32 | + for base64_frame in base64_frames: |
| 33 | + frame_format = { |
| 34 | + "type": "image_url", |
| 35 | + "image_url": {"url": f"data:image/jpeg;base64,{base64_frame}"}, |
| 36 | + "modalities": "video", |
| 37 | + } |
| 38 | + messages[0]["content"].append(frame_format) |
| 39 | + |
| 40 | + prompt = {"type": "text", "text": question} |
| 41 | + messages[0]["content"].append(prompt) |
| 42 | + |
| 43 | + video_request = client.chat.completions.create( |
| 44 | + model="llava-onevision-72b-ov", |
| 45 | + messages=messages, |
| 46 | + temperature=0, |
| 47 | + max_tokens=1024, |
| 48 | + ) |
| 49 | + |
| 50 | + return video_request.choices[0].message.content |
| 51 | + |
| 52 | + |
| 53 | +class Args: |
| 54 | + """ |
| 55 | + Class to store configuration arguments. |
| 56 | + """ |
| 57 | + def __init__(self, frame_limit=30, force_sample=False): |
| 58 | + self.frame_limit = frame_limit # Max number of frames to retrieve |
| 59 | + self.force_sample = force_sample # Whether to force uniform sampling |
| 60 | + |
| 61 | + |
| 62 | +# Function to capture frames from the camera until the user presses Enter |
| 63 | +def load_camera_frames_until_enter(args): |
| 64 | + global history_time # To maintain across multiple captures |
| 65 | + |
| 66 | + cap = cv2.VideoCapture(0) # 0 is the ID for the default camera |
| 67 | + if not cap.isOpened(): |
| 68 | + print("Error: Could not access the camera.") |
| 69 | + return None, None, None |
| 70 | + |
| 71 | + fps = cap.get(cv2.CAP_PROP_FPS) or 30 # Default to 30 FPS if unable to retrieve FPS |
| 72 | + frame_count = 0 |
| 73 | + |
| 74 | + print("Video capturing started. Press 'Enter' in the console to stop capturing.") |
| 75 | + |
| 76 | + while True: |
| 77 | + ret, frame = cap.read() |
| 78 | + if not ret: |
| 79 | + print("Error: Could not read frame from camera.") |
| 80 | + break |
| 81 | + |
| 82 | + frame_count += 1 |
| 83 | + cur_frame_time = frame_count / fps |
| 84 | + |
| 85 | + video_frames.append(frame) |
| 86 | + frame_times.append(cur_frame_time + history_time) |
| 87 | + |
| 88 | + # Display the frame |
| 89 | + cv2.imshow('Camera Feed', frame) |
| 90 | + |
| 91 | + # Add cv2.waitKey to ensure the window remains visible |
| 92 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 93 | + break |
| 94 | + |
| 95 | + # Check if user pressed 'Enter' in the console |
| 96 | + if sys.stdin in select.select([sys.stdin], [], [], 0)[0]: |
| 97 | + input() # Consume the "Enter" key press |
| 98 | + print("Video capture stopped.") |
| 99 | + break |
| 100 | + |
| 101 | + cap.release() |
| 102 | + cv2.destroyAllWindows() # Close the camera feed window |
| 103 | + |
| 104 | + history_time = frame_times[-1] if frame_times else history_time |
| 105 | + |
| 106 | + # Sample frames |
| 107 | + total_frames = len(video_frames) |
| 108 | + print(f"Total Frames Captured: {total_frames}") |
| 109 | + |
| 110 | + if total_frames > args.frame_limit: |
| 111 | + sample_indices = np.linspace(0, total_frames - 1, args.frame_limit, dtype=int) |
| 112 | + sampled_frames = [video_frames[i] for i in sample_indices] |
| 113 | + sampled_times = [frame_times[i] for i in sample_indices] |
| 114 | + else: |
| 115 | + sampled_frames = video_frames |
| 116 | + sampled_times = frame_times |
| 117 | + |
| 118 | + # import pdb; pdb.set_trace() |
| 119 | + frame_times_str = ",".join([f"{t:.2f}s" for t in sampled_times]) |
| 120 | + return np.array(sampled_frames), frame_times_str, history_time |
| 121 | + |
| 122 | + |
| 123 | +# Function to stream video, process it, and answer a user question |
| 124 | +def stream_camera_and_ask_question(args): |
| 125 | + video_frames, frame_times, video_time = load_camera_frames_until_enter(args) |
| 126 | + |
| 127 | + if video_frames is None: |
| 128 | + print("Error capturing video frames.") |
| 129 | + return |
| 130 | + |
| 131 | + question = input("Press the query for current video: ").strip().lower() |
| 132 | + |
| 133 | + print("question: ", question) |
| 134 | + image_base64 = encode_image(video_frames) |
| 135 | + # import pdb; pdb.set_trace() |
| 136 | + response = request_server(question, image_base64) |
| 137 | + |
| 138 | + print(f"Model's Answer: {response}") |
| 139 | + print(f"Video Duration: 0 to {video_time:.2f} seconds") |
| 140 | + print(f"Frame Times: {frame_times}") |
| 141 | + |
| 142 | + return response |
| 143 | + |
| 144 | + |
| 145 | +# Main loop to keep the system running and waiting for user input |
| 146 | +def main_loop(): |
| 147 | + question = "Please describe this video." |
| 148 | + args = Args(frame_limit=64, force_sample=True) |
| 149 | + |
| 150 | + while True: |
| 151 | + answer = stream_camera_and_ask_question(args) |
| 152 | + if answer is None: |
| 153 | + print("Exiting the loop.") |
| 154 | + break |
| 155 | + |
| 156 | + user_input = input("Press 'Enter' to capture again, or 'q' to quit: ").strip().lower() |
| 157 | + if user_input == "q": |
| 158 | + print("Quitting the demo.") |
| 159 | + break |
| 160 | + |
| 161 | + # Close all OpenCV windows after the user quits |
| 162 | + cv2.destroyAllWindows() |
| 163 | + |
| 164 | + |
| 165 | +if __name__ == "__main__": |
| 166 | + main_loop() |
0 commit comments