Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions docs-en/Libraries/Mediator/ML.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ builder.Services.AddPredictionEngine(config =>
{
config.RegisterMachineLearningModel<InMemoryImageData, ImagePredictionScore>(pool =>
{
pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!);
pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!);
});
});
```

`AddPredictionEngine` registers `IImageClassificationService`, `IModelInfoService` and `IModelHelper` (scoped) and binds `ImageClassificationOptions`. It does not register the mediator handlers - that is what scanning the library assembly is for. `RegisterMachineLearningModel` adds the ML.NET `PredictionEnginePool`; where the model is loaded from is decided by the pool builder (`FromFile` above). Register the model without a name: predictions use the default model of the pool.
`AddPredictionEngine` registers `IImageClassificationService`, `IModelInfoService` and `IModelHelper` (scoped) and binds `ImageClassificationOptions`. It does not register the mediator handlers - that is what scanning the library assembly is for. `RegisterMachineLearningModel` adds the ML.NET `PredictionEnginePool`; where the model is loaded from is decided by the pool builder (`FromModelFile` above). `FromModelFile(path, watchForChanges = true)` is the loader of this library: it describes the model (file name, checksum, version) from the same bytes it loads it from, which is what a prediction later reports in `ModelInfo`. Register the model without a name: predictions use the default model of the pool.

The types live in the namespace `TailoredApps.Shared.Mediator.ImageClassification`, not under the package name.

Expand Down Expand Up @@ -104,12 +104,23 @@ public class ImageAnalysisController : ControllerBase
prediction.FileName,
prediction.PredictedLabel,
prediction.PredictedScore,
Confidence = $"{prediction.PredictedScore:P2}"
Confidence = $"{prediction.PredictedScore:P2}",
prediction.Scores, // label -> score, for every label of the model
Model = prediction.ModelInfo?.Name,
ModelVersion = prediction.ModelInfo?.Version
});
}
}
```

Besides the winning label, the prediction carries the score of every label (`Scores`) and the description of the model that produced it (`ModelInfo`: name, checksum, version, labels) - enough to store with a file which model judged it and how.

- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The description (file name, checksum, version) is recorded by `FromModelFile` when it loads the model, through the same open file, so it cannot be that of another file. Replacing the file later does not change what the predictions of an already loaded model report; with `watchForChanges` the pool loads the new file, and its predictions carry the new description. A prediction never combines the scores of one model with the description of the other, also while the file is being replaced under load. A file that cannot be read yet (still being written, or held by its writer) is tried again for about a minute after the last change; until it loads, the loaded model stays in use. Watching starts before the first load, so a file replaced while the application starts is picked up as well, and disposing the service provider leaves the file closed.
- **`Scores` is `null`** when the model does not name its scores or the names do not match them one to one.
- **`ModelInfo` is `null`** when the model was loaded in another way (the `FromFile` of ML.NET, a URI), when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`. In each of these cases no file can be proven to be the model that predicted, and a description read from the configured path could belong to another file.
- **`GetModelInfo()`** describes the file as it is now. Its labels come from the `Labels.txt` entry that training writes; a file saved without it (one not trained with this library) gets the labels of the loaded model.
- **The checksum** of the model file is computed once and again only when the file's size or write time changes, so describing the model does not slow predictions down.

### Model training

```csharp
Expand Down Expand Up @@ -139,10 +150,11 @@ Training reads the files with the extension `.jpg` or `.png` from the source dir
| `IImageClassificationService` | Interface | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` |
| `IPredictionEnginePoolAdapter<TData, TPred>` | Interface | Abstraction over the ML.NET `PredictionEnginePool` |
| `ModelInfo` | Class | Model metadata: name, checksum, version, labels |
| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`; `Scores` and `ModelInfo` are not filled by `ClassifyImage` |
| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (label -> score for every label; `null` when the model does not name its scores) and `ModelInfo` (the model that made the prediction; `null` when it cannot be described) |
| `InMemoryImageData` | Class | Model input data: the image as `byte[]` |
| `ImagePredictionScore` | Class | Raw model output: `Score` (per class), `PredictedLabel` |
| `ImageClassificationOptions` | Class | Options bound from the `ImageClassification` section: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` |
| `AddPredictionEngineExtension.FromModelFile<TData, TPrediction>` | Ext. method | Loads the default model of the pool from a file (optionally watching it) and records its description from the same bytes; required for `ImagePrediction.ModelInfo` |
| `AddPredictionEngineExtension.AddPredictionEngine` | Ext. method | Registers `IImageClassificationService`, `IModelInfoService`, `IModelHelper` and the options in DI (not the mediator handlers) |
| `PredictionEngineServiceConfiguration.RegisterMachineLearningModel<D, R>` | Method | Adds the ML.NET `PredictionEnginePool<D, R>` and its adapter; called inside `AddPredictionEngine` |

Expand Down Expand Up @@ -185,7 +197,7 @@ builder.Services.AddMediator(cfg =>
});
builder.Services.AddPredictionEngine(config =>
config.RegisterMachineLearningModel<InMemoryImageData, ImagePredictionScore>(pool =>
pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!)));
pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!)));
```

