tomerk commited on
Commit
861698e
·
verified ·
1 Parent(s): 97e700a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +245 -0
app.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import time
4
+ import openai
5
+ import base64
6
+ import pytz
7
+ import uuid
8
+ from threading import Thread
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ from datetime import datetime
11
+ import json
12
+ import os
13
+ from moviepy.editor import ImageSequenceClip
14
+ from gradio_client import Client, file
15
+ # https://16d3-2a0d-6fc2-61b1-8500-5d45-b385-9a4d-5522.ngrok-free.app/video_feed
16
+ # rtsp://admin:Conntour1!@eu.loclx.io:5678/Streaming/Channels/101
17
+
18
+ import os
19
+
20
+ api_key = os.getenv("OPEN_AI_KEY")
21
+ user_name = os.getenv("USER_NAME")
22
+ password = os.getenv("PASSWORD")
23
+
24
+ LENGTH = 5
25
+ WEBCAM = 0
26
+
27
+ MARKDOWN = """
28
+ # Conntour
29
+ """
30
+ AVATARS = (
31
+ "https://assets-global.website-files.com/63d6dca820934a77a340f31e/63dfb7a21b4c08282d524010_pyramid.png",
32
+ "https://media.roboflow.com/spaces/openai-white-logomark.png"
33
+ )
34
+
35
+ # Set your OpenAI API key
36
+ openai.api_key = api_key
37
+ MODEL="gpt-4o"
38
+ client = openai.OpenAI(api_key=api_key)
39
+
40
+ # Global variable to stop the video capture loop
41
+ stop_capture = False
42
+ alerts_mode = True
43
+
44
+
45
+ def encode_to_video(frames, fps):
46
+ os.makedirs('videos', exist_ok=True)
47
+ video_clip_path = f"videos/{uuid.uuid4()}.mp4"
48
+
49
+ # Create a video clip from the frames using moviepy
50
+ clip = ImageSequenceClip([frame[:, :, ::-1] for frame in frames], fps=fps) # Convert from BGR to RGB
51
+ clip.write_videofile(video_clip_path, codec="libx264")
52
+
53
+ # Convert the video file to base64
54
+ with open(video_clip_path, "rb") as video_file:
55
+ video_data = base64.b64encode(video_file.read()).decode('utf-8')
56
+
57
+ return video_clip_path
58
+
59
+ # Function to process video frames using GPT-4 API
60
+ def process_frames(frames, frames_to_skip = 1):
61
+ os.makedirs('saved_frames', exist_ok=True)
62
+ curr_frame=0
63
+ base64Frames = []
64
+ while curr_frame < len(frames) - 1:
65
+ _, buffer = cv2.imencode(".jpg", frames[curr_frame])
66
+ base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
67
+ curr_frame += frames_to_skip
68
+ return base64Frames
69
+
70
+ # Function to check condition using GPT-4 API
71
+ def check_condition(prompt, base64Frames):
72
+ start_time = time.time()
73
+ print('checking condition for frames:', len(base64Frames))
74
+
75
+ # Save frames as images
76
+
77
+
78
+ messages = [
79
+ {"role": "system", "content": """You are analyzing video frames to check if the user's condition is met.
80
+ Please respond with a JSON object in the following format:
81
+ {"condition_met": true/false, "details": "optional details or summary"}"""},
82
+ {"role": "user", "content": [prompt, *map(lambda x: {"type": "image_url", "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames)]}
83
+ ]
84
+ response = client.chat.completions.create(
85
+ model="gpt-4o",
86
+ messages=messages,
87
+ temperature=0,
88
+ response_format={ "type": "json_object" }
89
+ )
90
+
91
+ end_time = time.time()
92
+ processing_time = end_time - start_time
93
+ frames_count = len(base64Frames)
94
+ api_response = response.choices[0].message.content
95
+ try:
96
+ jsonNew = json.loads(api_response)
97
+ print('result', response.usage.total_tokens, jsonNew)
98
+ return frames_count, processing_time, jsonNew
99
+ except:
100
+ print('result', response.usage.total_tokens, api_response)
101
+ return frames_count, processing_time, api_response
102
+
103
+
104
+ # Function to process video clip and update the chatbot
105
+ def process_clip(prompt, frames, chatbot):
106
+ # Print current time in Israel
107
+ israel_tz = pytz.timezone('Asia/Jerusalem')
108
+ start_time = datetime.now(israel_tz).strftime('%H:%M:%S')
109
+ print("[Start]:", start_time, len(frames))
110
+
111
+ # Encode frames into a video clip
112
+ fps = int(len(frames) / LENGTH)
113
+ base64Frames = process_frames(frames, fps)
114
+ frames_count, processing_time, api_response = check_condition(prompt, base64Frames)
115
+
116
+ if api_response["condition_met"] == True:
117
+ finish_time = datetime.now(israel_tz).strftime('%H:%M:%S')
118
+ video_clip_path = encode_to_video(frames, fps)
119
+ chatbot.append(((video_clip_path,), None))
120
+ result = f"Time: {start_time}\n"
121
+ chatbot.append((result, None))
122
+
123
+ frame_paths = []
124
+ for i, base64_frame in enumerate(base64Frames):
125
+ frame_data = base64.b64decode(base64_frame)
126
+ frame_path = f'saved_frames/frame_{uuid.uuid4()}.jpg'
127
+ with open(frame_path, "wb") as f:
128
+ f.write(frame_data)
129
+ frame_paths.append(frame_path)
130
+
131
+ def process_clip_from_file(prompt, frames, chatbot, fps):
132
+ global stop_capture
133
+ if not stop_capture:
134
+ israel_tz = pytz.timezone('Asia/Jerusalem')
135
+ start_time = datetime.now(israel_tz).strftime('%H:%M:%S')
136
+ print("[Start]:", start_time, len(frames))
137
+
138
+ fps = 20
139
+ frames_to_skip = int(fps * 1)
140
+ base64Frames = process_frames(frames, frames_to_skip)
141
+ frames_count, processing_time, api_response = check_condition(prompt, base64Frames)
142
+
143
+ result = None
144
+ if api_response and api_response.get("condition_met", False):
145
+ video_clip_path = encode_to_video(frames, fps)
146
+ chatbot.append(((video_clip_path,), None))
147
+ chatbot.append((f"Time: {start_time}\nDetails: {api_response.get('details', '')}", None))
148
+
149
+ return chatbot
150
+
151
+ # Function to capture video frames
152
+ def analyze_stream(prompt, stream, chatbot):
153
+ global stop_capture
154
+ stop_capture = False
155
+
156
+
157
+ cap = cv2.VideoCapture(stream or WEBCAM)
158
+
159
+ frames = []
160
+ start_time = time.time()
161
+ while not stop_capture:
162
+ ret, frame = cap.read()
163
+ if not ret:
164
+ break
165
+ frames.append(frame)
166
+
167
+ # Sample the frames every 5 seconds
168
+ if time.time() - start_time >= LENGTH:
169
+ # Start a new thread for processing the video clip
170
+ Thread(target=process_clip, args=(prompt, frames.copy(), chatbot,)).start()
171
+ frames = []
172
+ start_time = time.time()
173
+ yield chatbot
174
+
175
+ cap.release()
176
+ return chatbot
177
+
178
+ def analyze_video_file(prompt, video_path, chatbot):
179
+ global stop_capture
180
+ stop_capture = False # Reset the stop flag when analysis starts
181
+
182
+ cap = cv2.VideoCapture(video_path)
183
+
184
+ # Get video properties
185
+ fps = int(cap.get(cv2.CAP_PROP_FPS)) # Frames per second
186
+ frames_per_chunk = fps * LENGTH # Number of frames per 5-second chunk
187
+
188
+ frames = []
189
+
190
+ # Create a thread pool for concurrent processing
191
+ with ThreadPoolExecutor(max_workers=4) as executor:
192
+ futures = []
193
+
194
+ while not stop_capture:
195
+ ret, frame = cap.read()
196
+ if not ret:
197
+ break
198
+ frames.append(frame)
199
+
200
+ # Split the video into chunks of frames corresponding to 5 seconds
201
+ if len(frames) >= frames_per_chunk:
202
+ futures.append(executor.submit(process_clip_from_file, prompt, frames.copy(), chatbot, fps))
203
+ frames = []
204
+
205
+ # If any remaining frames that are less than 5 seconds, process them as a final chunk
206
+ if len(frames) > 0:
207
+ futures.append(executor.submit(process_clip_from_file, prompt, frames.copy(), chatbot, fps))
208
+
209
+ cap.release()
210
+ # Yield results as soon as each thread completes
211
+ for future in as_completed(futures):
212
+ result = future.result()
213
+ yield result
214
+ return chatbot
215
+
216
+
217
+ # Function to stop video capture
218
+ def stop_capture_func():
219
+ global stop_capture
220
+ stop_capture = True
221
+
222
+ # Gradio interface
223
+ with gr.Blocks(title="Conntour", fill_height=True) as demo:
224
+ with gr.Tab("Analyze"):
225
+ with gr.Row():
226
+ video = gr.Video(label="Video Source")
227
+ with gr.Column():
228
+ chatbot = gr.Chatbot(label="Events", bubble_full_width=False, avatar_images=AVATARS)
229
+ prompt = gr.Textbox(label="Enter your prompt alert")
230
+ start_btn = gr.Button("Start")
231
+ stop_btn = gr.Button("Stop")
232
+ start_btn.click(analyze_video_file, inputs=[prompt, video, chatbot], outputs=[chatbot], queue=True)
233
+ stop_btn.click(stop_capture_func)
234
+ with gr.Tab("Alerts"):
235
+ with gr.Row():
236
+ stream = gr.Textbox(label="Video Source", value="https://streamapi2.eu.loclx.io/video_feed/101 OR rtsp://admin:Conntour1!@eu.loclx.io:5678/Streaming/Channels/101")
237
+ with gr.Column():
238
+ chatbot = gr.Chatbot(label="Events", bubble_full_width=False, avatar_images=AVATARS)
239
+ prompt = gr.Textbox(label="Enter your prompt alert")
240
+ start_btn = gr.Button("Start")
241
+ stop_btn = gr.Button("Stop")
242
+ start_btn.click(analyze_stream, inputs=[prompt, stream, chatbot], outputs=[chatbot], queue=True)
243
+ stop_btn.click(stop_capture_func)
244
+
245
+ demo.launch(favicon_path='favicon.ico', auth=(user_name, password))