Initial commit: YOLO stream controller with Ollama LLM integration
This commit is contained in:
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.so
|
||||||
|
*.egg-info/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.pt
|
||||||
|
*.ts
|
||||||
|
|
||||||
|
# Virtual environment
|
||||||
|
YOLO/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
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)
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import os
|
||||||
|
import time
|
||||||
|
import requests
|
||||||
|
|
||||||
|
OLLAMA_HOST = os.environ.get("OLLAMA_HOST", "http://192.168.2.15:11434")
|
||||||
|
DEFAULT_MODEL = os.environ.get("OLLAMA_MODEL", "Qwen3.6:27b")
|
||||||
|
|
||||||
|
PROBE_TIMEOUT = 5
|
||||||
|
CHAT_TIMEOUT = 120
|
||||||
|
|
||||||
|
|
||||||
|
def _url(path):
|
||||||
|
return f"{OLLAMA_HOST.rstrip('/')}{path}"
|
||||||
|
|
||||||
|
|
||||||
|
def list_models(timeout=PROBE_TIMEOUT):
|
||||||
|
resp = requests.get(_url("/api/tags"), timeout=timeout)
|
||||||
|
resp.raise_for_status()
|
||||||
|
models = []
|
||||||
|
for entry in resp.json().get("models", []):
|
||||||
|
details = entry.get("details") or {}
|
||||||
|
models.append({
|
||||||
|
"name": entry.get("name"),
|
||||||
|
"size": entry.get("size"),
|
||||||
|
"family": details.get("family"),
|
||||||
|
"parameter_size": details.get("parameter_size"),
|
||||||
|
"quantization": details.get("quantization_level"),
|
||||||
|
"capabilities": entry.get("capabilities", []),
|
||||||
|
"vision": "vision" in entry.get("capabilities", []),
|
||||||
|
})
|
||||||
|
return models
|
||||||
|
|
||||||
|
|
||||||
|
def health(model=None, timeout=PROBE_TIMEOUT):
|
||||||
|
info = {
|
||||||
|
"host": OLLAMA_HOST,
|
||||||
|
"reachable": False,
|
||||||
|
"version": None,
|
||||||
|
"model_count": 0,
|
||||||
|
"model": model,
|
||||||
|
"model_present": False,
|
||||||
|
"latency_ms": None,
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
start = time.time()
|
||||||
|
try:
|
||||||
|
resp = requests.get(_url("/"), timeout=timeout)
|
||||||
|
resp.raise_for_status()
|
||||||
|
info["reachable"] = True
|
||||||
|
info["version"] = resp.text.strip()
|
||||||
|
|
||||||
|
models = list_models(timeout=timeout)
|
||||||
|
info["model_count"] = len(models)
|
||||||
|
if model:
|
||||||
|
info["model_present"] = any(m["name"] == model for m in models)
|
||||||
|
info["latency_ms"] = round((time.time() - start) * 1000, 1)
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
info["error"] = f"{type(exc).__name__}: {exc}"
|
||||||
|
except ValueError as exc:
|
||||||
|
info["error"] = f"BadResponse: {exc}"
|
||||||
|
return info
|
||||||
|
|
||||||
|
|
||||||
|
def chat(model, prompt, system=None, timeout=CHAT_TIMEOUT):
|
||||||
|
payload = {
|
||||||
|
"model": model,
|
||||||
|
"messages": ([{"role": "system", "content": system}] if system else [])
|
||||||
|
+ [{"role": "user", "content": prompt}],
|
||||||
|
"stream": False,
|
||||||
|
}
|
||||||
|
start = time.time()
|
||||||
|
resp = requests.post(_url("/api/chat"), json=payload, timeout=timeout)
|
||||||
|
resp.raise_for_status()
|
||||||
|
body = resp.json()
|
||||||
|
return {
|
||||||
|
"reply": (body.get("message") or {}).get("content", "").strip(),
|
||||||
|
"duration_ms": round((time.time() - start) * 1000, 1),
|
||||||
|
"eval_count": body.get("eval_count"),
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
flask
|
||||||
|
opencv-python
|
||||||
|
ultralytics
|
||||||
|
numpy
|
||||||
|
requests
|
||||||
@@ -0,0 +1,567 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>YOLO Stream Control</title>
|
||||||
|
<style>
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
background: #0f0f0f;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-family: 'Segoe UI', system-ui, sans-serif;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 300;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: #888;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
.container {
|
||||||
|
max-width: 1100px;
|
||||||
|
width: 100%;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 320px;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
.stream-section {
|
||||||
|
background: #1a1a1a;
|
||||||
|
border-radius: 12px;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid #2a2a2a;
|
||||||
|
}
|
||||||
|
.stream-section img {
|
||||||
|
width: 100%;
|
||||||
|
display: block;
|
||||||
|
aspect-ratio: 4/3;
|
||||||
|
object-fit: contain;
|
||||||
|
background: #000;
|
||||||
|
}
|
||||||
|
.controls {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.panel {
|
||||||
|
background: #1a1a1a;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 16px;
|
||||||
|
border: 1px solid #2a2a2a;
|
||||||
|
}
|
||||||
|
.panel h2 {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.stat-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.stat {
|
||||||
|
background: #242424;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.stat .value {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #4fc3f7;
|
||||||
|
}
|
||||||
|
.stat .label {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
color: #777;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
select, input[type="text"], button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: #242424;
|
||||||
|
border: 1px solid #333;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
select:focus, input[type="text"]:focus {
|
||||||
|
border-color: #4fc3f7;
|
||||||
|
}
|
||||||
|
select option { background: #242424; }
|
||||||
|
.btn {
|
||||||
|
background: #4fc3f7;
|
||||||
|
color: #000;
|
||||||
|
border: none;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
.btn:hover { background: #39b0e4; }
|
||||||
|
.btn:active { background: #2a9fd4; }
|
||||||
|
.btn.secondary {
|
||||||
|
background: #333;
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
.btn.secondary:hover { background: #444; }
|
||||||
|
.input-group {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.input-group input { flex: 1; }
|
||||||
|
.input-group button { width: auto; white-space: nowrap; padding: 10px 16px; }
|
||||||
|
.tag {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-left: 6px;
|
||||||
|
}
|
||||||
|
.tag.yolo { background: #1b5e20; color: #81c784; }
|
||||||
|
.tag.yoloe { background: #4a148c; color: #ce93d8; }
|
||||||
|
.badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 4px 10px;
|
||||||
|
border-radius: 20px;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
background: #1a3a1a;
|
||||||
|
color: #81c784;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
.badge.offline { background: #3a1a1a; color: #ef9a9a; }
|
||||||
|
#status-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
#status-bar .dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #4caf50;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
#status-bar .dot.offline { background: #f44336; }
|
||||||
|
.classes-area textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: #242424;
|
||||||
|
border: 1px solid #333;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
resize: vertical;
|
||||||
|
min-height: 80px;
|
||||||
|
outline: none;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
.classes-area textarea:focus { border-color: #ce93d8; }
|
||||||
|
.toast {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 20px;
|
||||||
|
right: 20px;
|
||||||
|
padding: 12px 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #333;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.3s;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
.toast.show { opacity: 1; }
|
||||||
|
.toast.success { background: #1b5e20; color: #a5d6a7; }
|
||||||
|
.toast.error { background: #b71c1c; color: #ef9a9a; }
|
||||||
|
.toast.info { background: #0d47a1; color: #90caf9; }
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.container { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>YOLO Stream Controller</h1>
|
||||||
|
|
||||||
|
<div id="status-bar">
|
||||||
|
<span class="dot" id="status-dot"></span>
|
||||||
|
<span id="status-text">Connecting...</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<div class="stream-section">
|
||||||
|
<img id="stream" src="/video_feed" alt="YOLO Stream">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="controls">
|
||||||
|
<div class="panel">
|
||||||
|
<h2>Model</h2>
|
||||||
|
<select id="model-select"></select>
|
||||||
|
<div style="margin-top:8px;display:flex;gap:8px;">
|
||||||
|
<button class="btn" id="apply-model" style="flex:1;">Apply Model</button>
|
||||||
|
<button class="btn secondary" id="refresh-models" style="width:40px;">↻</button>
|
||||||
|
</div>
|
||||||
|
<div id="model-badge" class="badge">yolo26n.pt</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<h2>Status</h2>
|
||||||
|
<div class="stat-grid">
|
||||||
|
<div class="stat">
|
||||||
|
<div class="value" id="stat-fps">0</div>
|
||||||
|
<div class="label">FPS</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<div class="value" id="stat-dets">0</div>
|
||||||
|
<div class="label">Detections</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<h2>Tracking</h2>
|
||||||
|
<label style="display:flex;align-items:center;gap:10px;cursor:pointer;padding:4px 0;">
|
||||||
|
<input type="checkbox" id="track-toggle" style="width:18px;height:18px;accent-color:#4fc3f7;">
|
||||||
|
<span style="font-size:0.9rem;">Enable tracking (<code>model.track()</code>)</span>
|
||||||
|
</label>
|
||||||
|
<div id="track-status" style="font-size:0.75rem;color:#888;margin-top:6px;">Tracking off</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<h2>RTSP Source</h2>
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="text" id="source-input" placeholder="rtsp://..." value="rtsp://192.168.2.72:80/h264ESVideoTest">
|
||||||
|
<button class="btn" id="apply-source">Apply</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel classes-area" id="yoloe-panel" style="display:none;">
|
||||||
|
<h2>YOLOE Classes</h2>
|
||||||
|
<textarea id="classes-input" placeholder="Enter comma-separated classes...">grass, tree, fence, chain fence, gate, wall, person, ball, block, house, pole, post, board, ground, dirt, field, bush</textarea>
|
||||||
|
<button class="btn secondary" id="apply-classes" style="margin-top:8px;width:100%;">Set Classes</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<h2>Ollama LLM</h2>
|
||||||
|
<select id="llm-model-select"></select>
|
||||||
|
<div style="margin-top:8px;display:flex;gap:8px;">
|
||||||
|
<button class="btn" id="test-llm" style="flex:1;">Test Connection</button>
|
||||||
|
<button class="btn secondary" id="refresh-llm" style="width:40px;">↻</button>
|
||||||
|
</div>
|
||||||
|
<div id="llm-badge" class="badge offline">disconnected</div>
|
||||||
|
<div id="llm-info" style="font-size:0.72rem;color:#777;margin-top:6px;line-height:1.5;"></div>
|
||||||
|
<div id="llm-reply" style="display:none;font-size:0.75rem;color:#aaa;margin-top:8px;padding:8px;background:#242424;border-radius:8px;white-space:pre-wrap;word-break:break-word;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const stream = document.getElementById('stream');
|
||||||
|
const modelSelect = document.getElementById('model-select');
|
||||||
|
const applyModelBtn = document.getElementById('apply-model');
|
||||||
|
const refreshModelsBtn = document.getElementById('refresh-models');
|
||||||
|
const modelBadge = document.getElementById('model-badge');
|
||||||
|
const statFps = document.getElementById('stat-fps');
|
||||||
|
const statDets = document.getElementById('stat-dets');
|
||||||
|
const sourceInput = document.getElementById('source-input');
|
||||||
|
const applySourceBtn = document.getElementById('apply-source');
|
||||||
|
const statusDot = document.getElementById('status-dot');
|
||||||
|
const statusText = document.getElementById('status-text');
|
||||||
|
const yoloePanel = document.getElementById('yoloe-panel');
|
||||||
|
const classesInput = document.getElementById('classes-input');
|
||||||
|
const trackToggle = document.getElementById('track-toggle');
|
||||||
|
const trackStatus = document.getElementById('track-status');
|
||||||
|
const applyClassesBtn = document.getElementById('apply-classes');
|
||||||
|
const llmModelSelect = document.getElementById('llm-model-select');
|
||||||
|
const testLlmBtn = document.getElementById('test-llm');
|
||||||
|
const refreshLlmBtn = document.getElementById('refresh-llm');
|
||||||
|
const llmBadge = document.getElementById('llm-badge');
|
||||||
|
const llmInfo = document.getElementById('llm-info');
|
||||||
|
const llmReply = document.getElementById('llm-reply');
|
||||||
|
const toast = document.getElementById('toast');
|
||||||
|
|
||||||
|
let currentModel = '';
|
||||||
|
|
||||||
|
function showToast(msg, type) {
|
||||||
|
toast.textContent = msg;
|
||||||
|
toast.className = 'toast ' + type + ' show';
|
||||||
|
clearTimeout(toast._hide);
|
||||||
|
toast._hide = setTimeout(() => toast.classList.remove('show'), 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
const TASK_LABELS = {detect: 'Detection', segment: 'Segmentation', classify: 'Classification', pose: 'Pose', obb: 'OBB'};
|
||||||
|
|
||||||
|
async function fetchModels() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/models');
|
||||||
|
const data = await res.json();
|
||||||
|
currentModel = data.current;
|
||||||
|
const groups = {};
|
||||||
|
data.models.forEach(m => {
|
||||||
|
const t = m.task || 'detect';
|
||||||
|
if (!groups[t]) groups[t] = [];
|
||||||
|
groups[t].push(m);
|
||||||
|
});
|
||||||
|
modelSelect.innerHTML = '';
|
||||||
|
for (const [task, models] of Object.entries(groups)) {
|
||||||
|
const grp = document.createElement('optgroup');
|
||||||
|
grp.label = TASK_LABELS[task] || task;
|
||||||
|
models.forEach(m => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = m.name;
|
||||||
|
let label = m.name;
|
||||||
|
if (m.type === 'yoloe') label += ' [YOLOE]';
|
||||||
|
opt.textContent = label;
|
||||||
|
if (m.name === data.current) opt.selected = true;
|
||||||
|
grp.appendChild(opt);
|
||||||
|
});
|
||||||
|
modelSelect.appendChild(grp);
|
||||||
|
}
|
||||||
|
updateBadge(currentModel);
|
||||||
|
updateDot(true, 'Connected');
|
||||||
|
return data;
|
||||||
|
} catch(e) {
|
||||||
|
updateDot(false, 'Disconnected');
|
||||||
|
showToast('Cannot connect to server', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshStatus() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/status');
|
||||||
|
const data = await res.json();
|
||||||
|
statFps.textContent = data.fps;
|
||||||
|
statDets.textContent = data.detections;
|
||||||
|
if (document.activeElement !== sourceInput) sourceInput.value = data.source;
|
||||||
|
trackToggle.checked = data.tracking;
|
||||||
|
trackStatus.textContent = data.tracking ? 'Tracking active (persist=True)' : 'Tracking off';
|
||||||
|
if (data.model !== currentModel) {
|
||||||
|
currentModel = data.model;
|
||||||
|
updateBadge(data.model);
|
||||||
|
for (const opt of modelSelect.options) {
|
||||||
|
if (opt.value === data.model) { opt.selected = true; break; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yoloePanel.style.display = data.model.includes('YOLOE') ? 'block' : 'none';
|
||||||
|
updateDot(true, 'Connected');
|
||||||
|
} catch(e) {
|
||||||
|
updateDot(false, 'Disconnected');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateBadge(name) {
|
||||||
|
modelBadge.textContent = name;
|
||||||
|
modelBadge.className = 'badge' + (name.includes('YOLOE') ? '' : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateDot(online, text) {
|
||||||
|
statusDot.className = 'dot' + (online ? '' : ' offline');
|
||||||
|
statusText.textContent = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
applyModelBtn.addEventListener('click', async () => {
|
||||||
|
const name = modelSelect.value;
|
||||||
|
if (!name) return;
|
||||||
|
applyModelBtn.disabled = true;
|
||||||
|
applyModelBtn.textContent = 'Switching...';
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/models', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({name})
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.status === 'ok') {
|
||||||
|
showToast(`Switched to ${data.model}`, 'success');
|
||||||
|
currentModel = data.model;
|
||||||
|
updateBadge(data.model);
|
||||||
|
} else {
|
||||||
|
showToast(data.message || 'Failed to switch model', 'error');
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
showToast('Error switching model', 'error');
|
||||||
|
}
|
||||||
|
applyModelBtn.disabled = false;
|
||||||
|
applyModelBtn.textContent = 'Apply Model';
|
||||||
|
});
|
||||||
|
|
||||||
|
refreshModelsBtn.addEventListener('click', fetchModels);
|
||||||
|
|
||||||
|
trackToggle.addEventListener('change', async () => {
|
||||||
|
try {
|
||||||
|
await fetch('/api/track', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({enabled: trackToggle.checked})
|
||||||
|
});
|
||||||
|
showToast(trackToggle.checked ? 'Tracking ON' : 'Tracking OFF', 'info');
|
||||||
|
} catch(e) {
|
||||||
|
showToast('Error toggling tracking', 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
applySourceBtn.addEventListener('click', async () => {
|
||||||
|
const url = sourceInput.value.trim();
|
||||||
|
if (!url) return;
|
||||||
|
applySourceBtn.disabled = true;
|
||||||
|
applySourceBtn.textContent = 'Applying...';
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/source', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({url})
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.status === 'ok') {
|
||||||
|
showToast('Source updated, reconnecting stream...', 'info');
|
||||||
|
stream.src = '/video_feed?' + Date.now();
|
||||||
|
} else {
|
||||||
|
showToast(data.message || 'Failed', 'error');
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
showToast('Error updating source', 'error');
|
||||||
|
}
|
||||||
|
applySourceBtn.disabled = false;
|
||||||
|
applySourceBtn.textContent = 'Apply';
|
||||||
|
});
|
||||||
|
|
||||||
|
applyClassesBtn.addEventListener('click', async () => {
|
||||||
|
const classes = classesInput.value.split(',').map(s => s.trim()).filter(Boolean);
|
||||||
|
if (!classes.length) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/yoloe/classes', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({classes})
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.status === 'ok') {
|
||||||
|
showToast('Classes updated', 'success');
|
||||||
|
} else {
|
||||||
|
showToast(data.message || 'Failed', 'error');
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
showToast('Error setting classes', 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function fetchLlmModels() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/llm/models');
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.status !== 'ok') {
|
||||||
|
llmBadge.textContent = 'unreachable';
|
||||||
|
llmBadge.className = 'badge offline';
|
||||||
|
llmInfo.textContent = data.message || 'Cannot reach Ollama';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const prev = llmModelSelect.value;
|
||||||
|
llmModelSelect.innerHTML = '';
|
||||||
|
data.models.forEach(m => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = m.name;
|
||||||
|
opt.textContent = m.vision ? m.name + ' [vision]' : m.name;
|
||||||
|
llmModelSelect.appendChild(opt);
|
||||||
|
});
|
||||||
|
if (prev && data.models.some(m => m.name === prev)) llmModelSelect.value = prev;
|
||||||
|
else if (data.models.some(m => m.name === data.current)) llmModelSelect.value = data.current;
|
||||||
|
llmInfo.textContent = data.host;
|
||||||
|
} catch(e) {
|
||||||
|
llmBadge.textContent = 'unreachable';
|
||||||
|
llmBadge.className = 'badge offline';
|
||||||
|
llmInfo.textContent = 'Cannot reach controller';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshLlmStatus() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/llm/status');
|
||||||
|
const data = await res.json();
|
||||||
|
const online = data.reachable && data.model_present;
|
||||||
|
llmBadge.textContent = data.reachable
|
||||||
|
? (data.model_present ? data.model : 'model missing')
|
||||||
|
: 'unreachable';
|
||||||
|
llmBadge.className = 'badge' + (online ? '' : ' offline');
|
||||||
|
if (data.reachable) {
|
||||||
|
llmInfo.textContent = [data.version, data.model_count + ' models',
|
||||||
|
data.latency_ms != null ? data.latency_ms + ' ms' : null].filter(Boolean).join(' · ');
|
||||||
|
} else if (data.error) {
|
||||||
|
llmInfo.textContent = data.error;
|
||||||
|
}
|
||||||
|
} catch(e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
llmModelSelect.addEventListener('change', async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/llm/model', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({name: llmModelSelect.value})
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.status === 'ok') showToast('LLM set to ' + data.model, 'success');
|
||||||
|
else showToast(data.message || 'Failed', 'error');
|
||||||
|
} catch(e) {
|
||||||
|
showToast('Error setting LLM model', 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
testLlmBtn.addEventListener('click', async () => {
|
||||||
|
testLlmBtn.disabled = true;
|
||||||
|
testLlmBtn.textContent = 'Testing...';
|
||||||
|
llmReply.style.display = 'none';
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/llm/test', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({})
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.status === 'ok') {
|
||||||
|
llmReply.textContent = `${data.reply}\n\n${data.duration_ms} ms` + (data.eval_count ? ` · ${data.eval_count} tokens` : '');
|
||||||
|
llmReply.style.display = 'block';
|
||||||
|
showToast('LLM reachable', 'success');
|
||||||
|
} else {
|
||||||
|
llmReply.textContent = data.message || 'Test failed';
|
||||||
|
llmReply.style.display = 'block';
|
||||||
|
showToast('LLM test failed', 'error');
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
showToast('Error testing LLM', 'error');
|
||||||
|
}
|
||||||
|
testLlmBtn.disabled = false;
|
||||||
|
testLlmBtn.textContent = 'Test Connection';
|
||||||
|
});
|
||||||
|
|
||||||
|
refreshLlmBtn.addEventListener('click', fetchLlmModels);
|
||||||
|
|
||||||
|
// Reconnect stream on error
|
||||||
|
stream.addEventListener('error', () => {
|
||||||
|
setTimeout(() => { stream.src = '/video_feed?' + Date.now(); }, 2000);
|
||||||
|
});
|
||||||
|
|
||||||
|
fetchModels();
|
||||||
|
fetchLlmModels();
|
||||||
|
refreshLlmStatus();
|
||||||
|
setInterval(refreshStatus, 2000);
|
||||||
|
setInterval(refreshLlmStatus, 5000);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user