### What gets configured
Expand All @@ -207,6 +219,8 @@ var result = await _mediator.Send(new ClassifyImage
});
// result.ImagePrediction.PredictedLabel — the predicted class
// result.ImagePrediction.PredictedScore — confidence (0-1)
// result.ImagePrediction.Scores — label -> score for every label; null when the model does not name its scores
// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels of the model that predicted; null when it cannot be described
```

### Model training
Expand All @@ -225,6 +239,10 @@ var result = await _mediator.Send(new TrainImageClassificationModel
- The model must be a ZIP file (ML.NET format)
- The `ImageClassification` configuration section is required — a missing section throws `InvalidOperationException` when the options are first used
- The model version and labels are stored in the archive as separate `Version.txt` and `Labels.txt` entries
- Scores and ModelInfo of a prediction describe the model that made it, not the current content of the model file
- Load the model with pool.FromModelFile(path): with the FromFile of ML.NET a prediction has no ModelInfo
- GetModelInfo() describes the file; without `Labels.txt` (a model not trained with this library) its labels come from the loaded model
- Check ImagePrediction.Scores and ImagePrediction.ModelInfo for null before using them
- Training folder: each subfolder = one class, folder name = label
- PredictionEnginePool is thread-safe — safe for concurrent use
- PredictedScore ∈ [0,1] — the closer to 1, the higher the model's confidence
Expand Down
20 changes: 20 additions & 0 deletions docs-en/Migration/v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,24 @@ The members marked `[Obsolete]` in 2.x are gone. The 2.x compiler warned about e
The old configuration key is detected on purpose: if it were only ignored, a sandbox setup (`ApiUrl` holding the sandbox address) would,
after the upgrade, silently connect to the production default of `ServiceUrl`.

### Image classification describes the model it loaded

Since 2.1.1 a prediction carries the description of the model in `ImagePrediction.ModelInfo` (file name, checksum, version). In 2.x
that description was read from the configured model file when a loaded model was first used. In 3.0 it is recorded while the model is
loaded, from the same bytes, by the loader of the library:

```csharp
// 2.x
pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!);

// 3.0
pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!);
```

With the `FromFile` of ML.NET the model still loads and `Scores` are still filled, but `ModelInfo` is `null`: a description read
afterwards could belong to another file than the one the model came from. `FromModelFile(path, watchForChanges = true)` watches the
file like `FromFile` does.

### New packages for minimal APIs

Two new packages of their own - they change nothing in the existing ones and nothing has to be migrated:
Expand Down Expand Up @@ -122,6 +140,7 @@ Apart from that, the libraries have no change in 3.0 that requires code modifica
| 7 | Stripe: handle an outage with `catch (HttpRequestException)` and a refusal with `PaymentStatus == Rejected`; remove `catch (StripeException)` around `RegisterPayment` and `GetStatus` | A Stripe outage bypasses the old `catch (StripeException)` block, and a refusal is no longer an exception and goes unhandled |
| 8 | Review alerts and queries that count Error entries or `error.type` for 4xx answers | An alert on "validation errors" stops firing |
| 9 | Replace `UtcTimeOfDaty` with `UtcTimeOfDay`, `AddExceptionHAndlingFilterAttribute` with `AddExceptionHandlingFilterAttribute`, and the `ApiUrl` key of the PayNow and Tpay configuration with `ServiceUrl` | A compile error, or a host that does not start |
| 10 | Image classification: replace `pool.FromFile(...)` with `pool.FromModelFile(...)` | `ImagePrediction.ModelInfo` is `null`, with no error |

---

Expand Down Expand Up @@ -217,6 +236,7 @@ You are upgrading a .NET 10 or .NET 11 application from the TailoredApps.Shared.
- The names and members of IRequest, IRequestHandler, IPipelineBehavior, IMediator, ISender, INotification do not change
- Stripe: replace catch (StripeException) around RegisterPayment/GetStatus with catch (HttpRequestException) (outage) and a check of PaymentStatus == Rejected (refusal)
- Alerts that count Error entries for validation failures stop working: validation is logged at Information level
- Image classification: pool.FromFile(path) -> pool.FromModelFile(path); with FromFile ImagePrediction.ModelInfo is null
- UtcTimeOfDaty -> UtcTimeOfDay; AddExceptionHAndlingFilterAttribute -> AddExceptionHandlingFilterAttribute; in appsettings*.json, environment variables and secrets: Payments:Providers:PayNow:ApiUrl and Payments:Providers:Tpay:ApiUrl -> ServiceUrl (the old key stops the host from starting)

### Configuration
Expand Down
28 changes: 23 additions & 5 deletions docs/Libraries/Mediator/ML.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ builder.Services.AddPredictionEngine(config =>
{
config.RegisterMachineLearningModel<InMemoryImageData, ImagePredictionScore>(pool =>
{
pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!);
pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!);
});
});
```

