forked from GongRzhe/YOLO-MCP-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_cli.py
More file actions
2017 lines (1729 loc) · 71.6 KB
/
server_cli.py
File metadata and controls
2017 lines (1729 loc) · 71.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# server.py - CLI version
import fnmatch
import os
import base64
import cv2
import time
import threading
import subprocess
import json
import tempfile
import platform
from io import BytesIO
from typing import List, Dict, Any, Optional, Union
import numpy as np
from PIL import Image
from mcp.server.fastmcp import FastMCP
# Set up logging configuration
import os.path
import sys
import logging
import contextlib
import signal
import atexit
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("yolo_service.log"),
logging.StreamHandler(sys.stderr)
]
)
camera_startup_status = None # Will store error details if startup fails
camera_last_error = None
logger = logging.getLogger('yolo_service')
# Global variables for camera control
camera_running = False
camera_thread = None
detection_results = []
camera_last_access_time = 0
CAMERA_INACTIVITY_TIMEOUT = 60 # Auto-shutdown after 60 seconds of inactivity
def camera_watchdog_thread():
"""Monitor thread that auto-stops the camera after inactivity"""
global camera_running, camera_last_access_time
logger.info("Camera watchdog thread started")
while True:
# Sleep for a short time to avoid excessive CPU usage
time.sleep(5)
# Check if camera is running
if camera_running:
current_time = time.time()
elapsed_time = current_time - camera_last_access_time
# If no access for more than the timeout, auto-stop
if elapsed_time > CAMERA_INACTIVITY_TIMEOUT:
logger.info(f"Auto-stopping camera after {elapsed_time:.1f} seconds of inactivity")
stop_camera_detection()
else:
# If camera is not running, no need to check frequently
time.sleep(10)
def load_image(image_source, is_path=False):
"""
Load image from file path or base64 data
Args:
image_source: File path or base64 encoded image data
is_path: Whether image_source is a file path
Returns:
PIL Image object
"""
try:
if is_path:
# Load image from file path
if os.path.exists(image_source):
return Image.open(image_source)
else:
raise FileNotFoundError(f"Image file not found: {image_source}")
else:
# Load image from base64 data
image_bytes = base64.b64decode(image_source)
return Image.open(BytesIO(image_bytes))
except Exception as e:
raise ValueError(f"Failed to load image: {str(e)}")
# New function to run YOLO CLI commands
def run_yolo_cli(command_args, capture_output=True, timeout=60):
"""
Run YOLO CLI command and return the results
Args:
command_args: List of command arguments to pass to yolo CLI
capture_output: Whether to capture and return command output
timeout: Command timeout in seconds
Returns:
Command output or success status
"""
# Build the complete command
cmd = ["yolo"] + command_args
# Log the command
logger.info(f"Running YOLO CLI command: {' '.join(cmd)}")
try:
# Run the command
result = subprocess.run(
cmd,
capture_output=capture_output,
text=True,
check=False, # Don't raise exception on non-zero exit
timeout=timeout
)
# Check for errors
if result.returncode != 0:
logger.error(f"YOLO CLI command failed with code {result.returncode}")
logger.error(f"stderr: {result.stderr}")
return {
"success": False,
"error": result.stderr,
"command": " ".join(cmd),
"returncode": result.returncode
}
# Return the result
if capture_output:
return {
"success": True,
"stdout": result.stdout,
"stderr": result.stderr,
"command": " ".join(cmd)
}
else:
return {"success": True, "command": " ".join(cmd)}
except subprocess.TimeoutExpired:
logger.error(f"YOLO CLI command timed out after {timeout} seconds")
return {
"success": False,
"error": f"Command timed out after {timeout} seconds",
"command": " ".join(cmd)
}
except Exception as e:
logger.error(f"Error running YOLO CLI command: {str(e)}")
return {
"success": False,
"error": str(e),
"command": " ".join(cmd)
}
# Create MCP server
mcp = FastMCP("YOLO_Service")
# Global configuration
CONFIG = {
"model_dirs": [
".", # Current directory
"./models", # Models subdirectory
os.path.join(os.path.dirname(os.path.abspath(__file__)), "models"),
]
}
# Function to save base64 data to temp file
def save_base64_to_temp(base64_data, prefix="image", suffix=".jpg"):
"""Save base64 encoded data to a temporary file and return the path"""
try:
# Create a temporary file
fd, temp_path = tempfile.mkstemp(suffix=suffix, prefix=prefix)
# Decode base64 data
image_data = base64.b64decode(base64_data)
# Write data to file
with os.fdopen(fd, 'wb') as temp_file:
temp_file.write(image_data)
return temp_path
except Exception as e:
logger.error(f"Error saving base64 to temp file: {str(e)}")
raise ValueError(f"Failed to save base64 data: {str(e)}")
@mcp.tool()
def get_model_directories() -> Dict[str, Any]:
"""Get information about configured model directories and available models"""
directories = []
for directory in CONFIG["model_dirs"]:
dir_info = {
"path": directory,
"exists": os.path.exists(directory),
"is_directory": os.path.isdir(directory) if os.path.exists(directory) else False,
"models": []
}
if dir_info["exists"] and dir_info["is_directory"]:
for filename in os.listdir(directory):
if filename.endswith(".pt"):
dir_info["models"].append(filename)
directories.append(dir_info)
return {
"configured_directories": CONFIG["model_dirs"],
"directory_details": directories,
"available_models": list_available_models(),
"loaded_models": [] # No longer track loaded models with CLI approach
}
@mcp.tool()
def detect_objects(
image_data: str,
model_name: str = "yolov8n.pt",
confidence: float = 0.25,
save_results: bool = False,
is_path: bool = False
) -> Dict[str, Any]:
"""
Detect objects in an image using YOLO CLI
Args:
image_data: Base64 encoded image or file path (if is_path=True)
model_name: YOLO model name
confidence: Detection confidence threshold
save_results: Whether to save results to disk
is_path: Whether image_data is a file path
Returns:
Dictionary containing detection results
"""
try:
# Determine source path
if is_path:
source_path = image_data
if not os.path.exists(source_path):
return {
"error": f"Image file not found: {source_path}",
"source": source_path
}
else:
# Save base64 data to temp file
source_path = save_base64_to_temp(image_data)
# Determine full model path
model_path = None
for directory in CONFIG["model_dirs"]:
potential_path = os.path.join(directory, model_name)
if os.path.exists(potential_path):
model_path = potential_path
break
if model_path is None:
available = list_available_models()
available_str = ", ".join(available) if available else "none"
return {
"error": f"Model '{model_name}' not found in any configured directories. Available models: {available_str}",
"source": image_data if is_path else "base64_image"
}
# Setup output directory if saving results
output_dir = os.path.join(tempfile.gettempdir(), "yolo_results")
if save_results and not os.path.exists(output_dir):
os.makedirs(output_dir)
# Build YOLO CLI command
cmd_args = [
"detect", # Task
"predict", # Mode
f"model={model_path}",
f"source={source_path}",
f"conf={confidence}",
"format=json", # Request JSON output for parsing
]
if save_results:
cmd_args.append(f"project={output_dir}")
cmd_args.append("save=True")
else:
cmd_args.append("save=False")
# Run YOLO CLI command
result = run_yolo_cli(cmd_args)
# Clean up temp file if we created one
if not is_path:
try:
os.remove(source_path)
except Exception as e:
logger.warning(f"Failed to clean up temp file {source_path}: {str(e)}")
# Check for command success
if not result["success"]:
return {
"error": f"YOLO CLI command failed: {result.get('error', 'Unknown error')}",
"command": result.get("command", ""),
"source": image_data if is_path else "base64_image"
}
# Parse JSON output from stdout
try:
# Try to find JSON in the output
json_start = result["stdout"].find("{")
json_end = result["stdout"].rfind("}")
if json_start >= 0 and json_end > json_start:
json_str = result["stdout"][json_start:json_end+1]
detection_data = json.loads(json_str)
else:
# If no JSON found, create a basic response with info from stderr
return {
"results": [],
"model_used": model_name,
"total_detections": 0,
"source": image_data if is_path else "base64_image",
"command_output": result["stderr"]
}
# Format results
formatted_results = []
# Parse detection data from YOLO JSON output
if "predictions" in detection_data:
detections = []
for pred in detection_data["predictions"]:
# Extract box coordinates
box = pred.get("box", {})
x1, y1, x2, y2 = box.get("x1", 0), box.get("y1", 0), box.get("x2", 0), box.get("y2", 0)
# Extract class information
confidence = pred.get("confidence", 0)
class_name = pred.get("name", "unknown")
class_id = pred.get("class", -1)
detections.append({
"box": [x1, y1, x2, y2],
"confidence": confidence,
"class_id": class_id,
"class_name": class_name
})
# Get image dimensions if available
image_shape = [
detection_data.get("width", 0),
detection_data.get("height", 0)
]
formatted_results.append({
"detections": detections,
"image_shape": image_shape
})
return {
"results": formatted_results,
"model_used": model_name,
"total_detections": sum(len(r["detections"]) for r in formatted_results),
"source": image_data if is_path else "base64_image",
"save_dir": output_dir if save_results else None
}
except json.JSONDecodeError as e:
logger.error(f"Failed to parse JSON from YOLO output: {e}")
logger.error(f"Output: {result['stdout']}")
return {
"error": f"Failed to parse YOLO results: {str(e)}",
"command": result.get("command", ""),
"source": image_data if is_path else "base64_image",
"stdout": result.get("stdout", ""),
"stderr": result.get("stderr", "")
}
except Exception as e:
logger.error(f"Error in detect_objects: {str(e)}")
return {
"error": f"Failed to detect objects: {str(e)}",
"source": image_data if is_path else "base64_image"
}
@mcp.tool()
def segment_objects(
image_data: str,
model_name: str = "yolov11n-seg.pt",
confidence: float = 0.25,
save_results: bool = False,
is_path: bool = False
) -> Dict[str, Any]:
"""
Perform instance segmentation on an image using YOLO CLI
Args:
image_data: Base64 encoded image or file path (if is_path=True)
model_name: YOLO segmentation model name
confidence: Detection confidence threshold
save_results: Whether to save results to disk
is_path: Whether image_data is a file path
Returns:
Dictionary containing segmentation results
"""
try:
# Determine source path
if is_path:
source_path = image_data
if not os.path.exists(source_path):
return {
"error": f"Image file not found: {source_path}",
"source": source_path
}
else:
# Save base64 data to temp file
source_path = save_base64_to_temp(image_data)
# Determine full model path
model_path = None
for directory in CONFIG["model_dirs"]:
potential_path = os.path.join(directory, model_name)
if os.path.exists(potential_path):
model_path = potential_path
break
if model_path is None:
available = list_available_models()
available_str = ", ".join(available) if available else "none"
return {
"error": f"Model '{model_name}' not found in any configured directories. Available models: {available_str}",
"source": image_data if is_path else "base64_image"
}
# Setup output directory if saving results
output_dir = os.path.join(tempfile.gettempdir(), "yolo_results")
if save_results and not os.path.exists(output_dir):
os.makedirs(output_dir)
# Build YOLO CLI command
cmd_args = [
"segment", # Task
"predict", # Mode
f"model={model_path}",
f"source={source_path}",
f"conf={confidence}",
"format=json", # Request JSON output for parsing
]
if save_results:
cmd_args.append(f"project={output_dir}")
cmd_args.append("save=True")
else:
cmd_args.append("save=False")
# Run YOLO CLI command
result = run_yolo_cli(cmd_args)
# Clean up temp file if we created one
if not is_path:
try:
os.remove(source_path)
except Exception as e:
logger.warning(f"Failed to clean up temp file {source_path}: {str(e)}")
# Check for command success
if not result["success"]:
return {
"error": f"YOLO CLI command failed: {result.get('error', 'Unknown error')}",
"command": result.get("command", ""),
"source": image_data if is_path else "base64_image"
}
# Parse JSON output from stdout
try:
# Try to find JSON in the output
json_start = result["stdout"].find("{")
json_end = result["stdout"].rfind("}")
if json_start >= 0 and json_end > json_start:
json_str = result["stdout"][json_start:json_end+1]
segmentation_data = json.loads(json_str)
else:
# If no JSON found, create a basic response with info from stderr
return {
"results": [],
"model_used": model_name,
"total_segments": 0,
"source": image_data if is_path else "base64_image",
"command_output": result["stderr"]
}
# Format results
formatted_results = []
# Parse segmentation data from YOLO JSON output
if "predictions" in segmentation_data:
segments = []
for pred in segmentation_data["predictions"]:
# Extract box coordinates
box = pred.get("box", {})
x1, y1, x2, y2 = box.get("x1", 0), box.get("y1", 0), box.get("x2", 0), box.get("y2", 0)
# Extract class information
confidence = pred.get("confidence", 0)
class_name = pred.get("name", "unknown")
class_id = pred.get("class", -1)
segment = {
"box": [x1, y1, x2, y2],
"confidence": confidence,
"class_id": class_id,
"class_name": class_name
}
# Extract mask if available
if "mask" in pred:
segment["mask"] = pred["mask"]
segments.append(segment)
# Get image dimensions if available
image_shape = [
segmentation_data.get("width", 0),
segmentation_data.get("height", 0)
]
formatted_results.append({
"segments": segments,
"image_shape": image_shape
})
return {
"results": formatted_results,
"model_used": model_name,
"total_segments": sum(len(r["segments"]) for r in formatted_results),
"source": image_data if is_path else "base64_image",
"save_dir": output_dir if save_results else None
}
except json.JSONDecodeError as e:
logger.error(f"Failed to parse JSON from YOLO output: {e}")
logger.error(f"Output: {result['stdout']}")
return {
"error": f"Failed to parse YOLO results: {str(e)}",
"command": result.get("command", ""),
"source": image_data if is_path else "base64_image",
"stdout": result.get("stdout", ""),
"stderr": result.get("stderr", "")
}
except Exception as e:
logger.error(f"Error in segment_objects: {str(e)}")
return {
"error": f"Failed to segment objects: {str(e)}",
"source": image_data if is_path else "base64_image"
}
@mcp.tool()
def classify_image(
image_data: str,
model_name: str = "yolov11n-cls.pt",
top_k: int = 5,
save_results: bool = False,
is_path: bool = False
) -> Dict[str, Any]:
"""
Classify an image using YOLO classification model via CLI
Args:
image_data: Base64 encoded image or file path (if is_path=True)
model_name: YOLO classification model name
top_k: Number of top categories to return
save_results: Whether to save results to disk
is_path: Whether image_data is a file path
Returns:
Dictionary containing classification results
"""
try:
# Determine source path
if is_path:
source_path = image_data
if not os.path.exists(source_path):
return {
"error": f"Image file not found: {source_path}",
"source": source_path
}
else:
# Save base64 data to temp file
source_path = save_base64_to_temp(image_data)
# Determine full model path
model_path = None
for directory in CONFIG["model_dirs"]:
potential_path = os.path.join(directory, model_name)
if os.path.exists(potential_path):
model_path = potential_path
break
if model_path is None:
available = list_available_models()
available_str = ", ".join(available) if available else "none"
return {
"error": f"Model '{model_name}' not found in any configured directories. Available models: {available_str}",
"source": image_data if is_path else "base64_image"
}
# Setup output directory if saving results
output_dir = os.path.join(tempfile.gettempdir(), "yolo_results")
if save_results and not os.path.exists(output_dir):
os.makedirs(output_dir)
# Build YOLO CLI command
cmd_args = [
"classify", # Task
"predict", # Mode
f"model={model_path}",
f"source={source_path}",
"format=json", # Request JSON output for parsing
]
if save_results:
cmd_args.append(f"project={output_dir}")
cmd_args.append("save=True")
else:
cmd_args.append("save=False")
# Run YOLO CLI command
result = run_yolo_cli(cmd_args)
# Clean up temp file if we created one
if not is_path:
try:
os.remove(source_path)
except Exception as e:
logger.warning(f"Failed to clean up temp file {source_path}: {str(e)}")
# Check for command success
if not result["success"]:
return {
"error": f"YOLO CLI command failed: {result.get('error', 'Unknown error')}",
"command": result.get("command", ""),
"source": image_data if is_path else "base64_image"
}
# Parse JSON output from stdout
try:
# Try to find JSON in the output
json_start = result["stdout"].find("{")
json_end = result["stdout"].rfind("}")
if json_start >= 0 and json_end > json_start:
json_str = result["stdout"][json_start:json_end+1]
classification_data = json.loads(json_str)
else:
# If no JSON found, create a basic response with info from stderr
return {
"results": [],
"model_used": model_name,
"top_k": top_k,
"source": image_data if is_path else "base64_image",
"command_output": result["stderr"]
}
# Format results
formatted_results = []
# Parse classification data from YOLO JSON output
if "predictions" in classification_data:
classifications = []
predictions = classification_data["predictions"]
# Predictions could be an array of classifications
for i, pred in enumerate(predictions[:top_k]):
class_name = pred.get("name", f"class_{i}")
confidence = pred.get("confidence", 0)
classifications.append({
"class_id": i,
"class_name": class_name,
"probability": confidence
})
# Get image dimensions if available
image_shape = [
classification_data.get("width", 0),
classification_data.get("height", 0)
]
formatted_results.append({
"classifications": classifications,
"image_shape": image_shape
})
return {
"results": formatted_results,
"model_used": model_name,
"top_k": top_k,
"source": image_data if is_path else "base64_image",
"save_dir": output_dir if save_results else None
}
except json.JSONDecodeError as e:
logger.error(f"Failed to parse JSON from YOLO output: {e}")
logger.error(f"Output: {result['stdout']}")
return {
"error": f"Failed to parse YOLO results: {str(e)}",
"command": result.get("command", ""),
"source": image_data if is_path else "base64_image",
"stdout": result.get("stdout", ""),
"stderr": result.get("stderr", "")
}
except Exception as e:
logger.error(f"Error in classify_image: {str(e)}")
return {
"error": f"Failed to classify image: {str(e)}",
"source": image_data if is_path else "base64_image"
}
@mcp.tool()
def track_objects(
image_data: str,
model_name: str = "yolov8n.pt",
confidence: float = 0.25,
tracker: str = "bytetrack.yaml",
save_results: bool = False
) -> Dict[str, Any]:
"""
Track objects in an image sequence using YOLO CLI
Args:
image_data: Base64 encoded image
model_name: YOLO model name
confidence: Detection confidence threshold
tracker: Tracker name to use (e.g., 'bytetrack.yaml', 'botsort.yaml')
save_results: Whether to save results to disk
Returns:
Dictionary containing tracking results
"""
try:
# Save base64 data to temp file
source_path = save_base64_to_temp(image_data)
# Determine full model path
model_path = None
for directory in CONFIG["model_dirs"]:
potential_path = os.path.join(directory, model_name)
if os.path.exists(potential_path):
model_path = potential_path
break
if model_path is None:
available = list_available_models()
available_str = ", ".join(available) if available else "none"
return {
"error": f"Model '{model_name}' not found in any configured directories. Available models: {available_str}"
}
# Setup output directory if saving results
output_dir = os.path.join(tempfile.gettempdir(), "yolo_track_results")
if save_results and not os.path.exists(output_dir):
os.makedirs(output_dir)
# Build YOLO CLI command
cmd_args = [
"track", # Combined task and mode for tracking
f"model={model_path}",
f"source={source_path}",
f"conf={confidence}",
f"tracker={tracker}",
"format=json", # Request JSON output for parsing
]
if save_results:
cmd_args.append(f"project={output_dir}")
cmd_args.append("save=True")
else:
cmd_args.append("save=False")
# Run YOLO CLI command
result = run_yolo_cli(cmd_args)
# Clean up temp file
try:
os.remove(source_path)
except Exception as e:
logger.warning(f"Failed to clean up temp file {source_path}: {str(e)}")
# Check for command success
if not result["success"]:
return {
"error": f"YOLO CLI command failed: {result.get('error', 'Unknown error')}",
"command": result.get("command", ""),
}
# Parse JSON output from stdout
try:
# Try to find JSON in the output
json_start = result["stdout"].find("{")
json_end = result["stdout"].rfind("}")
if json_start >= 0 and json_end > json_start:
json_str = result["stdout"][json_start:json_end+1]
tracking_data = json.loads(json_str)
else:
# If no JSON found, create a basic response
return {
"results": [],
"model_used": model_name,
"tracker": tracker,
"total_tracks": 0,
"command_output": result["stderr"]
}
# Format results
formatted_results = []
# Parse tracking data from YOLO JSON output
if "predictions" in tracking_data:
tracks = []
for pred in tracking_data["predictions"]:
# Extract box coordinates
box = pred.get("box", {})
x1, y1, x2, y2 = box.get("x1", 0), box.get("y1", 0), box.get("x2", 0), box.get("y2", 0)
# Extract class and tracking information
confidence = pred.get("confidence", 0)
class_name = pred.get("name", "unknown")
class_id = pred.get("class", -1)
track_id = pred.get("id", -1)
track = {
"box": [x1, y1, x2, y2],
"confidence": confidence,
"class_id": class_id,
"class_name": class_name,
"track_id": track_id
}
tracks.append(track)
# Get image dimensions if available
image_shape = [
tracking_data.get("width", 0),
tracking_data.get("height", 0)
]
formatted_results.append({
"tracks": tracks,
"image_shape": image_shape
})
return {
"results": formatted_results,
"model_used": model_name,
"tracker": tracker,
"total_tracks": sum(len(r["tracks"]) for r in formatted_results),
"save_dir": output_dir if save_results else None
}
except json.JSONDecodeError as e:
logger.error(f"Failed to parse JSON from YOLO output: {e}")
logger.error(f"Output: {result['stdout']}")
return {
"error": f"Failed to parse YOLO results: {str(e)}",
"command": result.get("command", ""),
"stdout": result.get("stdout", ""),
"stderr": result.get("stderr", "")
}
except Exception as e:
logger.error(f"Error in track_objects: {str(e)}")
return {
"error": f"Failed to track objects: {str(e)}"
}
@mcp.tool()
def train_model(
dataset_path: str,
model_name: str = "yolov8n.pt",
epochs: int = 100,
imgsz: int = 640,
batch: int = 16,
name: str = "yolo_custom_model",
project: str = "runs/train"
) -> Dict[str, Any]:
"""
Train a YOLO model on a custom dataset using CLI
Args:
dataset_path: Path to YOLO format dataset
model_name: Base model to start with
epochs: Number of training epochs
imgsz: Image size for training
batch: Batch size
name: Name for the training run
project: Project directory
Returns:
Dictionary containing training results
"""
# Validate dataset path
if not os.path.exists(dataset_path):
return {"error": f"Dataset not found: {dataset_path}"}
# Determine full model path
model_path = None
for directory in CONFIG["model_dirs"]:
potential_path = os.path.join(directory, model_name)
if os.path.exists(potential_path):
model_path = potential_path
break
if model_path is None:
available = list_available_models()
available_str = ", ".join(available) if available else "none"
return {
"error": f"Model '{model_name}' not found in any configured directories. Available models: {available_str}"
}
# Create project directory if it doesn't exist
if not os.path.exists(project):
os.makedirs(project)
# Determine task type based on model name
task = "detect" # Default task
if "seg" in model_name:
task = "segment"
elif "pose" in model_name:
task = "pose"
elif "cls" in model_name:
task = "classify"
elif "obb" in model_name:
task = "obb"
# Build YOLO CLI command
cmd_args = [
task, # Task
"train", # Mode
f"model={model_path}",
f"data={dataset_path}",
f"epochs={epochs}",
f"imgsz={imgsz}",
f"batch={batch}",
f"name={name}",
f"project={project}"
]
# Run YOLO CLI command - with longer timeout
logger.info(f"Starting model training with {epochs} epochs - this may take a while...")
result = run_yolo_cli(cmd_args, timeout=epochs * 300) # 5 minutes per epoch
# Check for command success
if not result["success"]:
return {
"error": f"Training failed: {result.get('error', 'Unknown error')}",
"command": result.get("command", ""),
"stderr": result.get("stderr", "")
}
# Determine path to best model weights
best_model_path = os.path.join(project, name, "weights", "best.pt")
# Determine metrics from stdout if possible
metrics = {}
try:
# Look for metrics in output
stdout = result.get("stdout", "")
# Extract metrics from training output
import re
precision_match = re.search(r"Precision: ([\d\.]+)", stdout)
recall_match = re.search(r"Recall: ([\d\.]+)", stdout)
map50_match = re.search(r"mAP50: ([\d\.]+)", stdout)
map_match = re.search(r"mAP50-95: ([\d\.]+)", stdout)
if precision_match:
metrics["precision"] = float(precision_match.group(1))
if recall_match:
metrics["recall"] = float(recall_match.group(1))
if map50_match:
metrics["mAP50"] = float(map50_match.group(1))
if map_match:
metrics["mAP50-95"] = float(map_match.group(1))
except Exception as e:
logger.warning(f"Failed to parse metrics from training output: {str(e)}")
return {
"status": "success",