Files

318 lines
11 KiB
Python
Raw Permalink Normal View History

import os
import sys
import json
import time
import threading
import cv2
import numpy as np
import requests
from flask import Flask, render_template, Response, request, jsonify
from ultralytics import YOLO, YOLOE
import ollama_client
models_dir = os.path.expanduser("~")
SIZES = ["n", "s", "m", "l", "x"]
def _make_models():
models = []
for size in SIZES:
models.append({"name": f"YOLO26{size} (detect)", "path": os.path.join(models_dir, f"yolo26{size}.pt"), "type": "yolo", "task": "detect"})
models.append({"name": f"YOLO26{size}-seg", "path": os.path.join(models_dir, f"yolo26{size}-seg.pt"), "type": "yolo", "task": "segment"})
models.append({"name": f"YOLO26{size}-cls", "path": os.path.join(models_dir, f"yolo26{size}-cls.pt"), "type": "yolo", "task": "classify"})
models.append({"name": f"YOLO26{size}-pose", "path": os.path.join(models_dir, f"yolo26{size}-pose.pt"), "type": "yolo", "task": "pose"})
models.append({"name": f"YOLO26{size}-obb", "path": os.path.join(models_dir, f"yolo26{size}-obb.pt"), "type": "yolo", "task": "obb"})
for size in SIZES[:4]:
models.append({"name": f"YOLOE-26{size}-seg", "path": os.path.join(models_dir, f"yoloe-26{size}-seg.pt"), "type": "yoloe", "task": "segment"})
models.append({"name": f"YOLOE-26{size}-seg-pf", "path": os.path.join(models_dir, f"yoloe-26{size}-seg-pf.pt"), "type": "yolo", "task": "segment"})
return models
AVAILABLE_MODELS = _make_models()
app = Flask(__name__)
lock = threading.Lock()
latest_frame = None
frame_ready = threading.Event()
current_model_name = "YOLO26n"
current_model_path = os.path.join(models_dir, "yolo26n.pt")
current_model_type = "yolo"
model = None
rtsp_source = "rtsp://192.168.2.72:80/h264ESVideoTest"
fps_value = 0
detection_count = 0
running = True
tracking = False
processing_thread = None
cap = None
llm_model = ollama_client.DEFAULT_MODEL
def load_model(model_path, model_type):
global model
try:
if model_type == "yoloe":
model = YOLOE(model_path)
else:
model = YOLO(model_path)
return True
except Exception as e:
print(f"Failed to load model {model_path}: {e}")
return False
def open_capture(source):
global cap
if cap is not None:
cap.release()
time.sleep(0.5)
cap = cv2.VideoCapture(source)
return cap.isOpened()
def process_stream():
global latest_frame, frame_ready, fps_value, detection_count, running, model, cap
global current_model_path, current_model_type, current_model_name, rtsp_source, tracking
if not load_model(current_model_path, current_model_type):
return
if not open_capture(rtsp_source):
print("Failed to open RTSP source")
return
fps_start = time.time()
frame_count = 0
while running:
new_model_path = None
new_model_type = None
new_source = None
with lock:
pending = getattr(process_stream, "_pending_model", None)
if pending is not None:
new_model_path = pending["path"]
new_model_type = pending["type"]
new_model_name = pending["name"]
process_stream._pending_model = None
src = getattr(process_stream, "_pending_source", None)
if src is not None:
new_source = src
process_stream._pending_source = None
if new_source:
with lock:
rtsp_source = new_source
latest_frame = None
frame_ready.set()
for attempt in range(30):
if open_capture(new_source):
break
print(f"Retrying RTSP connection ({attempt+1}/30)...")
time.sleep(1)
else:
print("Failed to open new RTSP source after 30 attempts")
if new_model_path:
print(f"Switching to model: {new_model_name}")
if load_model(new_model_path, new_model_type):
with lock:
current_model_path = new_model_path
current_model_type = new_model_type
current_model_name = new_model_name
if cap is None or not cap.isOpened():
time.sleep(1)
continue
success, frame = cap.read()
if not success:
print("Failed to read frame, reconnecting...")
cap.release()
time.sleep(1)
open_capture(rtsp_source)
continue
frame = cv2.resize(frame, (640, 480))
try:
with lock:
do_track = tracking
if do_track:
results = model.track(frame, persist=True)
else:
results = model(frame)
annotated = results[0].plot()
box_attr = getattr(results[0], 'boxes', None)
detected = len(box_attr) if box_attr is not None else 0
_, jpeg = cv2.imencode('.jpg', annotated, [cv2.IMWRITE_JPEG_QUALITY, 80])
with lock:
latest_frame = jpeg.tobytes()
detection_count = detected
frame_ready.set()
except Exception as e:
print(f"Inference error: {e}")
_, jpeg = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 80])
with lock:
latest_frame = jpeg.tobytes()
frame_ready.set()
frame_count += 1
elapsed = time.time() - fps_start
if elapsed >= 2.0:
with lock:
fps_value = frame_count / elapsed
frame_count = 0
fps_start = time.time()
if cap:
cap.release()
def queue_model_switch(name, path, mtype):
with lock:
process_stream._pending_model = {"name": name, "path": path, "type": mtype}
def queue_source_change(source):
with lock:
process_stream._pending_source = source
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video_feed')
def video_feed():
def generate():
while True:
if frame_ready.wait(timeout=5):
frame_ready.clear()
with lock:
if latest_frame is not None:
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + latest_frame + b'\r\n')
else:
# keep connection alive if no frame yet
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n\r\n')
return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/api/models', methods=['GET'])
def get_models():
return jsonify({"models": AVAILABLE_MODELS, "current": current_model_name})
@app.route('/api/models', methods=['POST'])
def switch_model():
data = request.get_json()
name = data.get("name")
for m in AVAILABLE_MODELS:
if m["name"] == name or m["path"] == name:
queue_model_switch(m["name"], m["path"], m["type"])
return jsonify({"status": "ok", "model": m["name"]})
return jsonify({"status": "error", "message": "Model not found"}), 400
@app.route('/api/source', methods=['POST'])
def change_source():
data = request.get_json()
url = data.get("url")
if url:
queue_source_change(url)
return jsonify({"status": "ok", "source": url})
return jsonify({"status": "error", "message": "No URL provided"}), 400
@app.route('/api/track', methods=['POST'])
def set_tracking():
data = request.get_json()
with lock:
global tracking
tracking = data.get("enabled", False)
return jsonify({"status": "ok", "tracking": tracking})
@app.route('/api/status', methods=['GET'])
def get_status():
with lock:
return jsonify({
"model": current_model_name,
"fps": round(fps_value, 1),
"detections": detection_count,
"source": rtsp_source,
"tracking": tracking
})
@app.route('/api/yoloe/classes', methods=['POST'])
def set_yoloe_classes():
if current_model_type != "yoloe":
return jsonify({"status": "error", "message": "Current model is not YOLOE"}), 400
data = request.get_json()
classes = data.get("classes", [])
if model and hasattr(model, 'set_classes'):
model.set_classes(classes)
return jsonify({"status": "ok", "classes": classes})
return jsonify({"status": "error", "message": "Model does not support set_classes"}), 400
@app.route('/api/llm/models', methods=['GET'])
def get_llm_models():
global llm_model
try:
models = ollama_client.list_models()
except requests.RequestException as exc:
return jsonify({"status": "error", "message": f"{type(exc).__name__}: {exc}",
"host": ollama_client.OLLAMA_HOST, "models": [], "current": llm_model}), 502
return jsonify({"status": "ok", "host": ollama_client.OLLAMA_HOST,
"models": models, "current": llm_model})
@app.route('/api/llm/model', methods=['POST'])
def set_llm_model():
global llm_model
data = request.get_json(silent=True) or {}
name = data.get("name")
if not name:
return jsonify({"status": "error", "message": "No model name provided"}), 400
with lock:
llm_model = name
return jsonify({"status": "ok", "model": llm_model})
@app.route('/api/llm/status', methods=['GET'])
def get_llm_status():
with lock:
current = llm_model
info = ollama_client.health(model=current)
return jsonify({"status": "ok", **info})
@app.route('/api/llm/test', methods=['POST'])
def test_llm():
with lock:
current = llm_model
data = request.get_json(silent=True) or {}
prompt = data.get("prompt") or "Reply with the single word: ok"
try:
result = ollama_client.chat(current, prompt)
except requests.RequestException as exc:
return jsonify({"status": "error", "model": current,
"message": f"{type(exc).__name__}: {exc}"}), 502
return jsonify({"status": "ok", **result, "model": current})
def shutdown_listener():
import sys, select, tty, termios
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
tty.setraw(fd)
print("Press Q to quit the server")
try:
while True:
if select.select([sys.stdin], [], [], 0.5)[0]:
ch = sys.stdin.read(1)
if ch.lower() == 'q':
print("\nShutting down...")
os._exit(0)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
if __name__ == '__main__':
processing_thread = threading.Thread(target=process_stream, daemon=True)
processing_thread.start()
listener = threading.Thread(target=shutdown_listener, daemon=True)
listener.start()
app.run(host='0.0.0.0', port=5000, debug=False, threaded=True)