`AddPredictionEngine` rejestruje `IImageClassificationService`, `IModelInfoService` i `IModelHelper` (scoped) oraz wiąże `ImageClassificationOptions`. Nie rejestruje handlerów mediatora — do tego służy skanowanie assembly biblioteki. `RegisterMachineLearningModel` dodaje `PredictionEnginePool` z ML.NET; o tym, skąd ładowany jest model, decyduje builder poola (powyżej `FromFile`). Model rejestruj bez nazwy: predykcje korzystają z domyślnego modelu poola.
`AddPredictionEngine` rejestruje `IImageClassificationService`, `IModelInfoService` i `IModelHelper` (scoped) oraz wiąże `ImageClassificationOptions`. Nie rejestruje handlerów mediatora — do tego służy skanowanie assembly biblioteki. `RegisterMachineLearningModel` dodaje `PredictionEnginePool` z ML.NET; o tym, skąd ładowany jest model, decyduje builder poola (powyżej `FromModelFile`). `FromModelFile(path, watchForChanges = true)` to loader tej biblioteki: opisuje model (nazwa pliku, checksum, wersja) na podstawie tych samych bajtów, z których go ładuje, i to ten opis predykcja zwraca potem w `ModelInfo`. Model rejestruj bez nazwy: predykcje korzystają z domyślnego modelu poola.

Typy znajdują się w przestrzeni nazw `TailoredApps.Shared.Mediator.ImageClassification`, a nie pod nazwą pakietu.

