v0.0.2
This commit is contained in:
parent
589d108338
commit
744c89aa8f
Binary file not shown.
@ -26,157 +26,86 @@ RECORD_DURATION = 60 # 1 минута
|
||||
read_task_lock = asyncio.Lock()
|
||||
|
||||
class VideoConsumer(AsyncWebsocketConsumer):
|
||||
# async def connect(self):
|
||||
# global read_task
|
||||
# await self.accept()
|
||||
# clients.add(self)
|
||||
|
||||
# async with read_task_lock:
|
||||
# if read_task is None or read_task.done():
|
||||
# read_task = asyncio.create_task(read_rtsp_stream())
|
||||
|
||||
# self.send_task = asyncio.create_task(self.send_frames())
|
||||
|
||||
async def connect(self):
|
||||
global read_task
|
||||
await self.accept()
|
||||
self.container = av.open(
|
||||
VIDEO_RTSP, 'r',
|
||||
options={
|
||||
'rtsp_transport': 'tcp',
|
||||
'fflags': 'nobuffer',
|
||||
'flags': 'low_delay',
|
||||
'stimeout': '100000',
|
||||
'max_delay': '100000',
|
||||
}
|
||||
)
|
||||
self.video_stream = next(s for s in self.container.streams if s.type == 'video')
|
||||
self.recording_process = None
|
||||
asyncio.create_task(self.send_frames())
|
||||
clients.add(self)
|
||||
|
||||
async with read_task_lock:
|
||||
if read_task is None or read_task.done():
|
||||
read_task = asyncio.create_task(read_rtsp_stream())
|
||||
|
||||
self.send_task = asyncio.create_task(self.send_frames())
|
||||
|
||||
async def disconnect(self, close_code):
|
||||
clients.discard(self)
|
||||
# try:
|
||||
# if self.send_task:
|
||||
# self.send_task.cancel()
|
||||
# await self.send_task
|
||||
# except asyncio.CancelledError:
|
||||
# pass
|
||||
|
||||
|
||||
async def receive(self, text_data):
|
||||
try:
|
||||
data = json.loads(text_data)
|
||||
mark_type = data.get("type")
|
||||
crop_x = data.get("cropX")
|
||||
crop_y = data.get("cropY")
|
||||
crop_w = data.get("cropW")
|
||||
crop_h = data.get("cropH")
|
||||
self.send_task.cancel()
|
||||
await self.send_task
|
||||
except Exception:
|
||||
return
|
||||
pass
|
||||
|
||||
if mark_type in ["good", "bad"]:
|
||||
folder = f"media/{mark_type}_clips"
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
filename = os.path.join(folder, f"{mark_type}_{timestamp}.mp4")
|
||||
|
||||
if self.recording_process:
|
||||
self.recording_process.terminate()
|
||||
|
||||
crop_filter = f"crop={crop_w}:{crop_h}:{crop_x}:{crop_y}"
|
||||
self.recording_process = subprocess.Popen([
|
||||
"ffmpeg",
|
||||
"-rtsp_transport", "tcp",
|
||||
"-i", VIDEO_RTSP,
|
||||
"-t", str(RECORD_DURATION),
|
||||
"-an",
|
||||
"-vf", crop_filter,
|
||||
"-c:v", "libx264",
|
||||
"-preset", "veryfast",
|
||||
filename
|
||||
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
await self.send(text_data="recording_started")
|
||||
|
||||
|
||||
# async def send_frames(self):
|
||||
# while True:
|
||||
# try:
|
||||
# jpeg_data = await video_frame_queue.get()
|
||||
# frame = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||
|
||||
# # Обработка кадра
|
||||
# cropped = frame[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w]
|
||||
# results = model.predict(source=cropped, save=False, verbose=False)
|
||||
|
||||
# predicted_class = results[0].names[results[0].probs.top1]
|
||||
# confidence = results[0].probs.top1conf.item()
|
||||
# label = f"{predicted_class}: {confidence:.2f}"
|
||||
# cv2.putText(frame, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
||||
|
||||
# _, jpeg = cv2.imencode('.jpg', frame)
|
||||
# frame_data = base64.b64encode(jpeg.tobytes()).decode('utf-8')
|
||||
# await self.send(text_data=frame_data)
|
||||
|
||||
# await asyncio.sleep(0.04) # 25 fps
|
||||
|
||||
# except Exception as e:
|
||||
# print("frame error:", e)
|
||||
# await asyncio.sleep(1)
|
||||
async def send_frames(self):
|
||||
from .models import AllowedColor
|
||||
start_time = None
|
||||
start_read = None
|
||||
|
||||
while True:
|
||||
try:
|
||||
for packet in self.container.demux(self.video_stream):
|
||||
for frame in packet.decode():
|
||||
if start_time is None:
|
||||
start_time = time.time()
|
||||
start_read = frame.time
|
||||
jpeg_data = await video_frame_queue.get()
|
||||
img = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||
|
||||
if (time.time() - start_time) - (frame.time - start_read) > 0.3:
|
||||
continue
|
||||
# Обработка нейросетью
|
||||
cropped = img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w]
|
||||
results = model.predict(source=cropped, save=False, verbose=False)
|
||||
predicted_class = results[0].names[results[0].probs.top1]
|
||||
|
||||
img = frame.to_ndarray(format='bgr24')
|
||||
cropped = img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w]
|
||||
results = model.predict(source=cropped, save=False, verbose=False)
|
||||
allowed_color = await asyncio.to_thread(
|
||||
lambda: AllowedColor.objects.filter(name=predicted_class).first()
|
||||
)
|
||||
|
||||
predicted_class = results[0].names[results[0].probs.top1]
|
||||
allowed_color = await asyncio.to_thread(
|
||||
lambda: AllowedColor.objects.filter(name=predicted_class).first())
|
||||
|
||||
if allowed_color and not allowed_color.allowed:
|
||||
print(f"⚠️ Обнаружен запрещённый цвет: {predicted_class}")
|
||||
# await self.send(text_data=json.dumps({"alert": f"Запрещённый цвет: {predicted_class}"}))
|
||||
|
||||
confidence = results[0].probs.top1conf.item()
|
||||
|
||||
label = f"{predicted_class}: {confidence:.2f}"
|
||||
|
||||
cv2.putText(img, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
||||
if allowed_color and not allowed_color.allowed:
|
||||
await self.send(text_data=json.dumps({
|
||||
"status": "danger",
|
||||
"message": f"Запрещённый цвет: {predicted_class}"
|
||||
}))
|
||||
else:
|
||||
await self.send(text_data=json.dumps({
|
||||
"status": "ok",
|
||||
"message": "Всё хорошо"
|
||||
}))
|
||||
|
||||
_, jpeg = cv2.imencode('.jpg', img)
|
||||
frame_data = base64.b64encode(jpeg.tobytes()).decode('utf-8')
|
||||
await self.send(text_data=frame_data)
|
||||
await asyncio.sleep(0.04)
|
||||
confidence = results[0].probs.top1conf.item()
|
||||
label = f"{predicted_class}: {confidence:.2f}"
|
||||
cv2.putText(img, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
||||
|
||||
_, jpeg = cv2.imencode('.jpg', img)
|
||||
frame_data = base64.b64encode(jpeg.tobytes()).decode('utf-8')
|
||||
await self.send(text_data=frame_data)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
print("frame error: ", e)
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
print(f"[SEND_FRAME ERROR]: {e}")
|
||||
await asyncio.sleep(0.04)
|
||||
|
||||
|
||||
async def read_rtsp_stream():
|
||||
global read_task
|
||||
try:
|
||||
container = av.open(
|
||||
VIDEO_RTSP, 'r', options={
|
||||
'rtsp_transport': 'tcp',
|
||||
'fflags': 'nobuffer',
|
||||
'flags': 'low_delay',
|
||||
'stimeout': '10000000',
|
||||
'max_delay': '10000000',
|
||||
})
|
||||
video_stream = next(s for s in container.streams if s.type == 'video')
|
||||
|
||||
while clients:
|
||||
try:
|
||||
container = av.open(settings.RTSP_URL)
|
||||
video_stream = container.streams.video[0]
|
||||
|
||||
for frame in container.decode(video_stream):
|
||||
for packet in container.demux(video_stream):
|
||||
for frame in packet.decode():
|
||||
img = frame.to_ndarray(format='bgr24')
|
||||
|
||||
# Сжимаем в JPEG
|
||||
ret, jpeg = cv2.imencode('.jpg', img)
|
||||
if not ret:
|
||||
continue
|
||||
@ -185,7 +114,6 @@ async def read_rtsp_stream():
|
||||
await video_frame_queue.get()
|
||||
await video_frame_queue.put(jpeg.tobytes())
|
||||
|
||||
await asyncio.sleep(0.03) # ~30 fps
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR] RTSP reader: {e}")
|
||||
await asyncio.sleep(0.03)
|
||||
except Exception as e:
|
||||
print(f"[RTSP ERROR] {e}")
|
||||
@ -35,6 +35,9 @@
|
||||
<button onclick="markBad()">Плохая жижа</button>
|
||||
|
||||
<div id="status" style="color:red; font-weight:bold; margin-top:10px;"></div>
|
||||
<div id="color-status" style="width: 300px; height: 40px; background-color: green; color: white; text-align: center; line-height: 40px; font-weight: bold;">
|
||||
Всё хорошо
|
||||
</div>
|
||||
<script>
|
||||
let socket = new WebSocket("ws://localhost:8000/ws/stream/");
|
||||
let statusDiv = document.getElementById("status");
|
||||
@ -101,6 +104,22 @@
|
||||
document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data;
|
||||
}
|
||||
};
|
||||
|
||||
socket.onmessage = event => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
if (data.status === "danger") {
|
||||
document.getElementById("color-status").style.backgroundColor = "red";
|
||||
document.getElementById("color-status").innerText = data.message;
|
||||
} else if (data.status === "ok") {
|
||||
document.getElementById("color-status").style.backgroundColor = "green";
|
||||
document.getElementById("color-status").innerText = data.message;
|
||||
}
|
||||
} catch {
|
||||
document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data;
|
||||
}
|
||||
};
|
||||
|
||||
// socket.onmessage = function(event) {
|
||||
// const data = event.data;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user