< Summary

Information
Class: InferenceEngine.Core.ModelProviders.ModelRegistry
Assembly: InferenceEngine.Core
File(s): /home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Core/ModelProviders/ModelRegistry.cs
Line coverage
100%
Covered lines: 125
Uncovered lines: 0
Coverable lines: 125
Total lines: 270
Line coverage: 100%
Branch coverage
86%
Covered branches: 26
Total branches: 30
Branch coverage: 86.6%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)75%44100%
GetModelUrls(...)100%22100%
GetModelEntry(...)100%22100%
IsModelRegistered(...)100%11100%
GetRegisteredModels()100%11100%
LoadRegistry(...)92.85%1414100%
CreateDefaultRegistry(...)75%88100%

File(s)

/home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Core/ModelProviders/ModelRegistry.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5using System.Text.Json;
 6using Microsoft.Extensions.Logging;
 7using Microsoft.Extensions.Logging.Abstractions;
 8
 9namespace InferenceEngine.Core.ModelProviders
 10{
 11    /// <summary>
 12    /// Registry of known models and their download URLs from popular model hubs.
 13    /// Allows engines to specify only a model name for commonly known models.
 14    /// </summary>
 15    public class ModelRegistry
 16    {
 17        private readonly Dictionary<string, ModelRegistryEntry> _entries;
 18        private readonly ILogger _logger;
 119        private static readonly string DefaultRegistryPath = Path.Combine(
 120            AppContext.BaseDirectory,
 121            "models.json");
 22
 23        /// <summary>
 24        /// Creates a model registry from a JSON file.
 25        /// </summary>
 26        /// <param name="registryPath">Path to the JSON registry file. Uses default if null.</param>
 27        /// <param name="logger">Optional logger</param>
 2028        public ModelRegistry(string? registryPath = null, ILogger? logger = null)
 29        {
 2030            _logger = logger ?? NullLogger.Instance;
 2031            var path = registryPath ?? DefaultRegistryPath;
 2032            _entries = LoadRegistry(path);
 2033        }
 34
 35        /// <summary>
 36        /// Gets download URLs for a model by name.
 37        /// </summary>
 38        /// <param name="modelName">Name of the model file (e.g., "yolo11n.onnx")</param>
 39        /// <returns>Array of URLs to download the model from, or null if not found</returns>
 40        public string[]? GetModelUrls(string modelName)
 41        {
 342            if (_entries.TryGetValue(modelName, out var entry))
 43            {
 244                _logger.LogDebug("Found model '{ModelName}' in registry with {UrlCount} source(s)", modelName, entry.Url
 245                return entry.Urls;
 46            }
 47
 148            _logger.LogDebug("Model '{ModelName}' not found in registry", modelName);
 149            return null;
 50        }
 51
 52        /// <summary>
 53        /// Gets the full registry entry for a model by name.
 54        /// </summary>
 55        /// <param name="modelName">Name of the model file (e.g., "yolo11n.onnx")</param>
 56        /// <returns>The registry entry, or null if not found</returns>
 57        public ModelRegistryEntry? GetModelEntry(string modelName)
 58        {
 859            return _entries.TryGetValue(modelName, out var entry) ? entry : null;
 60        }
 61
 62        /// <summary>
 63        /// Checks if a model is registered.
 64        /// </summary>
 65        /// <param name="modelName">Name of the model file</param>
 66        /// <returns>True if the model is in the registry</returns>
 67        public bool IsModelRegistered(string modelName)
 68        {
 669            return _entries.ContainsKey(modelName);
 70        }
 71
 72        /// <summary>
 73        /// Gets all registered model names.
 74        /// </summary>
 75        /// <returns>Collection of registered model names</returns>
 76        public IReadOnlyCollection<string> GetRegisteredModels()
 77        {
 878            return _entries.Keys;
 79        }
 80
 81        private Dictionary<string, ModelRegistryEntry> LoadRegistry(string path)
 82        {
 2083            if (!File.Exists(path))
 84            {
 185                _logger.LogWarning("Model registry file not found at '{Path}'. Using empty registry.", path);
 186                return new Dictionary<string, ModelRegistryEntry>(StringComparer.OrdinalIgnoreCase);
 87            }
 88
 89            try
 90            {
 1991                var json = File.ReadAllText(path);
 1892                var registry = JsonSerializer.Deserialize<ModelRegistryData>(json, new JsonSerializerOptions
 1893                {
 1894                    PropertyNameCaseInsensitive = true
 1895                });
 96
 1797                if (registry?.Models == null)
 98                {
 199                    _logger.LogWarning("Model registry file is empty or invalid. Using empty registry.");
 1100                    return new Dictionary<string, ModelRegistryEntry>(StringComparer.OrdinalIgnoreCase);
 101                }
 102
 16103                var entries = new Dictionary<string, ModelRegistryEntry>(StringComparer.OrdinalIgnoreCase);
 104104                foreach (var entry in registry.Models)
 105                {
 36106                    if (string.IsNullOrWhiteSpace(entry.Name) || entry.Urls == null || entry.Urls.Length == 0)
 107                    {
 4108                        _logger.LogWarning("Skipping invalid registry entry: missing name or URLs");
 4109                        continue;
 110                    }
 111
 32112                    entries[entry.Name] = entry;
 113                }
 114
 16115                _logger.LogInformation("Loaded {Count} models from registry", entries.Count);
 16116                return entries;
 117            }
 1118            catch (JsonException ex)
 119            {
 1120                _logger.LogError(ex, "Failed to parse model registry JSON");
 1121                return new Dictionary<string, ModelRegistryEntry>(StringComparer.OrdinalIgnoreCase);
 122            }
 1123            catch (Exception ex)
 124            {
 1125                _logger.LogError(ex, "Failed to load model registry from '{Path}'", path);
 1126                return new Dictionary<string, ModelRegistryEntry>(StringComparer.OrdinalIgnoreCase);
 127            }
 19128        }
 129
 130        /// <summary>
 131        /// Creates a default registry file with common models if it doesn't exist.
 132        /// </summary>
 133        /// <param name="path">Path to create the registry file</param>
 134        public static void CreateDefaultRegistry(string? path = null)
 135        {
 3136            var registryPath = path ?? DefaultRegistryPath;
 3137            if (File.Exists(registryPath))
 138            {
 1139                return;
 140            }
 141
 2142            var directory = Path.GetDirectoryName(registryPath);
 2143            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
 144            {
 1145                Directory.CreateDirectory(directory);
 146            }
 147
 2148            var defaultRegistry = new ModelRegistryData
 2149            {
 2150                Models = new[]
 2151                {
 2152                    new ModelRegistryEntry
 2153                    {
 2154                        Name = "yolo11n.onnx",
 2155                        Description = "YOLO11 Nano object detection model",
 2156                        Source = "Ultralytics",
 2157                        Urls = new[]
 2158                        {
 2159                            "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n.onnx",
 2160                            "https://huggingface.co/ultralytics/YOLO11/resolve/main/yolo11n.onnx"
 2161                        }
 2162                    },
 2163                    new ModelRegistryEntry
 2164                    {
 2165                        Name = "yolo11s.onnx",
 2166                        Description = "YOLO11 Small object detection model",
 2167                        Source = "Ultralytics",
 2168                        Urls = new[]
 2169                        {
 2170                            "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11s.onnx",
 2171                            "https://huggingface.co/ultralytics/YOLO11/resolve/main/yolo11s.onnx"
 2172                        }
 2173                    },
 2174                    new ModelRegistryEntry
 2175                    {
 2176                        Name = "yolo11m.onnx",
 2177                        Description = "YOLO11 Medium object detection model",
 2178                        Source = "Ultralytics",
 2179                        Urls = new[]
 2180                        {
 2181                            "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11m.onnx",
 2182                            "https://huggingface.co/ultralytics/YOLO11/resolve/main/yolo11m.onnx"
 2183                        }
 2184                    },
 2185                    new ModelRegistryEntry
 2186                    {
 2187                        Name = "yolov8n.onnx",
 2188                        Description = "YOLOv8 Nano object detection model",
 2189                        Source = "Ultralytics",
 2190                        Urls = new[]
 2191                        {
 2192                            "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov8n.onnx",
 2193                            "https://huggingface.co/ultralytics/YOLOv8/resolve/main/yolov8n.onnx"
 2194                        }
 2195                    },
 2196                    new ModelRegistryEntry
 2197                    {
 2198                        Name = "yolov8n-face.onnx",
 2199                        Description = "YOLOv8 Nano single-class face detection model",
 2200                        Source = "akanametov/yolo-face",
 2201                        Urls = new[]
 2202                        {
 2203                            "https://github.com/akanametov/yolo-face/releases/download/1.0.0/yolov8n-face.onnx"
 2204                        }
 2205                    },
 2206                    new ModelRegistryEntry
 2207                    {
 2208                        Name = "arcface-recognition.onnx",
 2209                        Description = "ArcFace ResNet50 face recognition (insightface buffalo_l w600k_r50), 512-dim embe
 2210                        Source = "InsightFace via HuggingFace mirror richarrrddd/w600k_r50_v1",
 2211                        Urls =
 2212                        [
 2213                            "https://huggingface.co/richarrrddd/w600k_r50_v1/resolve/main/w600k_r50.onnx"
 2214                        ]
 2215                    }
 2216                }
 2217            };
 218
 2219            var json = JsonSerializer.Serialize(defaultRegistry, new JsonSerializerOptions
 2220            {
 2221                WriteIndented = true,
 2222                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
 2223            });
 224
 2225            File.WriteAllText(registryPath, json);
 2226        }
 227    }
 228
 229    /// <summary>
 230    /// Data class for the registry JSON structure.
 231    /// </summary>
 232    public class ModelRegistryData
 233    {
 234        public ModelRegistryEntry[] Models { get; set; } = Array.Empty<ModelRegistryEntry>();
 235    }
 236
 237    /// <summary>
 238    /// Entry in the model registry.
 239    /// </summary>
 240    public class ModelRegistryEntry
 241    {
 242        /// <summary>
 243        /// Name of the model file (e.g., "yolo11n.onnx").
 244        /// </summary>
 245        public string Name { get; set; } = string.Empty;
 246
 247        /// <summary>
 248        /// Human-readable description of the model.
 249        /// </summary>
 250        public string Description { get; set; } = string.Empty;
 251
 252        /// <summary>
 253        /// Source organization or author of the model.
 254        /// </summary>
 255        public string Source { get; set; } = string.Empty;
 256
 257        /// <summary>
 258        /// URLs to download the model from, in priority order.
 259        /// </summary>
 260        public string[] Urls { get; set; } = Array.Empty<string>();
 261
 262        /// <summary>
 263        /// Optional expected SHA-256 of the model file, as 64 lowercase hex characters.
 264        /// When present, <see cref="DownloadingModelProvider"/> verifies the downloaded
 265        /// file against it and rejects mismatches; when absent, the download is accepted
 266        /// but logged as unverified.
 267        /// </summary>
 268        public string? Sha256 { get; set; }
 269    }
 270}