Expand Down Expand Up @@ -104,12 +104,23 @@ public class ImageAnalysisController : ControllerBase
prediction.FileName,
prediction.PredictedLabel,
prediction.PredictedScore,
Confidence = $"{prediction.PredictedScore:P2}"
Confidence = $"{prediction.PredictedScore:P2}",
prediction.Scores, // etykieta -> wynik, dla każdej etykiety modelu
Model = prediction.ModelInfo?.Name,
ModelVersion = prediction.ModelInfo?.Version
});
}
}
```

Oprócz zwycięskiej etykiety predykcja zawiera wynik każdej etykiety (`Scores`) i opis modelu, który ją wydał (`ModelInfo`: nazwa, checksum, wersja, etykiety) - tyle, ile trzeba, żeby zapisać przy pliku, który model go ocenił i jak.

- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Opis (nazwa pliku, checksum, wersja) zapisuje `FromModelFile` w chwili ładowania modelu, przez ten sam otwarty plik, więc nie może dotyczyć innego pliku. Późniejsza podmiana pliku nie zmienia tego, co zwracają predykcje już załadowanego modelu; z `watchForChanges` pula ładuje nowy plik, a jego predykcje mają nowy opis. Predykcja nigdy nie łączy wyników jednego modelu z opisem drugiego, także gdy plik jest podmieniany pod obciążeniem. Plik, którego nie da się jeszcze odczytać (nadal zapisywany albo trzymany przez piszącego), jest próbowany ponownie przez około minutę od ostatniej zmiany; dopóki się nie załaduje, w użyciu zostaje załadowany model. Obserwowanie zaczyna się przed pierwszym ładowaniem, więc plik podmieniony w trakcie startu aplikacji też zostanie załadowany, a po zwolnieniu dostawcy usług plik jest zamknięty.
- **`Scores` ma wartość `null`**, gdy model nie nazywa swoich wyników albo nazwy nie odpowiadają im jeden do jednego.
- **`ModelInfo` ma wartość `null`**, gdy model załadowano w inny sposób (`FromFile` z ML.NET, URI), gdy pula podmieniła model w trakcie predykcji oraz przy własnej implementacji `IPredictionEnginePoolAdapter`. W każdym z tych przypadków nie da się wykazać, że dany plik jest modelem, który wykonał predykcję, a opis odczytany ze skonfigurowanej ścieżki mógłby dotyczyć innego pliku.
- **`GetModelInfo()`** opisuje plik w jego obecnym stanie. Etykiety bierze z wpisu `Labels.txt`, który zapisuje trening; plik zapisany bez niego (nietrenowany tą biblioteką) dostaje etykiety załadowanego modelu.
- **Checksum** pliku modelu jest liczony raz i ponownie dopiero wtedy, gdy zmieni się rozmiar albo czas zapisu pliku, więc opis modelu nie spowalnia predykcji.

### Trening modelu

```csharp
Expand Down Expand Up @@ -139,10 +150,11 @@ Trening czyta pliki z rozszerzeniem `.jpg` lub `.png` z katalogu źródłowego i
| `IImageClassificationService` | Interfejs | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` |
| `IPredictionEnginePoolAdapter<TData, TPred>` | Interfejs | Abstrakcja nad ML.NET `PredictionEnginePool` |
| `ModelInfo` | Klasa | Metadane modelu: nazwa, checksum, wersja, etykiety |
| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`; `Scores` i `ModelInfo` nie są wypełniane przez `ClassifyImage` |
| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (etykieta -> wynik dla każdej etykiety; `null`, gdy model nie nazywa swoich wyników) i `ModelInfo` (model, który wykonał predykcję; `null`, gdy nie da się go opisać) |
| `InMemoryImageData` | Klasa | Dane wejściowe do modelu: obraz jako `byte[]` |
| `ImagePredictionScore` | Klasa | Surowy wynik modelu: `Score` (per klasa), `PredictedLabel` |
| `ImageClassificationOptions` | Klasa | Opcje wiązane z sekcji `ImageClassification`: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` |
| `AddPredictionEngineExtension.FromModelFile<TData, TPrediction>` | Metoda rozsz. | Ładuje domyślny model puli z pliku (opcjonalnie go obserwując) i zapisuje jego opis z tych samych bajtów; wymagane dla `ImagePrediction.ModelInfo` |
| `AddPredictionEngineExtension.AddPredictionEngine` | Metoda ext. | Rejestruje w DI `IImageClassificationService`, `IModelInfoService`, `IModelHelper` i opcje (bez handlerów mediatora) |
| `PredictionEngineServiceConfiguration.RegisterMachineLearningModel<D, R>` | Metoda | Dodaje `PredictionEnginePool<D, R>` z ML.NET i jego adapter; wywoływana wewnątrz `AddPredictionEngine` |

Expand Down Expand Up @@ -185,7 +197,7 @@ builder.Services.AddMediator(cfg =>
});
builder.Services.AddPredictionEngine(config =>
config.RegisterMachineLearningModel<InMemoryImageData, ImagePredictionScore>(pool =>
pool.FromFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!)));
pool.FromModelFile(builder.Configuration[ImageClassificationOptions.ModelFilePathConfig]!)));
```

### Co jest konfigurowane
Expand All @@ -207,6 +219,8 @@ var result = await _mediator.Send(new ClassifyImage
});
// result.ImagePrediction.PredictedLabel — przewidywana klasa
// result.ImagePrediction.PredictedScore — pewność (0-1)
// result.ImagePrediction.Scores — etykieta -> wynik dla każdej etykiety; null, gdy model nie nazywa swoich wyników
// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels modelu, który wykonał predykcję; null, gdy nie da się go opisać
```

### Trening modelu
Expand All @@ -225,6 +239,10 @@ var result = await _mediator.Send(new TrainImageClassificationModel
- Model musi być plikiem ZIP (ML.NET format)
- Sekcja konfiguracji `ImageClassification` jest wymagana — jej brak powoduje `InvalidOperationException` przy pierwszym użyciu opcji
- Wersja i etykiety modelu są zapisywane w archiwum jako osobne wpisy `Version.txt` i `Labels.txt`
- Scores i ModelInfo predykcji opisują model, który ją wykonał, a nie obecną zawartość pliku modelu
- Ładuj model przez pool.FromModelFile(path): z FromFile z ML.NET predykcja nie ma ModelInfo
- GetModelInfo() opisuje plik; bez `Labels.txt` (model nietrenowany tą biblioteką) etykiety pochodzą z załadowanego modelu
- Przed użyciem sprawdź, czy ImagePrediction.Scores i ImagePrediction.ModelInfo nie mają wartości null
- Folder treningowy: każdy podfolder = jedna klasa, nazwa folderu = etykieta
- PredictionEnginePool jest thread-safe — bezpieczne współbieżne użycie
- PredictedScore ∈ [0,1] — im bliżej 1, tym wyższe zaufanie modelu
Expand Down
Loading