AppSettings and Configuration changes,

major changes to E_Distance and minor for D_Face
This commit is contained in:
Mike Phares 2022-08-19 21:37:36 -07:00
parent 004017b9dd
commit be7a6abbf4
60 changed files with 1269 additions and 1344 deletions

View File

@ -34,8 +34,6 @@ public class Compare
string renameTo; string renameTo;
string[] segments; string[] segments;
_AppSettings = appSettings; _AppSettings = appSettings;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
_RenameFindReplace = new(); _RenameFindReplace = new();
_RenameBFindReplace = new(); _RenameBFindReplace = new();
_RenameCFindReplace = new(); _RenameCFindReplace = new();
@ -106,7 +104,7 @@ public class Compare
_RenameCFindReplace.Add(new(renameFrom, renameTo)); _RenameCFindReplace.Add(new(renameFrom, renameTo));
} }
groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories); groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection));
_Log.Information($"{nameof(Property.Models.Stateless.Container.GetGroupCollection)} has finished"); _Log.Information($"{nameof(Property.Models.Stateless.Container.GetGroupCollection)} has finished");
_Configuration = configuration; _Configuration = configuration;
@ -118,7 +116,7 @@ public class Compare
topDirectories.Clear(); topDirectories.Clear();
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory);
groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories); groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection));
} }
_Log.Information($"{nameof(PossiblyRename)} has finished"); _Log.Information($"{nameof(PossiblyRename)} has finished");
@ -127,7 +125,7 @@ public class Compare
topDirectories.Clear(); topDirectories.Clear();
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory);
groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories); groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection));
} }
_Log.Information($"{nameof(PossiblyRenameB)} has finished"); _Log.Information($"{nameof(PossiblyRenameB)} has finished");
@ -136,7 +134,7 @@ public class Compare
topDirectories.Clear(); topDirectories.Clear();
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory);
groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories); groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection));
} }
_Log.Information($"{nameof(PossiblyRenameC)} has finished"); _Log.Information($"{nameof(PossiblyRenameC)} has finished");
@ -145,7 +143,7 @@ public class Compare
topDirectories.Clear(); topDirectories.Clear();
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory);
groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories); groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection));
} }
_Log.Information($"{nameof(PossiblyCorrect)} has finished"); _Log.Information($"{nameof(PossiblyCorrect)} has finished");
@ -158,7 +156,7 @@ public class Compare
topDirectories.Clear(); topDirectories.Clear();
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory);
groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories); groupCollection = Property.Models.Stateless.Container.GetGroupCollection(propertyConfiguration.RootDirectory, searchPattern, topDirectories);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection));
} }
if (_IsEnvironment.Development && propertyConfiguration.PopulatePropertyId.Value && !propertyLogic.KeyValuePairs.Any()) if (_IsEnvironment.Development && propertyConfiguration.PopulatePropertyId.Value && !propertyLogic.KeyValuePairs.Any())
@ -389,11 +387,9 @@ public class Compare
private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel) private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel)
{ {
PropertyLogic result; PropertyLogic result;
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
result = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, reverse, model, predictorModel); result = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, reverse, model, predictorModel);
string fromPrepareForOld = "34720-637858334555170379.tsv"; string fromPrepareForOld = "34720-637858334555170379.tsv";
string fromPrepareForOldFile = Path.Combine(_Configuration.PropertyConfiguration.RootDirectory, fromPrepareForOld); string fromPrepareForOldFile = Path.Combine(_Configuration.PropertyConfiguration.RootDirectory, fromPrepareForOld);
if (File.Exists(fromPrepareForOldFile)) if (File.Exists(fromPrepareForOldFile))
@ -433,8 +429,6 @@ public class Compare
{ {
if (_Log is null) if (_Log is null)
throw new NullReferenceException(nameof(_Log)); throw new NullReferenceException(nameof(_Log));
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
string aPropertySingletonDirectory = Property.Models.Stateless.IResult.GetResultsDateGroupDirectory(configuration, nameof(A_Property), "{}"); string aPropertySingletonDirectory = Property.Models.Stateless.IResult.GetResultsDateGroupDirectory(configuration, nameof(A_Property), "{}");
@ -461,7 +455,7 @@ public class Compare
throw new Exception("Invalid directory should end with {}!"); throw new Exception("Invalid directory should end with {}!");
diffRootDirectory = Property.Models.Stateless.A_Property.GetDiffRootDirectory(_Configuration.DiffPropertyDirectory); diffRootDirectory = Property.Models.Stateless.A_Property.GetDiffRootDirectory(_Configuration.DiffPropertyDirectory);
} }
PropertyCompare.Models.PropertyCompareLogic propertyCompareLogic = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, _SpellingFindReplace, diffRootDirectory); PropertyCompare.Models.PropertyCompareLogic propertyCompareLogic = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, _SpellingFindReplace, diffRootDirectory);
if (string.IsNullOrEmpty(_Configuration.DiffPropertyDirectory) || !Directory.Exists(_Configuration.DiffPropertyDirectory)) if (string.IsNullOrEmpty(_Configuration.DiffPropertyDirectory) || !Directory.Exists(_Configuration.DiffPropertyDirectory))
diffPropertyCompareCollection = Array.Empty<PropertyCompare.Models.PropertyCompare>(); diffPropertyCompareCollection = Array.Empty<PropertyCompare.Models.PropertyCompare>();
else else
@ -509,14 +503,12 @@ public class Compare
private void ChangeExtensionFromDeleteToJson(string aPropertySingletonDirectory) private void ChangeExtensionFromDeleteToJson(string aPropertySingletonDirectory)
{ {
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
string searchPattern = "*.delete"; string searchPattern = "*.delete";
long ticks = DateTime.Now.Ticks; long ticks = DateTime.Now.Ticks;
List<string> topDirectories = new(); List<string> topDirectories = new();
List<(int g, string sourceDirectory, string[] sourceDirectoryFiles, int r)> groupCollection; List<(int g, string sourceDirectory, string[] sourceDirectoryFiles, int r)> groupCollection;
groupCollection = Property.Models.Stateless.Container.GetGroupCollection(aPropertySingletonDirectory, searchPattern, topDirectories); groupCollection = Property.Models.Stateless.Container.GetGroupCollection(aPropertySingletonDirectory, searchPattern, topDirectories);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.Container.GetGroupCollection));
foreach ((int g, string sourceDirectory, string[] sourceDirectoryFiles, int r) in groupCollection) foreach ((int g, string sourceDirectory, string[] sourceDirectoryFiles, int r) in groupCollection)
{ {

View File

@ -6,24 +6,16 @@ namespace View_by_Distance.Compare.Models;
public class AppSettings public class AppSettings
{ {
protected string _Company; public string Company { init; get; }
protected string _WorkingDirectoryName; public int MaxDegreeOfParallelism { init; get; }
protected int? _MaxDegreeOfParallelism; public string WorkingDirectoryName { init; get; }
public string Company => _Company;
public string WorkingDirectoryName => _WorkingDirectoryName;
public int? MaxDegreeOfParallelism => _MaxDegreeOfParallelism;
// public AppSettings()
// {
// }
[JsonConstructor] [JsonConstructor]
public AppSettings(string company, string workingDirectoryName, int? maxDegreeOfParallelism) public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{ {
_Company = company; Company = company;
_WorkingDirectoryName = workingDirectoryName; MaxDegreeOfParallelism = maxDegreeOfParallelism;
_MaxDegreeOfParallelism = maxDegreeOfParallelism; WorkingDirectoryName = workingDirectoryName;
} }
public override string ToString() public override string ToString()

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Configuration;
using System.Text.Json; using System.Text.Json;
namespace View_by_Distance.Compare.Models.Binder; namespace View_by_Distance.Compare.Models.Binder;
@ -6,16 +6,13 @@ namespace View_by_Distance.Compare.Models.Binder;
public class AppSettings public class AppSettings
{ {
[Display(Name = "Company"), Required] public string Company { get; set; } #nullable disable
[Display(Name = "Working Directory Name"), Required] public string WorkingDirectoryName { get; set; }
[Display(Name = "Max Degree Of Parallelism"), Required] public int? MaxDegreeOfParallelism { get; set; }
public AppSettings() public string Company { get; set; }
{ public int? MaxDegreeOfParallelism { get; set; }
Company = string.Empty; public string WorkingDirectoryName { get; set; }
WorkingDirectoryName = string.Empty;
MaxDegreeOfParallelism = -1; #nullable restore
}
public override string ToString() public override string ToString()
{ {
@ -23,4 +20,25 @@ public class AppSettings
return result; return result;
} }
private static Models.AppSettings Get(AppSettings appSettings)
{
Models.AppSettings result;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
} }

View File

@ -1,40 +0,0 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.Compare.Models.Stateless;
public abstract class AppSettings
{
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings? result;
Binder.AppSettings appSettings = configurationRoot.Get<Binder.AppSettings>();
string json = JsonSerializer.Serialize(appSettings, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.AppSettings>(json);
if (result is null)
throw new Exception(json);
if (string.IsNullOrEmpty(result.Company))
throw new Exception(json);
string jsonThis = result.ToString();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -21,10 +21,8 @@ public class Program
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true); .AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true);
IConfigurationRoot configurationRoot = configurationBuilder.Build(); IConfigurationRoot configurationRoot = configurationBuilder.Build();
AppSettings appSettings = Models.Stateless.AppSettings.Get(configurationRoot); AppSettings appSettings = Models.Binder.AppSettings.Get(configurationRoot);
if (appSettings.MaxDegreeOfParallelism is null) if (appSettings.MaxDegreeOfParallelism > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be set!");
if (appSettings.MaxDegreeOfParallelism.Value > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!"); throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!");
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working directory name must have a value!"); throw new Exception("Working directory name must have a value!");

View File

@ -30,8 +30,6 @@ public class DateGroup
if (console is null) if (console is null)
{ } { }
_AppSettings = appSettings; _AppSettings = appSettings;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
_IsEnvironment = isEnvironment; _IsEnvironment = isEnvironment;
_Exceptions = new List<string>(); _Exceptions = new List<string>();
_Log = Serilog.Log.ForContext<DateGroup>(); _Log = Serilog.Log.ForContext<DateGroup>();
@ -58,11 +56,11 @@ public class DateGroup
string[] dbFiles = Directory.GetFiles(propertyConfiguration.RootDirectory, "*.db", SearchOption.AllDirectories); string[] dbFiles = Directory.GetFiles(propertyConfiguration.RootDirectory, "*.db", SearchOption.AllDirectories);
foreach (string dbFile in dbFiles) foreach (string dbFile in dbFiles)
File.Delete(dbFile); File.Delete(dbFile);
if (true || appSettings.MaxDegreeOfParallelism.Value < 2) if (true || appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(File.Delete)); ticks = LogDelta(ticks, nameof(File.Delete));
for (int i = 1; i < 10; i++) for (int i = 1; i < 10; i++)
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory);
if (true || appSettings.MaxDegreeOfParallelism.Value < 2) if (true || appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.IPath.DeleteEmptyDirectories)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.IPath.DeleteEmptyDirectories));
List<Container> containers = Property.Models.Stateless.A_Property.Get(propertyConfiguration, propertyLogic); List<Container> containers = Property.Models.Stateless.A_Property.Get(propertyConfiguration, propertyLogic);
if (configuration.ByCreateDateShortcut.HasValue && configuration.ByCreateDateShortcut.Value) if (configuration.ByCreateDateShortcut.HasValue && configuration.ByCreateDateShortcut.Value)
@ -72,7 +70,7 @@ public class DateGroup
List<string> topDirectories = new(); List<string> topDirectories = new();
List<Property.Models.DirectoryInfo> directoryInfoCollection = new(); List<Property.Models.DirectoryInfo> directoryInfoCollection = new();
propertyLogic.ParallelWork(ticks, containers, firstPass: true); propertyLogic.ParallelWork(ticks, containers, firstPass: true);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(PropertyLogic.ParallelWork)); ticks = LogDelta(ticks, nameof(PropertyLogic.ParallelWork));
if (propertyLogic.ExceptionsDirectories.Any()) if (propertyLogic.ExceptionsDirectories.Any())
throw new Exception(); throw new Exception();
@ -80,7 +78,7 @@ public class DateGroup
{ {
if (Property.Models.Stateless.A_Property.Any(containers)) if (Property.Models.Stateless.A_Property.Any(containers))
propertyLogic.ParallelWork(ticks, containers, firstPass: false); propertyLogic.ParallelWork(ticks, containers, firstPass: false);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(PropertyLogic.ParallelWork)); ticks = LogDelta(ticks, nameof(PropertyLogic.ParallelWork));
if (propertyLogic.ExceptionsDirectories.Any()) if (propertyLogic.ExceptionsDirectories.Any())
throw new Exception(); throw new Exception();
@ -331,11 +329,9 @@ public class DateGroup
private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel) private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel)
{ {
PropertyLogic result; PropertyLogic result;
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
result = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, reverse, model, predictorModel); result = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, reverse, model, predictorModel);
return result; return result;
} }

View File

@ -6,24 +6,16 @@ namespace View_by_Distance.Date.Group.Models;
public class AppSettings public class AppSettings
{ {
protected string _Company; public string Company { init; get; }
protected string _WorkingDirectoryName; public int MaxDegreeOfParallelism { init; get; }
protected int? _MaxDegreeOfParallelism; public string WorkingDirectoryName { init; get; }
public string Company => _Company;
public string WorkingDirectoryName => _WorkingDirectoryName;
public int? MaxDegreeOfParallelism => _MaxDegreeOfParallelism;
// public AppSettings()
// {
// }
[JsonConstructor] [JsonConstructor]
public AppSettings(string company, string workingDirectoryName, int? maxDegreeOfParallelism) public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{ {
_Company = company; Company = company;
_WorkingDirectoryName = workingDirectoryName; MaxDegreeOfParallelism = maxDegreeOfParallelism;
_MaxDegreeOfParallelism = maxDegreeOfParallelism; WorkingDirectoryName = workingDirectoryName;
} }
public override string ToString() public override string ToString()

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Configuration;
using System.Text.Json; using System.Text.Json;
namespace View_by_Distance.Date.Group.Models.Binder; namespace View_by_Distance.Date.Group.Models.Binder;
@ -6,16 +6,13 @@ namespace View_by_Distance.Date.Group.Models.Binder;
public class AppSettings public class AppSettings
{ {
[Display(Name = "Company"), Required] public string Company { get; set; } #nullable disable
[Display(Name = "Working Directory Name"), Required] public string WorkingDirectoryName { get; set; }
[Display(Name = "Max Degree Of Parallelism"), Required] public int? MaxDegreeOfParallelism { get; set; }
public AppSettings() public string Company { get; set; }
{ public int? MaxDegreeOfParallelism { get; set; }
Company = string.Empty; public string WorkingDirectoryName { get; set; }
WorkingDirectoryName = string.Empty;
MaxDegreeOfParallelism = -1; #nullable restore
}
public override string ToString() public override string ToString()
{ {
@ -23,4 +20,25 @@ public class AppSettings
return result; return result;
} }
private static Models.AppSettings Get(AppSettings appSettings)
{
Models.AppSettings result;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
} }

View File

@ -1,40 +0,0 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.Date.Group.Models.Stateless;
public abstract class AppSettings
{
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings? result;
Binder.AppSettings appSettings = configurationRoot.Get<Binder.AppSettings>();
string json = JsonSerializer.Serialize(appSettings, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.AppSettings>(json);
if (result is null)
throw new Exception(json);
if (string.IsNullOrEmpty(result.Company))
throw new Exception(json);
string jsonThis = result.ToString();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -21,10 +21,8 @@ public class Program
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true); .AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true);
IConfigurationRoot configurationRoot = configurationBuilder.Build(); IConfigurationRoot configurationRoot = configurationBuilder.Build();
AppSettings appSettings = Models.Stateless.AppSettings.Get(configurationRoot); AppSettings appSettings = Models.Binder.AppSettings.Get(configurationRoot);
if (appSettings.MaxDegreeOfParallelism is null) if (appSettings.MaxDegreeOfParallelism > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be set!");
if (appSettings.MaxDegreeOfParallelism.Value > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!"); throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!");
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working directory name must have a value!"); throw new Exception("Working directory name must have a value!");

View File

@ -471,7 +471,7 @@ public sealed class FaceRecognition : DisposableObject
/// <returns>An enumerable collection of face location correspond to all faces in specified image.</returns> /// <returns>An enumerable collection of face location correspond to all faces in specified image.</returns>
/// <exception cref="NullReferenceException"><paramref name="image"/> is null.</exception> /// <exception cref="NullReferenceException"><paramref name="image"/> is null.</exception>
/// <exception cref="ObjectDisposedException"><paramref name="image"/> or this object is disposed.</exception> /// <exception cref="ObjectDisposedException"><paramref name="image"/> or this object is disposed.</exception>
public List<Location> FaceLocations(Model model, Image image, int numberOfTimesToUpsample, bool sortByPixelPercentage) public List<Location> FaceLocations(Model model, Image image, int numberOfTimesToUpsample, bool sortByNormalizedPixelPercentage)
{ {
if (image == null) if (image == null)
throw new NullReferenceException(nameof(image)); throw new NullReferenceException(nameof(image));
@ -487,8 +487,8 @@ public sealed class FaceRecognition : DisposableObject
face.Dispose(); face.Dispose();
results.Add(new Location(confidence, ret, image.Width, image.Height)); results.Add(new Location(confidence, ret, image.Width, image.Height));
} }
if (sortByPixelPercentage) if (sortByNormalizedPixelPercentage)
results = (from l in results orderby l.PixelPercentage select l).ToList(); results = (from l in results orderby l.NormalizedPixelPercentage select l).ToList();
return results; return results;
} }

View File

@ -64,31 +64,31 @@ public sealed class Image : DisposableObject
/// <summary> /// <summary>
/// Saves this <see cref="Image"/> to the specified file. /// Saves this <see cref="Image"/> to the specified file.
/// </summary> /// </summary>
/// <param name="filename">A string that contains the name of the file to which to save this <see cref="Image"/>.</param> /// <param name="fileName">A string that contains the name of the file to which to save this <see cref="Image"/>.</param>
/// <param name="format">The <see cref="ImageFormat"/> for this <see cref="Image"/>.</param> /// <param name="format">The <see cref="ImageFormat"/> for this <see cref="Image"/>.</param>
/// <exception cref="NullReferenceException"><paramref name="filename"/> is null.</exception> /// <exception cref="NullReferenceException"><paramref name="fileName"/> is null.</exception>
/// <exception cref="ObjectDisposedException">This object is disposed.</exception> /// <exception cref="ObjectDisposedException">This object is disposed.</exception>
public void Save(string filename, ImageFormat format) public void Save(string fileName, ImageFormat format)
{ {
if (filename == null) if (fileName == null)
throw new NullReferenceException(nameof(filename)); throw new NullReferenceException(nameof(fileName));
ThrowIfDisposed(); ThrowIfDisposed();
string? directory = Path.GetDirectoryName(filename); string? directory = Path.GetDirectoryName(fileName);
if (!Directory.Exists(directory) && !string.IsNullOrWhiteSpace(directory)) if (!Directory.Exists(directory) && !string.IsNullOrWhiteSpace(directory))
_ = Directory.CreateDirectory(directory); _ = Directory.CreateDirectory(directory);
switch (format) switch (format)
{ {
case ImageFormat.Bmp: case ImageFormat.Bmp:
DlibDotNet.Dlib.SaveBmp(Matrix, filename); DlibDotNet.Dlib.SaveBmp(Matrix, fileName);
break; break;
case ImageFormat.Jpeg: case ImageFormat.Jpeg:
DlibDotNet.Dlib.SaveJpeg(Matrix, filename); DlibDotNet.Dlib.SaveJpeg(Matrix, fileName);
break; break;
case ImageFormat.Png: case ImageFormat.Png:
DlibDotNet.Dlib.SavePng(Matrix, filename); DlibDotNet.Dlib.SavePng(Matrix, fileName);
break; break;
} }
} }

View File

@ -40,8 +40,6 @@ public class DlibDotNet
string argZero; string argZero;
Person[] people; Person[] people;
_AppSettings = appSettings; _AppSettings = appSettings;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
_IsEnvironment = isEnvironment; _IsEnvironment = isEnvironment;
_Exceptions = new List<string>(); _Exceptions = new List<string>();
_Log = Serilog.Log.ForContext<DlibDotNet>(); _Log = Serilog.Log.ForContext<DlibDotNet>();
@ -50,7 +48,7 @@ public class DlibDotNet
Property.Models.Configuration propertyConfiguration = Property.Models.Stateless.Configuration.Get(isEnvironment, configurationRoot, workingDirectory); Property.Models.Configuration propertyConfiguration = Property.Models.Stateless.Configuration.Get(isEnvironment, configurationRoot, workingDirectory);
_Log.Information(propertyConfiguration.RootDirectory); _Log.Information(propertyConfiguration.RootDirectory);
Property.Models.Configuration.Verify(propertyConfiguration); Property.Models.Configuration.Verify(propertyConfiguration);
Models.Configuration configuration = Models.Stateless.Configuration.Get(isEnvironment, configurationRoot, workingDirectory, propertyConfiguration); Models.Configuration configuration = Models.Binder.Configuration.Get(isEnvironment, configurationRoot, propertyConfiguration);
Verify(configuration); Verify(configuration);
VerifyExtra(args, propertyConfiguration, configuration); VerifyExtra(args, propertyConfiguration, configuration);
_Configuration = configuration; _Configuration = configuration;
@ -60,47 +58,31 @@ public class DlibDotNet
_Rename = new E3_Rename(configuration); _Rename = new E3_Rename(configuration);
_Distance = new E_Distance(configuration); _Distance = new E_Distance(configuration);
_FaceLandmarks = new D2_FaceLandmarks(configuration); _FaceLandmarks = new D2_FaceLandmarks(configuration);
if (configuration.ForceMetadataLastWriteTimeToCreationTime is null)
throw new NullReferenceException(nameof(configuration.ForceMetadataLastWriteTimeToCreationTime));
if (configuration.ForceResizeLastWriteTimeToCreationTime is null)
throw new NullReferenceException(nameof(configuration.ForceResizeLastWriteTimeToCreationTime));
if (configuration.IgnoreExtensions is null) if (configuration.IgnoreExtensions is null)
throw new NullReferenceException(nameof(configuration.IgnoreExtensions)); throw new NullReferenceException(nameof(configuration.IgnoreExtensions));
if (configuration.OutputQuality is null) _Metadata = new(configuration.ForceMetadataLastWriteTimeToCreationTime, configuration.PropertiesChangedForMetadata);
throw new NullReferenceException(nameof(configuration.OutputQuality));
if (configuration.OverrideForResizeImages is null)
throw new NullReferenceException(nameof(configuration.OverrideForResizeImages));
if (configuration.PropertiesChangedForMetadata is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForMetadata));
if (configuration.PropertiesChangedForResize is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForResize));
if (configuration.Reverse is null)
throw new NullReferenceException(nameof(configuration.Reverse));
_Metadata = new(configuration.ForceMetadataLastWriteTimeToCreationTime.Value, configuration.PropertiesChangedForMetadata.Value);
if (args.Count > 0) if (args.Count > 0)
argZero = Path.GetFullPath(args[0]); argZero = Path.GetFullPath(args[0]);
else else
argZero = Path.GetFullPath(propertyConfiguration.RootDirectory); argZero = Path.GetFullPath(propertyConfiguration.RootDirectory);
_ArgZeroIsConfigurationRootDirectory = propertyConfiguration.RootDirectory == argZero; _ArgZeroIsConfigurationRootDirectory = propertyConfiguration.RootDirectory == argZero;
(ImageCodecInfo imageCodecInfo, EncoderParameters encoderParameters) = C_Resize.GetTuple(configuration.OutputExtension, configuration.OutputQuality.Value); (ImageCodecInfo imageCodecInfo, EncoderParameters encoderParameters) = C_Resize.GetTuple(configuration.OutputExtension, configuration.OutputQuality);
_Resize = new C_Resize(configuration.ForceResizeLastWriteTimeToCreationTime.Value, configuration.OverrideForResizeImages.Value, configuration.PropertiesChangedForResize.Value, configuration.ValidResolutions, imageCodecInfo, encoderParameters); _Resize = new C_Resize(configuration.ForceResizeLastWriteTimeToCreationTime, configuration.OverrideForResizeImages, configuration.PropertiesChangedForResize, configuration.ValidResolutions, imageCodecInfo, encoderParameters);
_Log.Information(configuration.ModelDirectory); _Log.Information(configuration.ModelDirectory);
(Model model, PredictorModel predictorModel, ModelParameter modelParameter) = GetModel(configuration); (Model model, PredictorModel predictorModel, ModelParameter modelParameter) = GetModel(configuration);
_Faces = new D_Face(configuration, argZero, model, modelParameter, predictorModel); _Faces = new D_Face(configuration, argZero, model, modelParameter, predictorModel);
if (configuration.SkipSearch is null)
throw new NullReferenceException(nameof(configuration.SkipSearch));
if (!_ArgZeroIsConfigurationRootDirectory) if (!_ArgZeroIsConfigurationRootDirectory)
people = Array.Empty<Person>(); people = Array.Empty<Person>();
else else
people = _People.GetPeople(propertyConfiguration); people = _People.GetPeople(propertyConfiguration);
if (!isSilent && configuration.TestDistanceResults.HasValue && configuration.TestDistanceResults.Value) if (!isSilent && configuration.TestDistanceResults)
{ {
E2_Navigate e2Navigate = new(console, configuration, argZero); E2_Navigate e2Navigate = new(console, configuration, argZero);
e2Navigate.Navigate(propertyConfiguration, model, predictorModel, configuration.OutputResolutions[0]); e2Navigate.Navigate(propertyConfiguration, model, predictorModel, configuration.OutputResolutions[0]);
_Log.Information(propertyConfiguration.RootDirectory); _Log.Information(propertyConfiguration.RootDirectory);
} }
if (!configuration.SkipSearch.Value) if (!configuration.SkipSearch)
Search(propertyConfiguration, configuration.Reverse.Value, model, predictorModel, argZero, people, isSilent); Search(propertyConfiguration, configuration.Reverse, model, predictorModel, argZero, people, isSilent);
if (_Exceptions.Count == 0 && _ArgZeroIsConfigurationRootDirectory) if (_Exceptions.Count == 0 && _ArgZeroIsConfigurationRootDirectory)
{ {
long ticks = DateTime.Now.Ticks; long ticks = DateTime.Now.Ticks;
@ -113,7 +95,7 @@ public class DlibDotNet
string d2FaceLandmarksRootDirectory = Property.Models.Stateless.IResult.GetResultsDateGroupDirectory(propertyConfiguration, nameof(D2_FaceLandmarks)); string d2FaceLandmarksRootDirectory = Property.Models.Stateless.IResult.GetResultsDateGroupDirectory(propertyConfiguration, nameof(D2_FaceLandmarks));
_Log.Information(string.Concat("Cleaning <", d2FaceLandmarksRootDirectory, ">")); _Log.Information(string.Concat("Cleaning <", d2FaceLandmarksRootDirectory, ">"));
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(d2FaceLandmarksRootDirectory); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(d2FaceLandmarksRootDirectory);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(Property.Models.Stateless.IPath.DeleteEmptyDirectories)); ticks = LogDelta(ticks, nameof(Property.Models.Stateless.IPath.DeleteEmptyDirectories));
} }
string message = $"There were {_Exceptions.Count} exception(s) thrown! {Environment.NewLine}{string.Join(Environment.NewLine, _Exceptions)}"; string message = $"There were {_Exceptions.Count} exception(s) thrown! {Environment.NewLine}{string.Join(Environment.NewLine, _Exceptions)}";
@ -125,7 +107,7 @@ public class DlibDotNet
long ticks = DateTime.Now.Ticks; long ticks = DateTime.Now.Ticks;
foreach (string outputResolution in configuration.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions) foreach (string outputResolution in configuration.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions)
_Distance.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions(propertyConfiguration, model, predictorModel, outputResolution); _Distance.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions(propertyConfiguration, model, predictorModel, outputResolution);
if (appSettings.MaxDegreeOfParallelism.Value < 2) if (appSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(E_Distance.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions)); ticks = LogDelta(ticks, nameof(E_Distance.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions));
} }
} }
@ -141,6 +123,17 @@ public class DlibDotNet
return result; return result;
} }
private long LogDeltaInMinutes(long ticks, string methodName)
{
long result;
if (_Log is null)
throw new NullReferenceException(nameof(_Log));
double delta = new TimeSpan(DateTime.Now.Ticks - ticks).Minutes;
_Log.Debug($"{methodName} took {Math.Floor(delta)} minutes(s)");
result = DateTime.Now.Ticks;
return result;
}
#pragma warning disable CA1416 #pragma warning disable CA1416
#pragma warning restore CA1416 #pragma warning restore CA1416
@ -201,82 +194,18 @@ public class DlibDotNet
throw new Exception($"One or more {nameof(configuration.SaveShortcutsForOutputResolutions)} are not in the ValidResolutions list!"); throw new Exception($"One or more {nameof(configuration.SaveShortcutsForOutputResolutions)} are not in the ValidResolutions list!");
if ((from l in configuration.SaveFaceLandmarkForOutputResolutions where !configuration.ValidResolutions.Contains(l) select false).Any()) if ((from l in configuration.SaveFaceLandmarkForOutputResolutions where !configuration.ValidResolutions.Contains(l) select false).Any())
throw new Exception($"One or more {nameof(configuration.SaveFaceLandmarkForOutputResolutions)} are not in the ValidResolutions list!"); throw new Exception($"One or more {nameof(configuration.SaveFaceLandmarkForOutputResolutions)} are not in the ValidResolutions list!");
if (configuration.CheckJsonForDistanceResults is null) if (configuration.DistanceFactor + configuration.LocationConfidenceFactor != 10)
throw new NullReferenceException(nameof(configuration.CheckJsonForDistanceResults));
if (configuration.CrossDirectoryMaxItemsInDistanceCollection is null)
throw new NullReferenceException(nameof(configuration.CrossDirectoryMaxItemsInDistanceCollection));
if (configuration.DistanceFactor is null)
throw new NullReferenceException(nameof(configuration.DistanceFactor)); throw new NullReferenceException(nameof(configuration.DistanceFactor));
if (configuration.ForceMetadataLastWriteTimeToCreationTime is null)
throw new NullReferenceException(nameof(configuration.ForceMetadataLastWriteTimeToCreationTime));
if (configuration.ForceResizeLastWriteTimeToCreationTime is null)
throw new NullReferenceException(nameof(configuration.ForceResizeLastWriteTimeToCreationTime));
if (configuration.IgnoreExtensions is null)
throw new NullReferenceException(nameof(configuration.IgnoreExtensions));
if (configuration.IgnoreRelativePaths is null)
throw new NullReferenceException(nameof(configuration.IgnoreRelativePaths));
if (configuration.LoadOrCreateThenSaveIndex is null)
throw new NullReferenceException(nameof(configuration.LoadOrCreateThenSaveIndex));
if (configuration.LocationConfidenceFactor is null)
throw new NullReferenceException(nameof(configuration.LocationConfidenceFactor));
if (configuration.MappedMaxIndex is null)
throw new NullReferenceException(nameof(configuration.MappedMaxIndex));
if (configuration.MappedMaxIndex.HasValue && configuration.LoadOrCreateThenSaveIndex.Value && !_IsEnvironment.DebuggerWasAttachedDuringConstructor)
throw new NullReferenceException(nameof(configuration.MappedMaxIndex));
if (configuration.MaxItemsInDistanceCollection is null)
throw new NullReferenceException(nameof(configuration.MaxItemsInDistanceCollection));
if (configuration.MixedYearRelativePaths is null)
throw new NullReferenceException(nameof(configuration.MixedYearRelativePaths));
if (configuration.NumberOfJitters is null)
throw new NullReferenceException(nameof(configuration.NumberOfJitters));
if (configuration.NumberOfTimesToUpsample is null)
throw new NullReferenceException(nameof(configuration.NumberOfTimesToUpsample));
if (configuration.OutputQuality is null)
throw new NullReferenceException(nameof(configuration.OutputQuality));
if (configuration.OutputResolutions is null)
throw new NullReferenceException(nameof(configuration.OutputResolutions));
if (configuration.OverrideForFaceImages is null)
throw new NullReferenceException(nameof(configuration.OverrideForFaceImages));
if (configuration.OverrideForFaceLandmarkImages is null)
throw new NullReferenceException(nameof(configuration.OverrideForFaceLandmarkImages));
if (configuration.OverrideForResizeImages is null)
throw new NullReferenceException(nameof(configuration.OverrideForResizeImages));
if (configuration.PaddingLoops is null)
throw new NullReferenceException(nameof(configuration.PaddingLoops));
if (configuration.PropertiesChangedForDistance is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForDistance));
if (configuration.PropertiesChangedForFaces is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForFaces));
if (configuration.PropertiesChangedForIndex is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForIndex));
if (configuration.PropertiesChangedForMetadata is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForMetadata));
if (configuration.PropertiesChangedForResize is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForResize));
if (configuration.Reverse is null)
throw new NullReferenceException(nameof(configuration.Reverse));
if (configuration.SaveFaceLandmarkForOutputResolutions is null)
throw new NullReferenceException(nameof(configuration.SaveFaceLandmarkForOutputResolutions));
if (configuration.SaveFullYearOfRandomFiles is null)
throw new NullReferenceException(nameof(configuration.SaveFullYearOfRandomFiles));
if (configuration.SaveResizedSubfiles is null)
throw new NullReferenceException(nameof(configuration.SaveResizedSubfiles));
if (configuration.SkipSearch is null)
throw new NullReferenceException(nameof(configuration.SkipSearch));
if (configuration.TestDistanceResults is null)
throw new NullReferenceException(nameof(configuration.TestDistanceResults));
if (configuration.ValidResolutions is null)
throw new NullReferenceException(nameof(configuration.ValidResolutions));
if (string.IsNullOrEmpty(configuration.ModelDirectory) || !Directory.Exists(configuration.ModelDirectory))
throw new NullReferenceException(nameof(configuration.ModelDirectory));
if (string.IsNullOrEmpty(configuration.ModelName)) if (string.IsNullOrEmpty(configuration.ModelName))
throw new NullReferenceException(nameof(configuration.ModelName)); throw new NullReferenceException(nameof(configuration.ModelName));
if (string.IsNullOrEmpty(configuration.OutputExtension)) if (string.IsNullOrEmpty(configuration.OutputExtension))
throw new NullReferenceException(nameof(configuration.OutputExtension)); throw new NullReferenceException(nameof(configuration.OutputExtension));
if (string.IsNullOrEmpty(configuration.PredictorModelName)) if (string.IsNullOrEmpty(configuration.PredictorModelName))
throw new NullReferenceException(nameof(configuration.PredictorModelName)); throw new NullReferenceException(nameof(configuration.PredictorModelName));
if (configuration.DistanceFactor.Value + configuration.LocationConfidenceFactor.Value != 10) if (string.IsNullOrEmpty(configuration.ModelDirectory) || !Directory.Exists(configuration.ModelDirectory))
throw new NullReferenceException(nameof(configuration.DistanceFactor)); throw new NullReferenceException(nameof(configuration.ModelDirectory));
if (configuration.MappedMaxIndex.HasValue && configuration.LoadOrCreateThenSaveIndex && !_IsEnvironment.DebuggerWasAttachedDuringConstructor)
throw new NullReferenceException(nameof(configuration.MappedMaxIndex));
} }
private void VerifyExtra(List<string> args, Property.Models.Configuration propertyConfiguration, Models.Configuration configuration) private void VerifyExtra(List<string> args, Property.Models.Configuration propertyConfiguration, Models.Configuration configuration)
@ -309,10 +238,6 @@ public class DlibDotNet
{ {
if (item.ImageFileHolder is null) if (item.ImageFileHolder is null)
throw new NullReferenceException(nameof(item.ImageFileHolder)); throw new NullReferenceException(nameof(item.ImageFileHolder));
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration.SaveResizedSubfiles is null)
throw new NullReferenceException(nameof(_Configuration.SaveResizedSubfiles));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
if (_Configuration.PropertyConfiguration.WriteBitmapDataBytes is null) if (_Configuration.PropertyConfiguration.WriteBitmapDataBytes is null)
@ -343,24 +268,24 @@ public class DlibDotNet
} }
} }
(int metadataGroups, metadataCollection) = _Metadata.GetMetadataCollection(bResultsFullGroupDirectory, subFileTuples, parseExceptions, item); (int metadataGroups, metadataCollection) = _Metadata.GetMetadataCollection(bResultsFullGroupDirectory, subFileTuples, parseExceptions, item);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(B_Metadata.GetMetadataCollection)); ticks = LogDelta(ticks, nameof(B_Metadata.GetMetadataCollection));
FileHolder resizedFileHolder = new(Path.Combine(_Resize.AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName))); FileHolder resizedFileHolder = new(Path.Combine(_Resize.AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName)));
item.SetResizedFileHolder(resizedFileHolder); item.SetResizedFileHolder(resizedFileHolder);
imageResizeKeyValuePairs = _Resize.GetResizeKeyValuePairs(cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, property, item); imageResizeKeyValuePairs = _Resize.GetResizeKeyValuePairs(cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(C_Resize.GetResizeKeyValuePairs)); ticks = LogDelta(ticks, nameof(C_Resize.GetResizeKeyValuePairs));
if (_Configuration.SaveResizedSubfiles.Value) if (_Configuration.SaveResizedSubfiles)
{ {
_Resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, property, imageResizeKeyValuePairs); _Resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, imageResizeKeyValuePairs);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(C_Resize.SaveResizedSubfile)); ticks = LogDelta(ticks, nameof(C_Resize.SaveResizedSubfile));
item.SetResizedFileHolder(FileHolder.Refresh(resizedFileHolder)); item.SetResizedFileHolder(FileHolder.Refresh(resizedFileHolder));
} }
else if (outputResolution == _Configuration.OutputResolutions[0] && false) else if (outputResolution == _Configuration.OutputResolutions[0] && false)
{ {
byte[] bytes = _Resize.GetResizedBytes(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, property, imageResizeKeyValuePairs); byte[] bytes = _Resize.GetResizedBytes(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, property, imageResizeKeyValuePairs);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(C_Resize.GetResizedBytes)); ticks = LogDelta(ticks, nameof(C_Resize.GetResizedBytes));
string path = Path.Combine(resizedFileHolder.DirectoryName, resizedFileHolder.NameWithoutExtension); string path = Path.Combine(resizedFileHolder.DirectoryName, resizedFileHolder.NameWithoutExtension);
File.WriteAllBytes(path, bytes); File.WriteAllBytes(path, bytes);
@ -374,15 +299,15 @@ public class DlibDotNet
int outputResolutionHeight = outputResolutionCollection[1]; int outputResolutionHeight = outputResolutionCollection[1];
int outputResolutionOrientation = outputResolutionCollection[2]; int outputResolutionOrientation = outputResolutionCollection[2];
faceCollection = _Faces.GetFaces(dResultsFullGroupDirectory, subFileTuples, parseExceptions, item, property, resizedFileHolder, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation); faceCollection = _Faces.GetFaces(dResultsFullGroupDirectory, subFileTuples, parseExceptions, item, property, resizedFileHolder, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(D_Face.GetFaces)); ticks = LogDelta(ticks, nameof(D_Face.GetFaces));
_Faces.SaveFaces(dResultsFullGroupDirectory, subFileTuples, parseExceptions, item, faceCollection); _Faces.SaveFaces(dResultsFullGroupDirectory, subFileTuples, parseExceptions, item, faceCollection);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(D_Face.SaveFaces)); ticks = LogDelta(ticks, nameof(D_Face.SaveFaces));
if (_Configuration.SaveFaceLandmarkForOutputResolutions.Contains(outputResolution)) if (_Configuration.SaveFaceLandmarkForOutputResolutions.Contains(outputResolution))
{ {
_FaceLandmarks.SaveFaceLandmarkImages(d2ResultsFullGroupDirectory, sourceDirectory, subFileTuples, parseExceptions, item, faceCollection); _FaceLandmarks.SaveFaceLandmarkImages(d2ResultsFullGroupDirectory, sourceDirectory, subFileTuples, parseExceptions, item, faceCollection);
if (_AppSettings.MaxDegreeOfParallelism.Value < 2) if (_AppSettings.MaxDegreeOfParallelism < 2)
ticks = LogDelta(ticks, nameof(D2_FaceLandmarks.SaveFaceLandmarkImages)); ticks = LogDelta(ticks, nameof(D2_FaceLandmarks.SaveFaceLandmarkImages));
} }
} }
@ -402,9 +327,7 @@ public class DlibDotNet
int result = 0; int result = 0;
if (_Log is null) if (_Log is null)
throw new NullReferenceException(nameof(_Log)); throw new NullReferenceException(nameof(_Log));
if (_AppSettings.MaxDegreeOfParallelism is null) ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = _AppSettings.MaxDegreeOfParallelism };
throw new NullReferenceException(nameof(AppSettings.MaxDegreeOfParallelism));
ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = _AppSettings.MaxDegreeOfParallelism.Value };
ProgressBarOptions options = new() { ProgressCharacter = '─', ProgressBarOnBottom = true, DisableBottomPercentage = true }; ProgressBarOptions options = new() { ProgressCharacter = '─', ProgressBarOnBottom = true, DisableBottomPercentage = true };
if (faceCollections.Count != filteredItems.Length || metadataCollection.Count != filteredItems.Length || resizeKeyValuePairs.Count != filteredItems.Length || propertyCollection.Count != filteredItems.Length) if (faceCollections.Count != filteredItems.Length || metadataCollection.Count != filteredItems.Length || resizeKeyValuePairs.Count != filteredItems.Length || propertyCollection.Count != filteredItems.Length)
{ {
@ -478,14 +401,8 @@ public class DlibDotNet
private void WriteGroup(Property.Models.Configuration configuration, PropertyLogic propertyLogic, List<A_Property> propertyCollection, List<List<KeyValuePair<string, string>>> metadataCollection, List<List<D_Face>> faceCollections, List<Dictionary<string, int[]>> resizeKeyValuePairs, string sourceDirectory, string outputResolution, Item[] filteredItems) private void WriteGroup(Property.Models.Configuration configuration, PropertyLogic propertyLogic, List<A_Property> propertyCollection, List<List<KeyValuePair<string, string>>> metadataCollection, List<List<D_Face>> faceCollections, List<Dictionary<string, int[]>> resizeKeyValuePairs, string sourceDirectory, string outputResolution, Item[] filteredItems)
{ {
if (_Configuration.PropertiesChangedForMetadata is null)
throw new NullReferenceException(nameof(_Configuration.PropertiesChangedForMetadata));
if (configuration.PropertiesChangedForProperty is null) if (configuration.PropertiesChangedForProperty is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForProperty)); throw new NullReferenceException(nameof(configuration.PropertiesChangedForProperty));
if (_Configuration.PropertiesChangedForResize is null)
throw new NullReferenceException(nameof(_Configuration.PropertiesChangedForResize));
if (_Configuration.PropertiesChangedForFaces is null)
throw new NullReferenceException(nameof(_Configuration.PropertiesChangedForFaces));
Item item; Item item;
string key; string key;
string json; string json;
@ -560,67 +477,27 @@ public class DlibDotNet
} }
} }
private void FullDoWork(Property.Models.Configuration configuration, Model? model, PredictorModel? predictorModel, string argZero, Dictionary<string, List<Person>> peopleCollection, PropertyLogic propertyLogic, List<Container> containers, bool isSilent) private (string, string, string, string, string, string, string) GetResultsFullGroupDirectories(Property.Models.Configuration configuration, Model? model, PredictorModel? predictorModel, string outputResolution)
{ {
if (_Log is null) string aResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
throw new NullReferenceException(nameof(_Log));
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration.SaveResizedSubfiles is null)
throw new NullReferenceException(nameof(_Configuration.SaveResizedSubfiles));
int[] ids;
int distinctCount;
int exceptionCount;
Item[] filteredItems;
long ticks = DateTime.Now.Ticks;
string aResultsFullGroupDirectory;
string bResultsFullGroupDirectory;
string cResultsFullGroupDirectory;
string dResultsFullGroupDirectory;
string eResultsFullGroupDirectory;
string zResultsFullGroupDirectory;
string d2ResultsFullGroupDirectory;
List<List<D_Face>> faceCollections = new();
List<A_Property> propertyCollection = new();
List<FileHolder?> propertyFileHolderCollection = new();
List<Dictionary<string, int[]>> resizeKeyValuePairs = new();
List<Tuple<string, DateTime>> sourceDirectoryChanges = new();
List<List<KeyValuePair<string, string>>> metadataCollection = new();
string aPropertySingletonDirectory = Property.Models.Stateless.IResult.GetResultsDateGroupDirectory(configuration, nameof(A_Property), "{}");
string propertyRoot = Property.Models.Stateless.IResult.GetResultsGroupDirectory(configuration, nameof(A_Property));
foreach (string outputResolution in _Configuration.OutputResolutions)
{
_FileKeyValuePairs.Clear();
_FilePropertiesKeyValuePairs.Clear();
aResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, nameof(A_Property), outputResolution, includeResizeGroup: false, includeModel: false, includePredictorModel: false); configuration, model, predictorModel, nameof(A_Property), outputResolution, includeResizeGroup: false, includeModel: false, includePredictorModel: false);
bResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory( string bResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, nameof(B_Metadata), outputResolution, includeResizeGroup: false, includeModel: false, includePredictorModel: false); configuration, model, predictorModel, nameof(B_Metadata), outputResolution, includeResizeGroup: false, includeModel: false, includePredictorModel: false);
cResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory( string cResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, nameof(C_Resize), outputResolution, includeResizeGroup: true, includeModel: false, includePredictorModel: false); configuration, model, predictorModel, nameof(C_Resize), outputResolution, includeResizeGroup: true, includeModel: false, includePredictorModel: false);
d2ResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory( string dResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, nameof(D2_FaceLandmarks), outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true);
dResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, nameof(D_Face), outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true); configuration, model, predictorModel, nameof(D_Face), outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true);
eResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory( string d2ResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, nameof(D2_FaceLandmarks), outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true);
string eResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, nameof(E_Distance), outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true); configuration, model, predictorModel, nameof(E_Distance), outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true);
zResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory( string zResultsFullGroupDirectory = Property.Models.Stateless.IResult.GetResultsFullGroupDirectory(
configuration, model, predictorModel, $"Z_{nameof(Item)}", outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true); configuration, model, predictorModel, $"Z_{nameof(Item)}", outputResolution, includeResizeGroup: true, includeModel: true, includePredictorModel: true);
foreach (Container container in containers) return new(aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory, d2ResultsFullGroupDirectory, eResultsFullGroupDirectory, zResultsFullGroupDirectory);
}
private void SetAngleBracketCollections(Property.Models.Configuration configuration, PropertyLogic propertyLogic, string outputResolution, Container container, string aResultsFullGroupDirectory, string bResultsFullGroupDirectory, string cResultsFullGroupDirectory, string dResultsFullGroupDirectory)
{ {
if (!container.Items.Any())
continue;
if (!_ArgZeroIsConfigurationRootDirectory && !container.SourceDirectory.StartsWith(argZero))
continue;
filteredItems = (from l in container.Items where l.ImageFileHolder is not null && (l.Abandoned is null || !l.Abandoned.Value) && l.ValidImageFormatExtension && !_Configuration.IgnoreExtensions.Contains(l.ImageFileHolder.ExtensionLowered) select l).ToArray();
if (!filteredItems.Any())
continue;
faceCollections.Clear();
metadataCollection.Clear();
propertyCollection.Clear();
resizeKeyValuePairs.Clear();
sourceDirectoryChanges.Clear();
propertyFileHolderCollection.Clear();
_Faces.AngleBracketCollection.Clear(); _Faces.AngleBracketCollection.Clear();
_Resize.AngleBracketCollection.Clear(); _Resize.AngleBracketCollection.Clear();
_Metadata.AngleBracketCollection.Clear(); _Metadata.AngleBracketCollection.Clear();
@ -654,6 +531,52 @@ public class DlibDotNet
singletonDescription: string.Empty, singletonDescription: string.Empty,
collectionDescription: "For each image a json file with all faces found", collectionDescription: "For each image a json file with all faces found",
converted: true)); converted: true));
}
private void FullDoWork(bool isSilent, string argZero, Property.Models.Configuration configuration, Model? model, PredictorModel? predictorModel, long ticks, Dictionary<string, List<Person>> peopleCollection, PropertyLogic propertyLogic, List<Container> containers)
{
if (_Log is null)
throw new NullReferenceException(nameof(_Log));
int[] ids;
int distinctCount;
int exceptionCount;
Item[] filteredItems;
string aResultsFullGroupDirectory;
string bResultsFullGroupDirectory;
string cResultsFullGroupDirectory;
string dResultsFullGroupDirectory;
string eResultsFullGroupDirectory;
string zResultsFullGroupDirectory;
string d2ResultsFullGroupDirectory;
List<List<D_Face>> faceCollections = new();
List<A_Property> propertyCollection = new();
List<FileHolder?> propertyFileHolderCollection = new();
List<Dictionary<string, int[]>> resizeKeyValuePairs = new();
List<Tuple<string, DateTime>> sourceDirectoryChanges = new();
List<List<KeyValuePair<string, string>>> metadataCollection = new();
string aPropertySingletonDirectory = Property.Models.Stateless.IResult.GetResultsDateGroupDirectory(configuration, nameof(A_Property), "{}");
string propertyRoot = Property.Models.Stateless.IResult.GetResultsGroupDirectory(configuration, nameof(A_Property));
foreach (string outputResolution in _Configuration.OutputResolutions)
{
_FileKeyValuePairs.Clear();
_FilePropertiesKeyValuePairs.Clear();
(aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory, d2ResultsFullGroupDirectory, eResultsFullGroupDirectory, zResultsFullGroupDirectory) = GetResultsFullGroupDirectories(configuration, model, predictorModel, outputResolution);
foreach (Container container in containers)
{
if (!container.Items.Any())
continue;
if (!_ArgZeroIsConfigurationRootDirectory && !container.SourceDirectory.StartsWith(argZero))
continue;
filteredItems = (from l in container.Items where l.ImageFileHolder is not null && (l.Abandoned is null || !l.Abandoned.Value) && l.ValidImageFormatExtension && !_Configuration.IgnoreExtensions.Contains(l.ImageFileHolder.ExtensionLowered) select l).ToArray();
if (!filteredItems.Any())
continue;
faceCollections.Clear();
metadataCollection.Clear();
propertyCollection.Clear();
resizeKeyValuePairs.Clear();
sourceDirectoryChanges.Clear();
propertyFileHolderCollection.Clear();
SetAngleBracketCollections(configuration, propertyLogic, outputResolution, container, aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory);
exceptionCount = FullParallelWork(ticks, propertyLogic, outputResolution, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory, d2ResultsFullGroupDirectory, sourceDirectoryChanges, propertyFileHolderCollection, propertyCollection, metadataCollection, resizeKeyValuePairs, faceCollections, containers.Count, container, filteredItems); exceptionCount = FullParallelWork(ticks, propertyLogic, outputResolution, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory, d2ResultsFullGroupDirectory, sourceDirectoryChanges, propertyFileHolderCollection, propertyCollection, metadataCollection, resizeKeyValuePairs, faceCollections, containers.Count, container, filteredItems);
#pragma warning disable #pragma warning disable
ids = (from l in filteredItems where l.Property?.Id is not null select l.Property.Id.Value).ToArray(); ids = (from l in filteredItems where l.Property?.Id is not null select l.Property.Id.Value).ToArray();
@ -665,14 +588,24 @@ public class DlibDotNet
throw new Exception("Counts don't match!"); throw new Exception("Counts don't match!");
if (exceptionCount != 0) if (exceptionCount != 0)
_Exceptions.Add(container.SourceDirectory); _Exceptions.Add(container.SourceDirectory);
for (int i = 0; i < faceCollections.Count; i++)
filteredItems[i].Faces.AddRange(from l in faceCollections[i] select l);
if (_ArgZeroIsConfigurationRootDirectory && exceptionCount == 0) if (_ArgZeroIsConfigurationRootDirectory && exceptionCount == 0)
WriteGroup(configuration, propertyLogic, propertyCollection, metadataCollection, faceCollections, resizeKeyValuePairs, container.SourceDirectory, outputResolution, filteredItems); WriteGroup(configuration, propertyLogic, propertyCollection, metadataCollection, faceCollections, resizeKeyValuePairs, container.SourceDirectory, outputResolution, filteredItems);
if (_ArgZeroIsConfigurationRootDirectory && exceptionCount == 0 && outputResolution == _Configuration.OutputResolutions[0]) if (_ArgZeroIsConfigurationRootDirectory && exceptionCount == 0 && outputResolution == _Configuration.OutputResolutions[0])
propertyLogic.AddToPropertyLogicAllCollection(filteredItems); propertyLogic.AddToPropertyLogicAllCollection(filteredItems);
if (_ArgZeroIsConfigurationRootDirectory && exceptionCount == 0 && propertyLogic.NamedFaceInfoDeterministicHashCodeIds.Any()) if (exceptionCount == 0 && _Configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions.Contains(outputResolution))
_Distance.LoadOrCreateThenSaveDistanceResults(configuration, eResultsFullGroupDirectory, container.SourceDirectory, outputResolution, sourceDirectoryChanges, filteredItems);
if (Directory.GetFiles(propertyRoot, "*.txt", SearchOption.TopDirectoryOnly).Any())
{ {
if (outputResolution == _Configuration.OutputResolutions[0] || _Configuration.SaveShortcutsForOutputResolutions.Contains(outputResolution)) for (int y = 0; y < int.MaxValue; y++)
{ {
_Log.Information("Press \"Y\" key when ready to continue or close console");
if (System.Console.ReadKey().Key == ConsoleKey.Y)
break;
}
_Log.Information(". . .");
}
if (isSilent && container.SourceDirectory.EndsWith("Bohdi Ray 2016")) // 7#.1 if (isSilent && container.SourceDirectory.EndsWith("Bohdi Ray 2016")) // 7#.1
break; break;
// if (isSilent && container.SourceDirectory.EndsWith("Halloween 2013")) // 12#.1 // if (isSilent && container.SourceDirectory.EndsWith("Halloween 2013")) // 12#.1
@ -685,26 +618,42 @@ public class DlibDotNet
// break; // break;
// if (isSilent && container.SourceDirectory.EndsWith("Texas 2015")) //46#.4 // if (isSilent && container.SourceDirectory.EndsWith("Texas 2015")) //46#.4
// break; // break;
for (int i = 0; i < faceCollections.Count; i++)
filteredItems[i].Faces.AddRange(from l in faceCollections[i] select l);
Item.AddToNamed(propertyLogic, filteredItems);
if (_Configuration.SaveShortcutsForOutputResolutions.Contains(outputResolution))
D_Face.SaveShortcuts(_Configuration.JuliePhares, dResultsFullGroupDirectory, ticks, peopleCollection, propertyLogic, filteredItems);
} }
} }
if (exceptionCount == 0 && _Configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions.Contains(outputResolution)) }
_Distance.LoadOrCreateThenSaveDistanceResultsForOutputResolutions(configuration, eResultsFullGroupDirectory, container.SourceDirectory, outputResolution, sourceDirectoryChanges, filteredItems, faceCollections);
if (Directory.GetFiles(propertyRoot, "*.txt", SearchOption.TopDirectoryOnly).Any()) private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel)
{ {
for (int y = 0; y < int.MaxValue; y++) PropertyLogic result;
if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
result = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, reverse, model, predictorModel);
return result;
}
private void Search(Property.Models.Configuration configuration, bool reverse, Model? model, PredictorModel? predictorModel, string argZero, Person[] people, bool isSilent)
{ {
_Log.Information("Press \"Y\" key when ready to continue or close console"); if (_Log is null)
if (System.Console.ReadKey().Key == ConsoleKey.Y) throw new NullReferenceException(nameof(_Log));
break; List<Container> containers;
} long ticks = DateTime.Now.Ticks;
_Log.Information(". . ."); string aResultsFullGroupDirectory;
} string bResultsFullGroupDirectory;
} string cResultsFullGroupDirectory;
string dResultsFullGroupDirectory;
string eResultsFullGroupDirectory;
string zResultsFullGroupDirectory;
string d2ResultsFullGroupDirectory;
Dictionary<string, List<Person>> peopleCollection = A2_People.Convert(people);
PropertyLogic propertyLogic = GetPropertyLogic(reverse, model, predictorModel);
if (string.IsNullOrEmpty(configuration.RootDirectory))
containers = Property.Models.Stateless.A_Property.Get(configuration, propertyLogic);
else
containers = Property.Models.Stateless.Container.GetContainers(configuration, propertyLogic);
FullDoWork(isSilent, argZero, configuration, model, predictorModel, ticks, peopleCollection, propertyLogic, containers);
foreach (string outputResolution in _Configuration.OutputResolutions)
{
(aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory, d2ResultsFullGroupDirectory, eResultsFullGroupDirectory, zResultsFullGroupDirectory) = GetResultsFullGroupDirectories(configuration, model, predictorModel, outputResolution);
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(aResultsFullGroupDirectory, "{}")); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(aResultsFullGroupDirectory, "{}"));
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(bResultsFullGroupDirectory, "{}")); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(bResultsFullGroupDirectory, "{}"));
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(cResultsFullGroupDirectory, "{}")); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(cResultsFullGroupDirectory, "{}"));
@ -716,10 +665,18 @@ public class DlibDotNet
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(eResultsFullGroupDirectory, "[]")); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(eResultsFullGroupDirectory, "[]"));
if (_Configuration.SaveFaceLandmarkForOutputResolutions.Contains(outputResolution)) if (_Configuration.SaveFaceLandmarkForOutputResolutions.Contains(outputResolution))
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(d2ResultsFullGroupDirectory, "[]")); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(Path.Combine(d2ResultsFullGroupDirectory, "[]"));
if (_ArgZeroIsConfigurationRootDirectory && outputResolution == _Configuration.OutputResolutions[0]) if (_ArgZeroIsConfigurationRootDirectory && _Exceptions.Count == 0 && outputResolution == _Configuration.OutputResolutions[0] && (propertyLogic.NamedFaceInfoDeterministicHashCodeKeyValuePairs.Any() || propertyLogic.NamedDeterministicHashCodeKeyValuePairs.Any()))
{ {
if (!string.IsNullOrEmpty(propertyLogic.DeterministicHashCodeRootDirectory) && !propertyLogic.IncorrectDeterministicHashCodeKeyValuePairs.Any())
propertyLogic.UpdateKeyValuePairs(containers);
foreach (Container container in containers)
{
Item.AddToNamed(propertyLogic, container.Items);
if (_Configuration.SaveShortcutsForOutputResolutions.Contains(outputResolution))
D_Face.SaveShortcuts(_Configuration.JuliePhares, dResultsFullGroupDirectory, ticks, peopleCollection, propertyLogic, container.Items);
}
propertyLogic.SaveAllCollection(); propertyLogic.SaveAllCollection();
if (_Configuration.SaveResizedSubfiles.Value && propertyLogic.NamedFaceInfoDeterministicHashCodeIds.Any()) if (_Configuration.SaveResizedSubfiles)
{ {
string dFacesContentDirectory; string dFacesContentDirectory;
string eDistanceContentDirectory; string eDistanceContentDirectory;
@ -730,19 +687,17 @@ public class DlibDotNet
zPropertyHolderSingletonDirectory = Path.Combine(zResultsFullGroupDirectory, "{}"); zPropertyHolderSingletonDirectory = Path.Combine(zResultsFullGroupDirectory, "{}");
eDistanceCollectionDirectory = Path.Combine(eResultsFullGroupDirectory, $"[{ticks}]"); eDistanceCollectionDirectory = Path.Combine(eResultsFullGroupDirectory, $"[{ticks}]");
List<(DateTime, bool?, PersonBirthday, FaceRecognitionDotNet.FaceEncoding[])> collection; List<(DateTime, bool?, PersonBirthday, FaceRecognitionDotNet.FaceEncoding[])> collection;
collection = E_Distance.ParallelWork(_AppSettings.MaxDegreeOfParallelism.Value, argZero, containers); collection = E_Distance.ParallelWork(_AppSettings.MaxDegreeOfParallelism, argZero, propertyLogic, containers);
_ = LogDelta(ticks, nameof(E_Distance.ParallelWork)); _ = LogDeltaInMinutes(ticks, nameof(E_Distance.ParallelWork));
E_Distance.SavePropertyHolders(argZero, containers, zPropertyHolderSingletonDirectory); E_Distance.SavePropertyHolders(argZero, containers, zPropertyHolderSingletonDirectory);
_ = LogDelta(ticks, nameof(E_Distance.SavePropertyHolders)); _ = LogDeltaInMinutes(ticks, nameof(E_Distance.SavePropertyHolders));
E_Distance.SaveThreeSigmaFaceEncodings(collection, peopleCollection, eDistanceCollectionDirectory); E_Distance.SaveThreeSigmaFaceEncodings(collection, peopleCollection, eDistanceCollectionDirectory);
_ = LogDelta(ticks, nameof(E_Distance.SaveThreeSigmaFaceEncodings)); _ = LogDeltaInMinutes(ticks, nameof(E_Distance.SaveThreeSigmaFaceEncodings));
E_Distance.SaveClosest(argZero, containers, peopleCollection, propertyLogic, eDistanceContentDirectory, dFacesContentDirectory); E_Distance.SaveClosest(argZero, containers, peopleCollection, eDistanceContentDirectory, dFacesContentDirectory);
_ = LogDelta(ticks, nameof(E_Distance.SaveClosest)); _ = LogDeltaInMinutes(ticks, nameof(E_Distance.SaveClosest));
} }
if (!_Configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions.Any()) if (!_Configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions.Any())
break; break;
if (_Exceptions.Count == 0)
{
if (_FileKeyValuePairs.Any()) if (_FileKeyValuePairs.Any())
_Random.Random(configuration, _Configuration.OutputResolutions[0], _FileKeyValuePairs); _Random.Random(configuration, _Configuration.OutputResolutions[0], _FileKeyValuePairs);
if (_IsEnvironment.Development) if (_IsEnvironment.Development)
@ -751,35 +706,11 @@ public class DlibDotNet
List<G2_Identify> identifiedCollection = identify.GetIdentifiedCollection(configuration, _IsEnvironment, _People); List<G2_Identify> identifiedCollection = identify.GetIdentifiedCollection(configuration, _IsEnvironment, _People);
_People.WriteAllText(configuration, _Configuration.OutputResolutions[0], identifiedCollection); _People.WriteAllText(configuration, _Configuration.OutputResolutions[0], identifiedCollection);
identify.WriteAllText(configuration, _Configuration.OutputResolutions[0], identifiedCollection); identify.WriteAllText(configuration, _Configuration.OutputResolutions[0], identifiedCollection);
if (_Configuration.LoadOrCreateThenSaveIndex.HasValue && _Configuration.LoadOrCreateThenSaveIndex.Value && _FilePropertiesKeyValuePairs.Any()) if (_Configuration.LoadOrCreateThenSaveIndex && _FilePropertiesKeyValuePairs.Any())
_Index.SetIndex(configuration, model, predictorModel, _Configuration.OutputResolutions[0], _FilePropertiesKeyValuePairs); _Index.SetIndex(configuration, model, predictorModel, _Configuration.OutputResolutions[0], _FilePropertiesKeyValuePairs);
} }
} }
} }
}
private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel)
{
PropertyLogic result;
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
result = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, reverse, model, predictorModel);
return result;
}
private void Search(Property.Models.Configuration configuration, bool reverse, Model? model, PredictorModel? predictorModel, string argZero, Person[] people, bool isSilent)
{
List<Container> containers;
Dictionary<string, List<Person>> peopleCollection = A2_People.Convert(people);
PropertyLogic propertyLogic = GetPropertyLogic(reverse, model, predictorModel);
if (string.IsNullOrEmpty(configuration.RootDirectory))
containers = Property.Models.Stateless.A_Property.Get(configuration, propertyLogic);
else
containers = Property.Models.Stateless.Container.GetContainers(configuration, propertyLogic);
FullDoWork(configuration, model, predictorModel, argZero, peopleCollection, propertyLogic, containers, isSilent);
}
internal void RenameQueue(Property.Models.Configuration configuration, Model? model, PredictorModel? predictorModel) => _Rename.RenameQueue(configuration, model, predictorModel); internal void RenameQueue(Property.Models.Configuration configuration, Model? model, PredictorModel? predictorModel) => _Rename.RenameQueue(configuration, model, predictorModel);

View File

@ -6,24 +6,16 @@ namespace View_by_Distance.Instance.Models;
public class AppSettings public class AppSettings
{ {
protected string _Company; public string Company { init; get; }
protected string _WorkingDirectoryName; public int MaxDegreeOfParallelism { init; get; }
protected int? _MaxDegreeOfParallelism; public string WorkingDirectoryName { init; get; }
public string Company => _Company;
public string WorkingDirectoryName => _WorkingDirectoryName;
public int? MaxDegreeOfParallelism => _MaxDegreeOfParallelism;
// public AppSettings()
// {
// }
[JsonConstructor] [JsonConstructor]
public AppSettings(string company, string workingDirectoryName, int? maxDegreeOfParallelism) public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{ {
_Company = company; Company = company;
_WorkingDirectoryName = workingDirectoryName; MaxDegreeOfParallelism = maxDegreeOfParallelism;
_MaxDegreeOfParallelism = maxDegreeOfParallelism; WorkingDirectoryName = workingDirectoryName;
} }
public override string ToString() public override string ToString()

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Configuration;
using System.Text.Json; using System.Text.Json;
namespace View_by_Distance.Instance.Models.Binder; namespace View_by_Distance.Instance.Models.Binder;
@ -6,16 +6,13 @@ namespace View_by_Distance.Instance.Models.Binder;
public class AppSettings public class AppSettings
{ {
[Display(Name = "Company"), Required] public string Company { get; set; } #nullable disable
[Display(Name = "Working Directory Name"), Required] public string WorkingDirectoryName { get; set; }
[Display(Name = "Max Degree Of Parallelism"), Required] public int? MaxDegreeOfParallelism { get; set; }
public AppSettings() public string Company { get; set; }
{ public int? MaxDegreeOfParallelism { get; set; }
Company = string.Empty; public string WorkingDirectoryName { get; set; }
WorkingDirectoryName = string.Empty;
MaxDegreeOfParallelism = -1; #nullable restore
}
public override string ToString() public override string ToString()
{ {
@ -23,4 +20,25 @@ public class AppSettings
return result; return result;
} }
private static Models.AppSettings Get(AppSettings appSettings)
{
Models.AppSettings result;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
} }

View File

@ -1,3 +1,5 @@
using Microsoft.Extensions.Configuration;
using Phares.Shared;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json; using System.Text.Json;
@ -6,9 +8,12 @@ namespace View_by_Distance.Instance.Models.Binder;
public class Configuration public class Configuration
{ {
#nullable disable
[Display(Name = "Check Json For Distance Results"), Required] public bool? CheckJsonForDistanceResults { get; set; } [Display(Name = "Check Json For Distance Results"), Required] public bool? CheckJsonForDistanceResults { get; set; }
[Display(Name = "CrossDirectory Max Items In Distance Collection"), Required] public int? CrossDirectoryMaxItemsInDistanceCollection { get; set; } [Display(Name = "CrossDirectory Max Items In Distance Collection"), Required] public int? CrossDirectoryMaxItemsInDistanceCollection { get; set; }
[Display(Name = "Distance Factor"), Required] public int? DistanceFactor { get; set; } [Display(Name = "Distance Factor"), Required] public int? DistanceFactor { get; set; }
[Display(Name = "Force Face Last Write Time to Creation Time"), Required] public bool? ForceFaceLastWriteTimeToCreationTime { get; set; }
[Display(Name = "Force Metadata Last Write Time to Creation Time"), Required] public bool? ForceMetadataLastWriteTimeToCreationTime { get; set; } [Display(Name = "Force Metadata Last Write Time to Creation Time"), Required] public bool? ForceMetadataLastWriteTimeToCreationTime { get; set; }
[Display(Name = "Force Resize Last Write Time to Creation Time"), Required] public bool? ForceResizeLastWriteTimeToCreationTime { get; set; } [Display(Name = "Force Resize Last Write Time to Creation Time"), Required] public bool? ForceResizeLastWriteTimeToCreationTime { get; set; }
[Display(Name = "Ignore Extensions"), Required] public string[] IgnoreExtensions { get; set; } [Display(Name = "Ignore Extensions"), Required] public string[] IgnoreExtensions { get; set; }
@ -39,7 +44,7 @@ public class Configuration
[Display(Name = "Properties Changed For Index"), Required] public bool? PropertiesChangedForIndex { get; set; } [Display(Name = "Properties Changed For Index"), Required] public bool? PropertiesChangedForIndex { get; set; }
[Display(Name = "Properties Changed For Metadata"), Required] public bool? PropertiesChangedForMetadata { get; set; } [Display(Name = "Properties Changed For Metadata"), Required] public bool? PropertiesChangedForMetadata { get; set; }
[Display(Name = "Properties Changed For Resize"), Required] public bool? PropertiesChangedForResize { get; set; } [Display(Name = "Properties Changed For Resize"), Required] public bool? PropertiesChangedForResize { get; set; }
[Display(Name = "Property Configuration"), Required] public Property.Models.Configuration? PropertyConfiguration { get; set; } [Display(Name = "Property Configuration"), Required] public Property.Models.Configuration PropertyConfiguration { get; set; }
[Display(Name = "Reverse"), Required] public bool? Reverse { get; set; } [Display(Name = "Reverse"), Required] public bool? Reverse { get; set; }
[Display(Name = "Save Face Landmark For Output Resolutions"), Required] public string[] SaveFaceLandmarkForOutputResolutions { get; set; } [Display(Name = "Save Face Landmark For Output Resolutions"), Required] public string[] SaveFaceLandmarkForOutputResolutions { get; set; }
[Display(Name = "Save Full Year Of Random Files"), Required] public bool? SaveFullYearOfRandomFiles { get; set; } [Display(Name = "Save Full Year Of Random Files"), Required] public bool? SaveFullYearOfRandomFiles { get; set; }
@ -49,50 +54,7 @@ public class Configuration
[Display(Name = "Test Distance Results"), Required] public bool? TestDistanceResults { get; set; } [Display(Name = "Test Distance Results"), Required] public bool? TestDistanceResults { get; set; }
[Display(Name = "Valid Resolutions"), Required] public string[] ValidResolutions { get; set; } [Display(Name = "Valid Resolutions"), Required] public string[] ValidResolutions { get; set; }
public Configuration() #nullable restore
{
CheckJsonForDistanceResults = null;
CrossDirectoryMaxItemsInDistanceCollection = null;
DistanceFactor = null;
ForceMetadataLastWriteTimeToCreationTime = null;
ForceResizeLastWriteTimeToCreationTime = null;
IgnoreExtensions = Array.Empty<string>();
IgnoreRelativePaths = Array.Empty<string>();
JuliePhares = Array.Empty<string>();
LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions = Array.Empty<string>();
LoadOrCreateThenSaveDistanceResultsForOutputResolutions = Array.Empty<string>();
LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = Array.Empty<string>();
LoadOrCreateThenSaveIndex = null;
LocationConfidenceFactor = null;
MappedMaxIndex = null;
MaxItemsInDistanceCollection = null;
MixedYearRelativePaths = Array.Empty<string>();
ModelDirectory = string.Empty;
ModelName = string.Empty;
NumberOfJitters = null;
NumberOfTimesToUpsample = null;
OutputExtension = string.Empty;
OutputQuality = null;
OutputResolutions = Array.Empty<string>();
OverrideForFaceImages = null;
OverrideForFaceLandmarkImages = null;
OverrideForResizeImages = null;
PaddingLoops = null;
PredictorModelName = string.Empty;
PropertiesChangedForDistance = null;
PropertiesChangedForFaces = null;
PropertiesChangedForIndex = null;
PropertiesChangedForMetadata = null;
PropertiesChangedForResize = null;
Reverse = null;
SaveFaceLandmarkForOutputResolutions = Array.Empty<string>();
SaveFullYearOfRandomFiles = null;
SaveResizedSubfiles = null;
SaveShortcutsForOutputResolutions = Array.Empty<string>();
SkipSearch = null;
TestDistanceResults = null;
ValidResolutions = Array.Empty<string>();
}
public override string ToString() public override string ToString()
{ {
@ -100,4 +62,146 @@ public class Configuration
return result; return result;
} }
private static Models.Configuration Get(Configuration configuration)
{
Models.Configuration result;
if (configuration.CheckJsonForDistanceResults is null)
throw new NullReferenceException(nameof(configuration.CheckJsonForDistanceResults));
if (configuration.CrossDirectoryMaxItemsInDistanceCollection is null)
throw new NullReferenceException(nameof(configuration.CrossDirectoryMaxItemsInDistanceCollection));
if (configuration.DistanceFactor is null)
throw new NullReferenceException(nameof(configuration.DistanceFactor));
if (configuration.ForceFaceLastWriteTimeToCreationTime is null)
throw new NullReferenceException(nameof(configuration.ForceFaceLastWriteTimeToCreationTime));
if (configuration.ForceMetadataLastWriteTimeToCreationTime is null)
throw new NullReferenceException(nameof(configuration.ForceMetadataLastWriteTimeToCreationTime));
if (configuration.ForceResizeLastWriteTimeToCreationTime is null)
throw new NullReferenceException(nameof(configuration.ForceResizeLastWriteTimeToCreationTime));
if (configuration.IgnoreExtensions is null)
throw new NullReferenceException(nameof(configuration.IgnoreExtensions));
if (configuration.IgnoreRelativePaths is null)
throw new NullReferenceException(nameof(configuration.IgnoreRelativePaths));
if (configuration.LoadOrCreateThenSaveIndex is null)
throw new NullReferenceException(nameof(configuration.LoadOrCreateThenSaveIndex));
if (configuration.LocationConfidenceFactor is null)
throw new NullReferenceException(nameof(configuration.LocationConfidenceFactor));
if (configuration.MaxItemsInDistanceCollection is null)
throw new NullReferenceException(nameof(configuration.MaxItemsInDistanceCollection));
if (configuration.MixedYearRelativePaths is null)
throw new NullReferenceException(nameof(configuration.MixedYearRelativePaths));
if (configuration.NumberOfJitters is null)
throw new NullReferenceException(nameof(configuration.NumberOfJitters));
if (configuration.NumberOfTimesToUpsample is null)
throw new NullReferenceException(nameof(configuration.NumberOfTimesToUpsample));
if (configuration.OutputQuality is null)
throw new NullReferenceException(nameof(configuration.OutputQuality));
if (configuration.OutputResolutions is null)
throw new NullReferenceException(nameof(configuration.OutputResolutions));
if (configuration.OverrideForFaceImages is null)
throw new NullReferenceException(nameof(configuration.OverrideForFaceImages));
if (configuration.OverrideForFaceLandmarkImages is null)
throw new NullReferenceException(nameof(configuration.OverrideForFaceLandmarkImages));
if (configuration.OverrideForResizeImages is null)
throw new NullReferenceException(nameof(configuration.OverrideForResizeImages));
if (configuration.PaddingLoops is null)
throw new NullReferenceException(nameof(configuration.PaddingLoops));
if (configuration.PropertiesChangedForDistance is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForDistance));
if (configuration.PropertiesChangedForFaces is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForFaces));
if (configuration.PropertiesChangedForIndex is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForIndex));
if (configuration.PropertiesChangedForMetadata is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForMetadata));
if (configuration.PropertiesChangedForResize is null)
throw new NullReferenceException(nameof(configuration.PropertiesChangedForResize));
if (configuration.Reverse is null)
throw new NullReferenceException(nameof(configuration.Reverse));
if (configuration.SaveFaceLandmarkForOutputResolutions is null)
throw new NullReferenceException(nameof(configuration.SaveFaceLandmarkForOutputResolutions));
if (configuration.SaveFullYearOfRandomFiles is null)
throw new NullReferenceException(nameof(configuration.SaveFullYearOfRandomFiles));
if (configuration.SaveResizedSubfiles is null)
throw new NullReferenceException(nameof(configuration.SaveResizedSubfiles));
if (configuration.SkipSearch is null)
throw new NullReferenceException(nameof(configuration.SkipSearch));
if (configuration.TestDistanceResults is null)
throw new NullReferenceException(nameof(configuration.TestDistanceResults));
if (configuration.ValidResolutions is null)
throw new NullReferenceException(nameof(configuration.ValidResolutions));
if (configuration.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions is null)
configuration.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions = Array.Empty<string>();
if (configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions is null)
configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions = Array.Empty<string>();
if (configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions is null)
configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = Array.Empty<string>();
if (configuration.SaveFaceLandmarkForOutputResolutions is null)
configuration.SaveFaceLandmarkForOutputResolutions = Array.Empty<string>();
if (configuration.SaveShortcutsForOutputResolutions is null)
configuration.SaveShortcutsForOutputResolutions = Array.Empty<string>();
result = new(configuration.PropertyConfiguration,
configuration.CheckJsonForDistanceResults.Value,
configuration.CrossDirectoryMaxItemsInDistanceCollection.Value,
configuration.DistanceFactor.Value,
configuration.ForceFaceLastWriteTimeToCreationTime.Value,
configuration.ForceMetadataLastWriteTimeToCreationTime.Value,
configuration.ForceResizeLastWriteTimeToCreationTime.Value,
configuration.IgnoreExtensions,
configuration.IgnoreRelativePaths,
configuration.JuliePhares,
configuration.LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions,
configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions,
configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions,
configuration.LoadOrCreateThenSaveIndex.Value,
configuration.LocationConfidenceFactor.Value,
configuration.MappedMaxIndex,
configuration.MaxItemsInDistanceCollection.Value,
configuration.MixedYearRelativePaths,
configuration.ModelDirectory,
configuration.ModelName,
configuration.NumberOfJitters.Value,
configuration.NumberOfTimesToUpsample.Value,
configuration.OutputExtension,
configuration.OutputQuality.Value,
configuration.OutputResolutions,
configuration.OverrideForFaceImages.Value,
configuration.OverrideForFaceLandmarkImages.Value,
configuration.OverrideForResizeImages.Value,
configuration.PaddingLoops.Value,
configuration.PredictorModelName,
configuration.PropertiesChangedForDistance.Value,
configuration.PropertiesChangedForFaces.Value,
configuration.PropertiesChangedForIndex.Value,
configuration.PropertiesChangedForMetadata.Value,
configuration.PropertiesChangedForResize.Value,
configuration.Reverse.Value,
configuration.SaveFaceLandmarkForOutputResolutions,
configuration.SaveFullYearOfRandomFiles.Value,
configuration.SaveResizedSubfiles.Value,
configuration.SaveShortcutsForOutputResolutions,
configuration.SkipSearch.Value,
configuration.TestDistanceResults.Value,
configuration.ValidResolutions);
return result;
}
public static Models.Configuration Get(IsEnvironment isEnvironment, IConfigurationRoot configurationRoot, Property.Models.Configuration propertyConfiguration)
{
Models.Configuration result;
Configuration configuration;
if (isEnvironment is null)
configuration = configurationRoot.Get<Configuration>();
else
{
string environmentName = IsEnvironment.GetEnvironmentName(isEnvironment);
string section = string.Concat(environmentName, ":", nameof(Configuration));
IConfigurationSection configurationSection = configurationRoot.GetSection(section);
configuration = configurationSection.Get<Configuration>();
}
result = Get(configuration);
result.Set(propertyConfiguration);
result.Update();
return result;
}
} }

View File

@ -6,136 +6,98 @@ namespace View_by_Distance.Instance.Models;
public class Configuration public class Configuration
{ {
protected readonly bool? _CheckJsonForDistanceResults; protected Property.Models.Configuration _PropertyConfiguration;
protected readonly int? _CrossDirectoryMaxItemsInDistanceCollection; public Property.Models.Configuration PropertyConfiguration => _PropertyConfiguration;
protected readonly int? _DistanceFactor;
protected readonly bool? _ForceMetadataLastWriteTimeToCreationTime; public bool CheckJsonForDistanceResults { init; get; }
protected readonly bool? _ForceResizeLastWriteTimeToCreationTime; public int CrossDirectoryMaxItemsInDistanceCollection { init; get; }
protected readonly string[] _IgnoreExtensions; public int DistanceFactor { init; get; }
protected readonly string[] _IgnoreRelativePaths; public bool ForceFaceLastWriteTimeToCreationTime { init; get; }
protected readonly string[] _JuliePhares; public bool ForceMetadataLastWriteTimeToCreationTime { init; get; }
protected readonly string[] _LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions; public bool ForceResizeLastWriteTimeToCreationTime { init; get; }
protected readonly string[] _LoadOrCreateThenSaveDistanceResultsForOutputResolutions; public string[] IgnoreExtensions { init; get; }
protected readonly string[] _LoadOrCreateThenSaveImageFacesResultsForOutputResolutions; public string[] IgnoreRelativePaths { init; get; }
protected readonly bool? _LoadOrCreateThenSaveIndex; public string[] JuliePhares { init; get; }
protected readonly int? _LocationConfidenceFactor; public string[] LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions { init; get; }
protected readonly int? _MappedMaxIndex; public string[] LoadOrCreateThenSaveDistanceResultsForOutputResolutions { init; get; }
protected readonly int? _MaxItemsInDistanceCollection; public string[] LoadOrCreateThenSaveImageFacesResultsForOutputResolutions { init; get; }
protected readonly string[] _MixedYearRelativePaths; public bool LoadOrCreateThenSaveIndex { init; get; }
protected readonly string _ModelDirectory; public int LocationConfidenceFactor { init; get; }
protected readonly string _ModelName; public int? MappedMaxIndex { init; get; }
protected readonly int? _NumberOfJitters; public int MaxItemsInDistanceCollection { init; get; }
protected readonly int? _NumberOfTimesToUpsample; public string[] MixedYearRelativePaths { init; get; }
protected readonly string _OutputExtension; public string ModelDirectory { init; get; }
protected readonly int? _OutputQuality; public string ModelName { init; get; }
protected readonly string[] _OutputResolutions; public int NumberOfJitters { init; get; }
protected readonly bool? _OverrideForFaceImages; public int NumberOfTimesToUpsample { init; get; }
protected readonly bool? _OverrideForFaceLandmarkImages; public string OutputExtension { init; get; }
protected readonly bool? _OverrideForResizeImages; public int OutputQuality { init; get; }
protected readonly int? _PaddingLoops; public string[] OutputResolutions { init; get; }
protected readonly string _PredictorModelName; public bool OverrideForFaceImages { init; get; }
protected readonly bool? _PropertiesChangedForDistance; public bool OverrideForFaceLandmarkImages { init; get; }
protected readonly bool? _PropertiesChangedForFaces; public bool OverrideForResizeImages { init; get; }
protected readonly bool? _PropertiesChangedForIndex; public int PaddingLoops { init; get; }
protected readonly bool? _PropertiesChangedForMetadata; public string PredictorModelName { init; get; }
protected readonly bool? _PropertiesChangedForResize; public bool PropertiesChangedForDistance { init; get; }
protected Property.Models.Configuration? _PropertyConfiguration; public bool PropertiesChangedForFaces { init; get; }
protected readonly bool? _Reverse; public bool PropertiesChangedForIndex { init; get; }
protected readonly string[] _SaveFaceLandmarkForOutputResolutions; public bool PropertiesChangedForMetadata { init; get; }
protected readonly bool? _SaveFullYearOfRandomFiles; public bool PropertiesChangedForResize { init; get; }
protected readonly bool? _SaveResizedSubfiles; public bool Reverse { init; get; }
protected readonly string[] _SaveShortcutsForOutputResolutions; public string[] SaveFaceLandmarkForOutputResolutions { init; get; }
protected readonly bool? _SkipSearch; public bool SaveFullYearOfRandomFiles { init; get; }
protected readonly bool? _TestDistanceResults; public bool SaveResizedSubfiles { init; get; }
protected readonly string[] _ValidResolutions; public string[] SaveShortcutsForOutputResolutions { init; get; }
public bool? CheckJsonForDistanceResults => _CheckJsonForDistanceResults; public bool SkipSearch { init; get; }
public int? CrossDirectoryMaxItemsInDistanceCollection => _CrossDirectoryMaxItemsInDistanceCollection; public bool TestDistanceResults { init; get; }
public int? DistanceFactor => _DistanceFactor; public string[] ValidResolutions { init; get; }
public bool? ForceMetadataLastWriteTimeToCreationTime => _ForceMetadataLastWriteTimeToCreationTime;
public bool? ForceResizeLastWriteTimeToCreationTime => _ForceResizeLastWriteTimeToCreationTime;
public string[] IgnoreExtensions => _IgnoreExtensions;
public string[] IgnoreRelativePaths => _IgnoreRelativePaths;
public string[] JuliePhares => _JuliePhares;
public string[] LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions => _LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions;
public string[] LoadOrCreateThenSaveDistanceResultsForOutputResolutions => _LoadOrCreateThenSaveDistanceResultsForOutputResolutions;
public string[] LoadOrCreateThenSaveImageFacesResultsForOutputResolutions => _LoadOrCreateThenSaveImageFacesResultsForOutputResolutions;
public bool? LoadOrCreateThenSaveIndex => _LoadOrCreateThenSaveIndex;
public int? LocationConfidenceFactor => _LocationConfidenceFactor;
public int? MappedMaxIndex => _MappedMaxIndex;
public int? MaxItemsInDistanceCollection => _MaxItemsInDistanceCollection;
public string[] MixedYearRelativePaths => _MixedYearRelativePaths;
public string ModelDirectory => _ModelDirectory;
public string ModelName => _ModelName;
public int? NumberOfJitters => _NumberOfJitters;
public int? NumberOfTimesToUpsample => _NumberOfTimesToUpsample;
public string OutputExtension => _OutputExtension;
public int? OutputQuality => _OutputQuality;
public string[] OutputResolutions => _OutputResolutions;
public bool? OverrideForFaceImages => _OverrideForFaceImages;
public bool? OverrideForFaceLandmarkImages => _OverrideForFaceLandmarkImages;
public bool? OverrideForResizeImages => _OverrideForResizeImages;
public int? PaddingLoops => _PaddingLoops;
public string PredictorModelName => _PredictorModelName;
public bool? PropertiesChangedForDistance => _PropertiesChangedForDistance;
public bool? PropertiesChangedForFaces => _PropertiesChangedForFaces;
public bool? PropertiesChangedForIndex => _PropertiesChangedForIndex;
public bool? PropertiesChangedForMetadata => _PropertiesChangedForMetadata;
public bool? PropertiesChangedForResize => _PropertiesChangedForResize;
public Property.Models.Configuration? PropertyConfiguration => _PropertyConfiguration;
public bool? Reverse => _Reverse;
public string[] SaveFaceLandmarkForOutputResolutions => _SaveFaceLandmarkForOutputResolutions;
public bool? SaveFullYearOfRandomFiles => _SaveFullYearOfRandomFiles;
public bool? SaveResizedSubfiles => _SaveResizedSubfiles;
public string[] SaveShortcutsForOutputResolutions => _SaveShortcutsForOutputResolutions;
public bool? SkipSearch => _SkipSearch;
public bool? TestDistanceResults => _TestDistanceResults;
public string[] ValidResolutions => _ValidResolutions;
[JsonConstructor] [JsonConstructor]
public Configuration(bool? checkJsonForDistanceResults, int? crossDirectoryMaxItemsInDistanceCollection, int? distanceFactor, bool? forceMetadataLastWriteTimeToCreationTime, bool? forceResizeLastWriteTimeToCreationTime, string[] ignoreExtensions, string[] ignoreRelativePaths, string[] juliePhares, string[] loadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions, string[] loadOrCreateThenSaveDistanceResultsForOutputResolutions, string[] loadOrCreateThenSaveImageFacesResultsForOutputResolutions, bool? loadOrCreateThenSaveIndex, int? locationConfidenceFactor, int? mappedMaxIndex, int? maxItemsInDistanceCollection, string[] mixedYearRelativePaths, string modelDirectory, string modelName, int? numberOfJitters, int? numberOfTimesToUpsample, string outputExtension, int? outputQuality, string[] outputResolutions, bool? overrideForFaceImages, bool? overrideForFaceLandmarkImages, bool? overrideForResizeImages, int? paddingLoops, string predictorModelName, bool? propertiesChangedForDistance, bool? propertiesChangedForFaces, bool? propertiesChangedForIndex, bool? propertiesChangedForMetadata, bool? propertiesChangedForResize, Property.Models.Configuration? propertyConfiguration, bool? reverse, string[] saveFaceLandmarkForOutputResolutions, bool? saveFullYearOfRandomFiles, bool? saveResizedSubfiles, string[] saveShortcutsForOutputResolutions, bool? skipSearch, bool? testDistanceResults, string[] validResolutions) public Configuration(Property.Models.Configuration propertyConfiguration, bool checkJsonForDistanceResults, int crossDirectoryMaxItemsInDistanceCollection, int distanceFactor, bool forceFaceLastWriteTimeToCreationTime, bool forceMetadataLastWriteTimeToCreationTime, bool forceResizeLastWriteTimeToCreationTime, string[] ignoreExtensions, string[] ignoreRelativePaths, string[] juliePhares, string[] loadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions, string[] loadOrCreateThenSaveDistanceResultsForOutputResolutions, string[] loadOrCreateThenSaveImageFacesResultsForOutputResolutions, bool loadOrCreateThenSaveIndex, int locationConfidenceFactor, int? mappedMaxIndex, int maxItemsInDistanceCollection, string[] mixedYearRelativePaths, string modelDirectory, string modelName, int numberOfJitters, int numberOfTimesToUpsample, string outputExtension, int outputQuality, string[] outputResolutions, bool overrideForFaceImages, bool overrideForFaceLandmarkImages, bool overrideForResizeImages, int paddingLoops, string predictorModelName, bool propertiesChangedForDistance, bool propertiesChangedForFaces, bool propertiesChangedForIndex, bool propertiesChangedForMetadata, bool propertiesChangedForResize, bool reverse, string[] saveFaceLandmarkForOutputResolutions, bool saveFullYearOfRandomFiles, bool saveResizedSubfiles, string[] saveShortcutsForOutputResolutions, bool skipSearch, bool testDistanceResults, string[] validResolutions)
{ {
_CheckJsonForDistanceResults = checkJsonForDistanceResults;
_CrossDirectoryMaxItemsInDistanceCollection = crossDirectoryMaxItemsInDistanceCollection;
_DistanceFactor = distanceFactor;
_ForceMetadataLastWriteTimeToCreationTime = forceMetadataLastWriteTimeToCreationTime;
_ForceResizeLastWriteTimeToCreationTime = forceResizeLastWriteTimeToCreationTime;
_IgnoreExtensions = ignoreExtensions;
_IgnoreRelativePaths = ignoreRelativePaths;
_JuliePhares = juliePhares;
_LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions = loadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions;
_LoadOrCreateThenSaveDistanceResultsForOutputResolutions = loadOrCreateThenSaveDistanceResultsForOutputResolutions;
_LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = loadOrCreateThenSaveImageFacesResultsForOutputResolutions;
_LoadOrCreateThenSaveIndex = loadOrCreateThenSaveIndex;
_LocationConfidenceFactor = locationConfidenceFactor;
_MappedMaxIndex = mappedMaxIndex;
_MaxItemsInDistanceCollection = maxItemsInDistanceCollection;
_MixedYearRelativePaths = mixedYearRelativePaths;
_ModelDirectory = modelDirectory;
_ModelName = modelName;
_NumberOfJitters = numberOfJitters;
_NumberOfTimesToUpsample = numberOfTimesToUpsample;
_OutputExtension = outputExtension;
_OutputQuality = outputQuality;
_OutputResolutions = outputResolutions;
_OverrideForFaceImages = overrideForFaceImages;
_OverrideForFaceLandmarkImages = overrideForFaceLandmarkImages;
_OverrideForResizeImages = overrideForResizeImages;
_PaddingLoops = paddingLoops;
_PredictorModelName = predictorModelName;
_PropertiesChangedForDistance = propertiesChangedForDistance;
_PropertiesChangedForFaces = propertiesChangedForFaces;
_PropertiesChangedForIndex = propertiesChangedForIndex;
_PropertiesChangedForMetadata = propertiesChangedForMetadata;
_PropertiesChangedForResize = propertiesChangedForResize;
_PropertyConfiguration = propertyConfiguration; _PropertyConfiguration = propertyConfiguration;
_Reverse = reverse; CheckJsonForDistanceResults = checkJsonForDistanceResults;
_SaveFaceLandmarkForOutputResolutions = saveFaceLandmarkForOutputResolutions; CrossDirectoryMaxItemsInDistanceCollection = crossDirectoryMaxItemsInDistanceCollection;
_SaveFullYearOfRandomFiles = saveFullYearOfRandomFiles; DistanceFactor = distanceFactor;
_SaveResizedSubfiles = saveResizedSubfiles; ForceFaceLastWriteTimeToCreationTime = forceFaceLastWriteTimeToCreationTime;
_SaveShortcutsForOutputResolutions = saveShortcutsForOutputResolutions; ForceMetadataLastWriteTimeToCreationTime = forceMetadataLastWriteTimeToCreationTime;
_SkipSearch = skipSearch; ForceResizeLastWriteTimeToCreationTime = forceResizeLastWriteTimeToCreationTime;
_TestDistanceResults = testDistanceResults; IgnoreExtensions = ignoreExtensions;
_ValidResolutions = validResolutions; IgnoreRelativePaths = ignoreRelativePaths;
JuliePhares = juliePhares;
LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions = loadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions;
LoadOrCreateThenSaveDistanceResultsForOutputResolutions = loadOrCreateThenSaveDistanceResultsForOutputResolutions;
LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = loadOrCreateThenSaveImageFacesResultsForOutputResolutions;
LoadOrCreateThenSaveIndex = loadOrCreateThenSaveIndex;
LocationConfidenceFactor = locationConfidenceFactor;
MappedMaxIndex = mappedMaxIndex;
MaxItemsInDistanceCollection = maxItemsInDistanceCollection;
MixedYearRelativePaths = mixedYearRelativePaths;
ModelDirectory = modelDirectory;
ModelName = modelName;
NumberOfJitters = numberOfJitters;
NumberOfTimesToUpsample = numberOfTimesToUpsample;
OutputExtension = outputExtension;
OutputQuality = outputQuality;
OutputResolutions = outputResolutions;
OverrideForFaceImages = overrideForFaceImages;
OverrideForFaceLandmarkImages = overrideForFaceLandmarkImages;
OverrideForResizeImages = overrideForResizeImages;
PaddingLoops = paddingLoops;
PredictorModelName = predictorModelName;
PropertiesChangedForDistance = propertiesChangedForDistance;
PropertiesChangedForFaces = propertiesChangedForFaces;
PropertiesChangedForIndex = propertiesChangedForIndex;
PropertiesChangedForMetadata = propertiesChangedForMetadata;
PropertiesChangedForResize = propertiesChangedForResize;
Reverse = reverse;
SaveFaceLandmarkForOutputResolutions = saveFaceLandmarkForOutputResolutions;
SaveFullYearOfRandomFiles = saveFullYearOfRandomFiles;
SaveResizedSubfiles = saveResizedSubfiles;
SaveShortcutsForOutputResolutions = saveShortcutsForOutputResolutions;
SkipSearch = skipSearch;
TestDistanceResults = testDistanceResults;
ValidResolutions = validResolutions;
} }
public override string ToString() public override string ToString()
@ -146,6 +108,6 @@ public class Configuration
public void Set(Property.Models.Configuration configuration) => _PropertyConfiguration = configuration; public void Set(Property.Models.Configuration configuration) => _PropertyConfiguration = configuration;
public void Update() => _PropertyConfiguration?.Update(); public void Update() => _PropertyConfiguration.Update();
} }

View File

@ -0,0 +1,48 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using View_by_Distance.FaceRecognitionDotNet;
using View_by_Distance.Property.Models;
using View_by_Distance.Shared.Models.Properties;
namespace View_by_Distance.Instance.Models;
internal class DistanceHolder
{
public IFace Face { init; get; }
public FaceEncoding? FaceEncoding { init; get; }
public FileHolder FileHolder { init; get; }
public int Id { init; get; }
public string JSONDirectory { init; get; }
public ILocation Location { init; get; }
public string TSVDirectory { init; get; }
public double Sort { get; set; }
[JsonConstructor]
public DistanceHolder(
IFace face,
FaceEncoding? faceEncoding,
FileHolder fileHolder,
int id,
string jsonDirectory,
ILocation location,
string tsvDirectory
)
{
FileHolder = fileHolder;
Sort = double.MaxValue;
Face = face;
FaceEncoding = faceEncoding;
Id = id;
JSONDirectory = jsonDirectory;
Location = location;
TSVDirectory = tsvDirectory;
}
public override string ToString()
{
string result = JsonSerializer.Serialize(this, new JsonSerializerOptions() { WriteIndented = true });
return result;
}
}

View File

@ -1,40 +0,0 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.Instance.Models.Stateless;
public abstract class AppSettings
{
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings? result;
Binder.AppSettings appSettings = configurationRoot.Get<Binder.AppSettings>();
string json = JsonSerializer.Serialize(appSettings, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.AppSettings>(json);
if (result is null)
throw new Exception(json);
if (string.IsNullOrEmpty(result.Company))
throw new Exception(json);
string jsonThis = result.ToString();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -1,44 +0,0 @@
using Microsoft.Extensions.Configuration;
using Phares.Shared;
using System.Text.Json;
namespace View_by_Distance.Instance.Models.Stateless;
public abstract class Configuration
{
public static Models.Configuration Get(IsEnvironment isEnvironment, IConfigurationRoot configurationRoot, string workingDirectory, Property.Models.Configuration propertyConfiguration)
{
Models.Configuration? result;
string environmentName = IsEnvironment.GetEnvironmentName(isEnvironment);
string section = string.Concat(environmentName, ":", nameof(Binder.Configuration));
IConfigurationSection configurationSection = configurationRoot.GetSection(section);
Binder.Configuration configuration = configurationSection.Get<Binder.Configuration>();
string json = JsonSerializer.Serialize(configuration, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.Configuration>(json);
if (result is null)
throw new Exception(json);
string jsonThis = result.ToString();
result.Set(propertyConfiguration);
result.Update();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -157,9 +157,7 @@ internal class D2_FaceLandmarks
imageFiles.Add(new string[] { fileInfo.FullName, rotatedFileInfo.FullName }); imageFiles.Add(new string[] { fileInfo.FullName, rotatedFileInfo.FullName });
if (check) if (check)
continue; continue;
if (_Configuration.OverrideForFaceLandmarkImages is null) else if (_Configuration.OverrideForFaceLandmarkImages)
check = false;
else if (_Configuration.OverrideForFaceLandmarkImages.Value)
check = true; check = true;
else if (!fileInfo.Exists) else if (!fileInfo.Exists)
check = true; check = true;

View File

@ -254,14 +254,8 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
private List<D_Face> GetFaces(FileHolder resizedFileHolder, Item item, A_Property property, int outputResolutionWidth, int outputResolutionHeight, int outputResolutionOrientation, string facesDirectory) private List<D_Face> GetFaces(FileHolder resizedFileHolder, Item item, A_Property property, int outputResolutionWidth, int outputResolutionHeight, int outputResolutionOrientation, string facesDirectory)
{ {
List<D_Face> results = new(); List<D_Face> results = new();
if (_Configuration.PaddingLoops is null)
throw new NullReferenceException(nameof(_Configuration.PaddingLoops));
if (item.ImageFileHolder is null) if (item.ImageFileHolder is null)
throw new NullReferenceException(nameof(item.ImageFileHolder)); throw new NullReferenceException(nameof(item.ImageFileHolder));
if (_Configuration.NumberOfJitters is null)
throw new NullReferenceException(nameof(_Configuration.NumberOfJitters));
if (_Configuration.NumberOfTimesToUpsample is null)
throw new NullReferenceException(nameof(_Configuration.NumberOfTimesToUpsample));
List<Location> locations; List<Location> locations;
FaceRecognitionDotNet.Image? unknownImage = null; FaceRecognitionDotNet.Image? unknownImage = null;
if (resizedFileHolder.Exists) if (resizedFileHolder.Exists)
@ -275,7 +269,7 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
else else
{ {
FaceRecognition faceRecognition = FaceRecognition.Create(_ModelParameter); FaceRecognition faceRecognition = FaceRecognition.Create(_ModelParameter);
locations = faceRecognition.FaceLocations(_Model, unknownImage, _Configuration.NumberOfTimesToUpsample.Value, sortByPixelPercentage: true); locations = faceRecognition.FaceLocations(_Model, unknownImage, _Configuration.NumberOfTimesToUpsample, sortByNormalizedPixelPercentage: true);
if (!locations.Any()) if (!locations.Any())
results.Add(new D_Face(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, item.RelativePath, i: null, location: null)); results.Add(new D_Face(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, item.RelativePath, i: null, location: null));
else else
@ -305,7 +299,7 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
padding = (int)((source.Width + source.Height) / 2 * .01); padding = (int)((source.Width + source.Height) / 2 * .01);
for (int i = 0; i < locations.Count; i++) for (int i = 0; i < locations.Count; i++)
{ {
for (int p = 0; p <= _Configuration.PaddingLoops.Value; p++) for (int p = 0; p <= _Configuration.PaddingLoops; p++)
{ {
location = new(locations[i].Confidence, location = new(locations[i].Confidence,
locations[i].Bottom + (padding * p), locations[i].Bottom + (padding * p),
@ -332,9 +326,9 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
{ {
if (knownImage is null || knownImage.IsDisposed) if (knownImage is null || knownImage.IsDisposed)
throw new NullReferenceException(nameof(knownImage)); throw new NullReferenceException(nameof(knownImage));
facesLandmarks = faceRecognition.GetFaceLandmarkCollection(knownImage, _Configuration.NumberOfTimesToUpsample.Value, faceLocations: null, _PredictorModel, _Model); facesLandmarks = faceRecognition.GetFaceLandmarkCollection(knownImage, _Configuration.NumberOfTimesToUpsample, faceLocations: null, _PredictorModel, _Model);
} }
if (facesLandmarks.Count == 0 && p < _Configuration.PaddingLoops.Value) if (facesLandmarks.Count == 0 && p < _Configuration.PaddingLoops)
continue; continue;
else if (facesLandmarks.Count != 1) else if (facesLandmarks.Count != 1)
continue; continue;
@ -364,9 +358,9 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
{ {
if (rotatedImage is null || rotatedImage.IsDisposed) if (rotatedImage is null || rotatedImage.IsDisposed)
throw new NullReferenceException(nameof(rotatedImage)); throw new NullReferenceException(nameof(rotatedImage));
faceEncodings = faceRecognition.FaceEncodings(rotatedImage, _Configuration.NumberOfTimesToUpsample.Value, knownFaceLocation: null, _Configuration.NumberOfJitters.Value, _PredictorModel, _Model); faceEncodings = faceRecognition.FaceEncodings(rotatedImage, _Configuration.NumberOfTimesToUpsample, knownFaceLocation: null, _Configuration.NumberOfJitters, _PredictorModel, _Model);
} }
if (faceEncodings.Count == 0 && p < _Configuration.PaddingLoops.Value) if (faceEncodings.Count == 0 && p < _Configuration.PaddingLoops)
continue; continue;
else if (faceEncodings.Count != 1) else if (faceEncodings.Count != 1)
continue; continue;
@ -417,15 +411,11 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
List<D_Face>? results; List<D_Face>? results;
if (item.Property?.Id is null) if (item.Property?.Id is null)
throw new NullReferenceException(nameof(item.Property.Id)); throw new NullReferenceException(nameof(item.Property.Id));
if (_Configuration.PropertiesChangedForFaces is null)
throw new NullReferenceException(nameof(_Configuration.PropertiesChangedForFaces));
if (item.ImageFileHolder is null) if (item.ImageFileHolder is null)
throw new NullReferenceException(nameof(item.ImageFileHolder)); throw new NullReferenceException(nameof(item.ImageFileHolder));
if (string.IsNullOrEmpty(dResultsFullGroupDirectory)) if (string.IsNullOrEmpty(dResultsFullGroupDirectory))
throw new NullReferenceException(nameof(dResultsFullGroupDirectory)); throw new NullReferenceException(nameof(dResultsFullGroupDirectory));
string json; string json;
D_Face face;
bool checkForOutputResolutionChange = false;
string[] changesFrom = new string[] { nameof(A_Property), nameof(B_Metadata), nameof(C_Resize) }; string[] changesFrom = new string[] { nameof(A_Property), nameof(B_Metadata), nameof(C_Resize) };
List<DateTime> dateTimes = (from l in subFileTuples where changesFrom.Contains(l.Item1) select l.Item2).ToList(); List<DateTime> dateTimes = (from l in subFileTuples where changesFrom.Contains(l.Item1) select l.Item2).ToList();
string facesDirectory = Path.Combine(AngleBracketCollection[0].Replace("<>", "()"), item.ImageFileHolder.NameWithoutExtension); string facesDirectory = Path.Combine(AngleBracketCollection[0].Replace("<>", "()"), item.ImageFileHolder.NameWithoutExtension);
@ -453,7 +443,17 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
} }
if (!Directory.Exists(facesDirectory)) if (!Directory.Exists(facesDirectory))
_ = Directory.CreateDirectory(facesDirectory); _ = Directory.CreateDirectory(facesDirectory);
if (_Configuration.PropertiesChangedForFaces.Value) if (_Configuration.ForceFaceLastWriteTimeToCreationTime && !fileInfo.Exists && File.Exists(Path.ChangeExtension(fileInfo.FullName, ".delete")))
{
File.Move(Path.ChangeExtension(fileInfo.FullName, ".delete"), fileInfo.FullName);
fileInfo.Refresh();
}
if (_Configuration.ForceFaceLastWriteTimeToCreationTime && fileInfo.Exists && fileInfo.LastWriteTime != fileInfo.CreationTime)
{
File.SetLastWriteTime(fileInfo.FullName, fileInfo.CreationTime);
fileInfo.Refresh();
}
if (_Configuration.PropertiesChangedForFaces)
results = null; results = null;
else if (!fileInfo.Exists) else if (!fileInfo.Exists)
results = null; results = null;
@ -467,15 +467,6 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
results = JsonSerializer.Deserialize<List<D_Face>>(json); results = JsonSerializer.Deserialize<List<D_Face>>(json);
if (results is null) if (results is null)
throw new NullReferenceException(nameof(results)); throw new NullReferenceException(nameof(results));
for (int i = 0; i < results.Count; i++)
{
face = results[i];
if (face.OutputResolution is not null)
continue;
if (!checkForOutputResolutionChange)
checkForOutputResolutionChange = true;
results[i] = new(outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, face);
}
subFileTuples.Add(new Tuple<string, DateTime>(nameof(D_Face), fileInfo.LastWriteTime)); subFileTuples.Add(new Tuple<string, DateTime>(nameof(D_Face), fileInfo.LastWriteTime));
} }
catch (Exception) catch (Exception)
@ -484,15 +475,7 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
parseExceptions.Add(nameof(D_Face)); parseExceptions.Add(nameof(D_Face));
} }
} }
if (results is not null && checkForOutputResolutionChange) if (results is null)
{
json = JsonSerializer.Serialize(results, _WriteIndentedJsonSerializerOptions);
bool updateDateWhenMatches = dateTimes.Any() && fileInfo.Exists && dateTimes.Max() > fileInfo.LastWriteTime;
DateTime? dateTime = !updateDateWhenMatches ? null : dateTimes.Max();
if (Property.Models.Stateless.IPath.WriteAllText(fileInfo.FullName, json, updateDateWhenMatches, compareBeforeWrite: true, updateToWhenMatches: dateTime))
File.SetLastWriteTime(fileInfo.FullName, fileInfo.CreationTime);
}
else if (results is null)
{ {
results = GetFaces(resizedFileHolder, item, property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, facesDirectory); results = GetFaces(resizedFileHolder, item, property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, facesDirectory);
json = JsonSerializer.Serialize(results, _WriteIndentedJsonSerializerOptions); json = JsonSerializer.Serialize(results, _WriteIndentedJsonSerializerOptions);
@ -501,13 +484,23 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
if (Property.Models.Stateless.IPath.WriteAllText(fileInfo.FullName, json, updateDateWhenMatches, compareBeforeWrite: true, updateToWhenMatches: dateTime)) if (Property.Models.Stateless.IPath.WriteAllText(fileInfo.FullName, json, updateDateWhenMatches, compareBeforeWrite: true, updateToWhenMatches: dateTime))
subFileTuples.Add(new Tuple<string, DateTime>(nameof(D_Face), DateTime.Now)); subFileTuples.Add(new Tuple<string, DateTime>(nameof(D_Face), DateTime.Now));
} }
if (_Configuration.ForceFaceLastWriteTimeToCreationTime)
{
json = JsonSerializer.Serialize(results, _WriteIndentedJsonSerializerOptions);
bool updateDateWhenMatches = dateTimes.Any() && fileInfo.Exists && dateTimes.Max() > fileInfo.LastWriteTime;
DateTime? dateTime = !updateDateWhenMatches ? null : dateTimes.Max();
if (Property.Models.Stateless.IPath.WriteAllText(fileInfo.FullName, json, updateDateWhenMatches, compareBeforeWrite: true, updateToWhenMatches: dateTime))
{
File.SetLastWriteTime(fileInfo.FullName, fileInfo.CreationTime);
fileInfo.Refresh();
subFileTuples.Add(new Tuple<string, DateTime>(nameof(D_Face), fileInfo.CreationTime));
}
}
return results; return results;
} }
internal void SaveFaces(string dResultsFullGroupDirectory, List<Tuple<string, DateTime>> subFileTuples, List<string> parseExceptions, Item item, List<D_Face> faceCollection) internal void SaveFaces(string dResultsFullGroupDirectory, List<Tuple<string, DateTime>> subFileTuples, List<string> parseExceptions, Item item, List<D_Face> faceCollection)
{ {
if (_Configuration.OverrideForFaceImages is null)
throw new NullReferenceException(nameof(_Configuration.OverrideForFaceImages));
if (item.ImageFileHolder is null) if (item.ImageFileHolder is null)
throw new NullReferenceException(nameof(item.ImageFileHolder)); throw new NullReferenceException(nameof(item.ImageFileHolder));
if (item.ResizedFileHolder is null) if (item.ResizedFileHolder is null)
@ -539,7 +532,7 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
File.Delete(parentCheck); File.Delete(parentCheck);
} }
imageFiles.Add(fileInfo.FullName); imageFiles.Add(fileInfo.FullName);
if (_Configuration.OverrideForFaceImages.Value) if (_Configuration.OverrideForFaceImages)
check = true; check = true;
else if (!fileInfo.Exists) else if (!fileInfo.Exists)
check = true; check = true;
@ -550,7 +543,7 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
SaveFaces(faceCollection, item.ResizedFileHolder, imageFiles); SaveFaces(faceCollection, item.ResizedFileHolder, imageFiles);
} }
internal static void SaveShortcuts(string[] juliePhares, string dResultsFullGroupDirectory, long ticks, Dictionary<string, List<Person>> peopleCollection, PropertyLogic propertyLogic, Item[] filteredItems) internal static void SaveShortcuts(string[] juliePhares, string dResultsFullGroupDirectory, long ticks, Dictionary<string, List<Person>> peopleCollection, PropertyLogic propertyLogic, List<Item> items)
{ {
Person person; Person person;
string fileName; string fileName;
@ -559,7 +552,7 @@ public class D_Face : Shared.Models.Properties.IFace, IFace
WindowsShortcut windowsShortcut; WindowsShortcut windowsShortcut;
const string pattern = @"[\\,\/,\:,\*,\?,\"",\<,\>,\|]"; const string pattern = @"[\\,\/,\:,\*,\?,\"",\<,\>,\|]";
string dFacesContentDirectory = Path.Combine(dResultsFullGroupDirectory, $"({ticks})"); string dFacesContentDirectory = Path.Combine(dResultsFullGroupDirectory, $"({ticks})");
List<(Item, (string, Shared.Models.Properties.IFace?, (string, string, string, string))[])> collections = Item.GetCollection(propertyLogic, filteredItems, dFacesContentDirectory); List<(Item, (string, Shared.Models.Properties.IFace?, (string, string, string, string))[])> collections = Item.GetCollection(propertyLogic, items, dFacesContentDirectory);
foreach ((Item item, (string personKey, Shared.Models.Properties.IFace? _, (string, string, string, string))[] collection) in collections) foreach ((Item item, (string personKey, Shared.Models.Properties.IFace? _, (string, string, string, string))[] collection) in collections)
{ {
if (collection.Length != 1) if (collection.Length != 1)

View File

@ -1,19 +1,15 @@
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using View_by_Distance.FaceRecognitionDotNet; using View_by_Distance.FaceRecognitionDotNet;
using View_by_Distance.Metadata.Models; using View_by_Distance.Metadata.Models;
using View_by_Distance.Property.Models; using View_by_Distance.Property.Models;
using View_by_Distance.Resize.Models; using View_by_Distance.Resize.Models;
using View_by_Distance.Shared.Models.Properties;
using View_by_Distance.Shared.Models.Stateless; using View_by_Distance.Shared.Models.Stateless;
using WindowsShortcutFactory; using WindowsShortcutFactory;
namespace View_by_Distance.Instance.Models; namespace View_by_Distance.Instance.Models;
/// <summary>
// List<D_Faces>
/// </summary>
internal class E_Distance internal class E_Distance
{ {
@ -34,183 +30,177 @@ internal class E_Distance
return result; return result;
} }
private static void LoadFaceEncodingCollections(Item[] filteredItems, List<List<D_Face>> faceCollections, List<int[]> locationIndicesCollection, List<FaceEncoding> faceEncodingCollection, List<List<FaceEncoding>> faceEncodingCollections) private static List<DistanceHolder> GetDistanceHolder(Item[] items, List<(string JSONDirectory, string TSVDirectory)> directories)
{ {
List<D_Face> faceCollection; List<DistanceHolder> results = new();
FaceEncoding faceEncoding; Item item;
for (int i = 0; i < filteredItems.Length; i++) const int zero = 0;
{ string tsvDirectory;
faceCollection = faceCollections[i]; string jsonDirectory;
if (!faceCollection.Any()) FaceEncoding? faceEncoding;
if (items.Length != directories.Count)
throw new Exception(); throw new Exception();
faceEncodingCollections.Add(new List<FaceEncoding>()); for (int i = 0; i < items.Length; i++)
for (int j = 0; j < faceCollection.Count; j++)
{ {
if (!faceCollection[j].Populated) faceEncoding = null;
item = items[i];
if (item.ImageFileHolder is null || item.Property?.Id is null || !item.Faces.Any())
continue; continue;
faceEncoding = FaceRecognition.LoadFaceEncoding(faceCollection[j].FaceEncoding.RawEncoding); tsvDirectory = directories[i].TSVDirectory;
faceEncodingCollection.Add(faceEncoding); jsonDirectory = directories[i].JSONDirectory;
faceEncodingCollections[i].Add(faceEncoding); foreach (IFace face in item.Faces)
locationIndicesCollection.Add(new int[] { i, j }); {
if (!face.Populated)
continue;
faceEncoding = FaceRecognition.LoadFaceEncoding(face.FaceEncoding.RawEncoding);
results.Add(new(face, faceEncoding, item.ImageFileHolder, item.Property.Id.Value, jsonDirectory, item.Faces[zero].Location, tsvDirectory));
} }
if (faceEncoding is null)
results.Add(new(item.Faces[zero], null, item.ImageFileHolder, item.Property.Id.Value, jsonDirectory, item.Faces[zero].Location, tsvDirectory));
} }
return results;
} }
private List<Tuple<Shared.Models.Properties.IFace, string>> GetOrderedNoFaceCollection(List<List<D_Face>> faceCollections, int i, D_Face face) private List<Tuple<IFace, string>> GetOrderedNoFaceCollection(List<List<IFace>> faceCollections, int i, IFace face)
{ {
List<Tuple<Shared.Models.Properties.IFace, string>> results = new() { new(face, string.Empty) }; List<Tuple<IFace, string>> results = new() { new(face, string.Empty) };
if (_Configuration.MaxItemsInDistanceCollection is null)
throw new NullReferenceException(nameof(_Configuration.MaxItemsInDistanceCollection));
for (int n = 0; n < faceCollections.Count; n++) for (int n = 0; n < faceCollections.Count; n++)
{ {
if (i == n) if (i == n)
continue; continue;
for (int j = 0; j < faceCollections[n].Count; j++) for (int j = 0; j < faceCollections[n].Count; j++)
{
if (!faceCollections[n][j].Populated)
continue;
results.Add(new(faceCollections[n][j], string.Empty)); results.Add(new(faceCollections[n][j], string.Empty));
} }
for (int r = results.Count - 1; r > _Configuration.MaxItemsInDistanceCollection.Value; r--) }
for (int r = results.Count - 1; r > _Configuration.MaxItemsInDistanceCollection; r--)
results.RemoveAt(r); results.RemoveAt(r);
return results; return results;
} }
private List<double[]> GetValues(List<List<D_Face>> faceCollections, List<int[]> locationIndicesCollection, List<double> faceDistances) private void WriteNoFaceCollection(bool updateDateWhenMatches, DateTime? updateToWhenMatches, List<Tuple<string, DateTime>> subFileTuples, List<DistanceHolder> distanceHolders)
{ {
List<double[]> results = new();
if (_Configuration.LocationConfidenceFactor is null)
throw new NullReferenceException(nameof(_Configuration.LocationConfidenceFactor));
if (_Configuration.DistanceFactor is null)
throw new NullReferenceException(nameof(_Configuration.DistanceFactor));
D_Face face;
int[] locationIndices;
for (int d = 0; d < faceDistances.Count; d++)
{
locationIndices = locationIndicesCollection[d];
face = faceCollections[locationIndices[0]][locationIndices[1]];
if (face.Populated && face.LocationIndex is not null && locationIndices[1] != face.LocationIndex)
throw new Exception();
results.Add(new double[] { d, faceDistances[d], (faceDistances[d] * _Configuration.DistanceFactor.Value) + face.Location.Confidence * _Configuration.LocationConfidenceFactor.Value / 10 });
}
results = (from l in results orderby l[2] select l).ToList();
return results;
}
private List<Tuple<Shared.Models.Properties.IFace, string>> GetOrderedFaceCollection(List<List<D_Face>> faceCollections, List<int[]> locationIndicesCollection, List<double[]> indicesAndValues)
{
List<Tuple<Shared.Models.Properties.IFace, string>> results = new();
if (_Configuration.MaxItemsInDistanceCollection is null)
throw new NullReferenceException(nameof(_Configuration.MaxItemsInDistanceCollection));
int[] locationIndices;
for (int t = 0; t < indicesAndValues.Count; t++)
{
locationIndices = locationIndicesCollection[(int)indicesAndValues[t][0]];
results.Add(new(faceCollections[locationIndices[0]][locationIndices[1]], string.Join('|', (from l in indicesAndValues[t] select l.ToString("0.000")).ToArray(), 1, indicesAndValues[t].Length - 1)));
}
for (int r = results.Count - 1; r > _Configuration.MaxItemsInDistanceCollection.Value; r--)
results.RemoveAt(r);
return results;
}
private static string GetText(string fileNameWithoutExtension, List<List<D_Face>> faceCollections, List<int[]> locationIndicesCollection, List<double[]> indicesAndValues)
{
string result;
D_Face face;
int[] locationIndices;
StringBuilder tvs = new();
_ = tvs.Append("FileNameWithoutExtension").Append('\t').Append("LocationIndex").Append('\t').Append("FaceConfidence").Append('\t').Append("FaceDistance").Append('\t').Append("FactoredValue").AppendLine();
for (int t = 0; t < indicesAndValues.Count; t++)
{
locationIndices = locationIndicesCollection[(int)indicesAndValues[t][0]];
face = faceCollections[locationIndices[0]][locationIndices[1]];
if (face.Populated && face.LocationIndex is not null && locationIndices[1] != face.LocationIndex)
throw new Exception();
_ = tvs.Append(fileNameWithoutExtension).Append('\t').Append(face.LocationIndex).Append('\t').Append(face.Location.Confidence).Append('\t').Append(indicesAndValues[t][1]).Append('\t').Append(indicesAndValues[t][2]).AppendLine();
}
result = tvs.ToString();
return result;
}
private void LoadOrCreateThenSaveDistanceResultsForOutputResolutionsLoop(List<List<D_Face>> faceCollections, int subFilesCount, int i, List<D_Face> faceCollection, List<int[]> locationIndicesCollection, List<Tuple<string, DateTime>> subFileTuples, List<FaceEncoding> faceEncodingCollection, List<FaceEncoding> faceEncodingCollections, string fileNameWithoutExtension, string jsonDirectory, string tvsDirectory, bool updateDateWhenMatches, DateTime? updateToWhenMatches)
{
string text;
string json; string json;
string check;
string jsonFile; string jsonFile;
List<Tuple<Shared.Models.Properties.IFace, string>> orderedFaceCollection; const int zero = 0;
if (!Directory.Exists(jsonDirectory)) DistanceHolder distanceHolder;
_ = Directory.CreateDirectory(jsonDirectory); List<Tuple<IFace, string>> tupleCollection;
if (!Directory.Exists(tvsDirectory)) for (int i = 0; i < distanceHolders.Count; i++)
_ = Directory.CreateDirectory(tvsDirectory);
if (!faceEncodingCollections.Any())
{ {
int j = 0; distanceHolder = distanceHolders[i];
orderedFaceCollection = GetOrderedNoFaceCollection(faceCollections, i, faceCollection[j]); if (distanceHolder.Face.Location.NormalizedPixelPercentage is null)
json = JsonSerializer.Serialize(orderedFaceCollection, _WriteIndentedJsonSerializerOptions); continue;
jsonFile = Path.Combine(jsonDirectory, $"{j} - {fileNameWithoutExtension}.json"); check = Path.Combine(distanceHolder.JSONDirectory, $"{zero} - {distanceHolder.FileHolder.NameWithoutExtension}.json");
jsonFile = Path.Combine(distanceHolder.JSONDirectory, $"{distanceHolder.Id}.{zero}{distanceHolder.FileHolder.ExtensionLowered}.json");
if (File.Exists(check))
File.Move(check, jsonFile);
tupleCollection = new() { new(distanceHolders[i].Face, string.Empty) };
for (int j = 0; j < distanceHolders.Count; j++)
{
if (j == i)
continue;
distanceHolder = distanceHolders[j];
tupleCollection.Add(new(distanceHolder.Face, string.Empty));
if (tupleCollection.Count > _Configuration.MaxItemsInDistanceCollection)
break;
}
json = JsonSerializer.Serialize(tupleCollection, _WriteIndentedJsonSerializerOptions);
if (Property.Models.Stateless.IPath.WriteAllText(jsonFile, json, updateDateWhenMatches, compareBeforeWrite: true, updateToWhenMatches: updateToWhenMatches)) if (Property.Models.Stateless.IPath.WriteAllText(jsonFile, json, updateDateWhenMatches, compareBeforeWrite: true, updateToWhenMatches: updateToWhenMatches))
subFileTuples.Add(new Tuple<string, DateTime>(nameof(E_Distance), DateTime.Now)); subFileTuples.Add(new Tuple<string, DateTime>(nameof(E_Distance), DateTime.Now));
} }
else }
private static List<FaceEncoding> GetFaceEncodings(List<DistanceHolder> distanceHolders)
{ {
string tvsFile; List<FaceEncoding> results = new();
foreach (DistanceHolder distanceHolder in distanceHolders)
{
if (!distanceHolder.Face.Populated || distanceHolder.FaceEncoding is null)
continue;
results.Add(distanceHolder.FaceEncoding);
}
return results;
}
private void SaveDistanceResults(bool updateDateWhenMatches, DateTime? updateToWhenMatches, List<Tuple<string, DateTime>> subFileTuples, List<DistanceHolder> distanceHolders)
{
string json;
string check;
string jsonFile;
int locationIndex;
List<double> faceDistances; List<double> faceDistances;
List<double[]> indicesAndValues; DistanceHolder distanceHolder;
for (int j = 0; j < faceEncodingCollections.Count; j++) int normalizedPixelPercentage;
DistanceHolder[] sortedDistanceHolders;
List<Tuple<IFace, string>> tupleCollection;
List<(int Index, double Distance)> collection;
distanceHolders = distanceHolders.OrderByDescending(l => l.Face.Populated).ToList();
List<FaceEncoding> faceEncodings = GetFaceEncodings(distanceHolders);
for (int i = 0; i < distanceHolders.Count; i++)
{ {
if (!faceCollection[j].Populated) distanceHolder = distanceHolders[i];
continue; collection = new();
tvsFile = Path.Combine(tvsDirectory, $"{j} - {fileNameWithoutExtension}.tvs"); tupleCollection = new();
jsonFile = Path.Combine(jsonDirectory, $"{j} - {fileNameWithoutExtension}.json"); distanceHolder.Sort = 0d;
faceDistances = FaceRecognition.FaceDistances(faceEncodingCollection, faceEncodingCollections[j]); if (distanceHolder.Face.LocationIndex is null)
indicesAndValues = GetValues(faceCollections, locationIndicesCollection, faceDistances); locationIndex = 0;
orderedFaceCollection = GetOrderedFaceCollection(faceCollections, locationIndicesCollection, indicesAndValues); else
text = GetText(fileNameWithoutExtension, faceCollections, locationIndicesCollection, indicesAndValues); locationIndex = distanceHolder.Face.LocationIndex.Value;
if (Property.Models.Stateless.IPath.WriteAllText(tvsFile, text, updateDateWhenMatches, compareBeforeWrite: true)) if (!distanceHolder.Face.Populated || distanceHolder.Face.Location.NormalizedPixelPercentage is null)
subFileTuples.Add(new Tuple<string, DateTime>(nameof(E_Distance), DateTime.Now)); normalizedPixelPercentage = 0;
json = JsonSerializer.Serialize(orderedFaceCollection, _WriteIndentedJsonSerializerOptions); else
if (Property.Models.Stateless.IPath.WriteAllText(jsonFile, json, updateDateWhenMatches, compareBeforeWrite: true)) normalizedPixelPercentage = distanceHolder.Face.Location.NormalizedPixelPercentage.Value;
check = Path.Combine(distanceHolder.JSONDirectory, $"{locationIndex} - {distanceHolder.FileHolder.NameWithoutExtension}.json");
jsonFile = Path.Combine(distanceHolder.JSONDirectory, $"{distanceHolder.Id}.{normalizedPixelPercentage}{distanceHolder.FileHolder.ExtensionLowered}.json");
if (!Directory.Exists(distanceHolder.JSONDirectory))
_ = Directory.CreateDirectory(distanceHolder.JSONDirectory);
if (File.Exists(check))
File.Move(check, jsonFile);
if (faceEncodings.Count == 1)
faceDistances = new() { 0d };
else if (distanceHolder.FaceEncoding is null)
faceDistances = Enumerable.Repeat(9d, faceEncodings.Count).ToList();
else
faceDistances = FaceRecognition.FaceDistances(faceEncodings, distanceHolder.FaceEncoding);
if (distanceHolder.Face.Populated && distanceHolder.FaceEncoding is not null && faceDistances[i] != 0d)
faceDistances[i] = 0d;
for (int d = 0; d < faceDistances.Count; d++)
collection.Add(new(d, faceDistances[d]));
collection = collection.OrderBy(l => l.Distance).ToList();
foreach ((int index, double distance) in collection)
distanceHolders[index].Sort = ((distance * _Configuration.DistanceFactor) + (distanceHolders[index].Location.Confidence * _Configuration.LocationConfidenceFactor)) / 10;
sortedDistanceHolders = distanceHolders.OrderBy(l => l.Sort).ToArray();
for (int j = 0; j < sortedDistanceHolders.Length; j++)
{
distanceHolder = sortedDistanceHolders[j];
tupleCollection.Add(new(distanceHolders[j].Face, string.Empty));
if (tupleCollection.Count > _Configuration.MaxItemsInDistanceCollection)
break;
}
json = JsonSerializer.Serialize(tupleCollection, _WriteIndentedJsonSerializerOptions);
if (Property.Models.Stateless.IPath.WriteAllText(jsonFile, json, updateDateWhenMatches, compareBeforeWrite: true, updateToWhenMatches: updateToWhenMatches))
subFileTuples.Add(new Tuple<string, DateTime>(nameof(E_Distance), DateTime.Now)); subFileTuples.Add(new Tuple<string, DateTime>(nameof(E_Distance), DateTime.Now));
} }
} }
}
private void LoadOrCreateThenSaveDistanceResultsForOutputResolutions(Item[] filteredItems, List<List<D_Face>> faceCollections, List<string[]> directories, bool updateDateWhenMatches, DateTime? updateToWhenMatches) internal void LoadOrCreateThenSaveDistanceResults(Property.Models.Configuration configuration, string eResultsFullGroupDirectory, string sourceDirectory, string outputResolution, List<Tuple<string, DateTime>> sourceDirectoryChanges, Item[] filteredItems)
{ {
FileHolder? fileHolder;
List<int[]> locationIndicesCollection = new();
List<Tuple<string, DateTime>> subFileTuples = new();
List<FaceEncoding> faceEncodingCollection = new();
List<List<FaceEncoding>> faceEncodingCollections = new();
LoadFaceEncodingCollections(filteredItems, faceCollections, locationIndicesCollection, faceEncodingCollection, faceEncodingCollections);
if (faceEncodingCollections.Count != faceCollections.Count)
throw new Exception();
if (locationIndicesCollection.Count != faceEncodingCollection.Count)
throw new Exception();
for (int i = 0; i < filteredItems.Length; i++)
{
fileHolder = filteredItems[i].ImageFileHolder;
if (fileHolder is null)
continue;
LoadOrCreateThenSaveDistanceResultsForOutputResolutionsLoop(faceCollections, filteredItems.Length, i, faceCollections[i], locationIndicesCollection, subFileTuples, faceEncodingCollection, faceEncodingCollections[i], fileHolder.NameWithoutExtension, directories[i][0], directories[i][1], updateDateWhenMatches, updateToWhenMatches);
}
}
internal void LoadOrCreateThenSaveDistanceResultsForOutputResolutions(Property.Models.Configuration configuration, string eResultsFullGroupDirectory, string sourceDirectory, string outputResolution, List<Tuple<string, DateTime>> sourceDirectoryChanges, Item[] filteredItems, List<List<D_Face>> faceCollections)
{
if (_Configuration.CheckJsonForDistanceResults is null)
throw new NullReferenceException(nameof(_Configuration.CheckJsonForDistanceResults));
if (_Configuration.PropertiesChangedForDistance is null)
throw new NullReferenceException(nameof(_Configuration.PropertiesChangedForDistance));
Item item; Item item;
string json; string json;
bool check = false; bool check = false;
string parentCheck; string parentCheck;
bool hasPopulatedFace;
string usingRelativePath; string usingRelativePath;
DateTime? dateTime = null; DateTime? dateTime = null;
string dCollectionDirectory; string dCollectionDirectory;
FileInfo[] fileInfoCollection;
bool updateDateWhenMatches = false; bool updateDateWhenMatches = false;
List<string[]> directories = new();
System.IO.DirectoryInfo directoryInfo; System.IO.DirectoryInfo directoryInfo;
System.IO.DirectoryInfo tvsDirectoryInfo; System.IO.DirectoryInfo tvsDirectoryInfo;
IEnumerator<FileInfo> fileInfoCollection;
List<(string, string)> directories = new();
string[] changesFrom = new string[] { nameof(A_Property), nameof(B_Metadata), nameof(C_Resize), nameof(D_Face) }; string[] changesFrom = new string[] { nameof(A_Property), nameof(B_Metadata), nameof(C_Resize), nameof(D_Face) };
List<DateTime> dateTimes = (from l in sourceDirectoryChanges where changesFrom.Contains(l.Item1) select l.Item2).ToList(); List<DateTime> dateTimes = (from l in sourceDirectoryChanges where changesFrom.Contains(l.Item1) select l.Item2).ToList();
List<string> directoryInfoCollection = Property.Models.Stateless.IResult.GetDirectoryInfoCollection( List<string> directoryInfoCollection = Property.Models.Stateless.IResult.GetDirectoryInfoCollection(
@ -226,6 +216,7 @@ internal class E_Distance
item = filteredItems[i]; item = filteredItems[i];
if (item.ImageFileHolder is null || item.Property?.Id is null) if (item.ImageFileHolder is null || item.Property?.Id is null)
continue; continue;
hasPopulatedFace = (from l in item.Faces where l.Populated select true).Any();
usingRelativePath = Path.Combine(directoryInfoCollection[0].Replace("<>", "[]"), item.ImageFileHolder.NameWithoutExtension); usingRelativePath = Path.Combine(directoryInfoCollection[0].Replace("<>", "[]"), item.ImageFileHolder.NameWithoutExtension);
dCollectionDirectory = Path.Combine(eResultsFullGroupDirectory, "[]", Property.Models.Stateless.IResult.AllInOne, $"{item.Property.Id.Value}{item.ImageFileHolder.ExtensionLowered}"); dCollectionDirectory = Path.Combine(eResultsFullGroupDirectory, "[]", Property.Models.Stateless.IResult.AllInOne, $"{item.Property.Id.Value}{item.ImageFileHolder.ExtensionLowered}");
directoryInfo = new System.IO.DirectoryInfo(dCollectionDirectory); directoryInfo = new System.IO.DirectoryInfo(dCollectionDirectory);
@ -250,24 +241,32 @@ internal class E_Distance
} }
} }
tvsDirectoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfoCollection[0].Replace("<>", "()"), item.ImageFileHolder.NameWithoutExtension)); tvsDirectoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfoCollection[0].Replace("<>", "()"), item.ImageFileHolder.NameWithoutExtension));
directories.Add(new string[] { directoryInfo.FullName, tvsDirectoryInfo.FullName }); directories.Add(new(directoryInfo.FullName, tvsDirectoryInfo.FullName));
if (_Configuration.CheckJsonForDistanceResults.Value && directoryInfo.Exists) if (_Configuration.CheckJsonForDistanceResults && directoryInfo.Exists)
{ {
fileInfoCollection = directoryInfo.GetFiles("*.json", SearchOption.AllDirectories); json = string.Empty;
for (int j = 0; j < fileInfoCollection.Length; j++) fileInfoCollection = directoryInfo.EnumerateFiles("*.json", SearchOption.AllDirectories).GetEnumerator();
for (int j = 0; j < int.MaxValue; j++)
{
if (!fileInfoCollection.MoveNext())
break;
json = Shared.Models.Stateless.Methods.IIndex.GetJson(fileInfoCollection.Current.FullName, fileInfoCollection.Current);
if (!_Configuration.PropertiesChangedForDistance && Shared.Models.Stateless.Methods.IFace.GetFace(fileInfoCollection.Current.FullName) is null)
{ {
json = Shared.Models.Stateless.Methods.IIndex.GetJson(fileInfoCollection[j].FullName, fileInfoCollection[j]);
if (!_Configuration.PropertiesChangedForDistance.Value && Shared.Models.Stateless.Methods.IFace.GetFace(fileInfoCollection[j].FullName) is null)
check = true; check = true;
break;
} }
} }
if (!check && string.IsNullOrEmpty(json))
check = true;
}
if (check) if (check)
continue; continue;
if (_Configuration.PropertiesChangedForDistance.Value) if (_Configuration.PropertiesChangedForDistance)
check = true; check = true;
else if (!directoryInfo.Exists) else if (hasPopulatedFace && !directoryInfo.Exists)
check = true; check = true;
else if (!tvsDirectoryInfo.Exists) else if (hasPopulatedFace && !tvsDirectoryInfo.Exists)
check = true; check = true;
else if (dateTimes.Any() && dateTimes.Max() > directoryInfo.LastWriteTime) else if (dateTimes.Any() && dateTimes.Max() > directoryInfo.LastWriteTime)
check = true; check = true;
@ -278,7 +277,12 @@ internal class E_Distance
} }
} }
if (check) if (check)
LoadOrCreateThenSaveDistanceResultsForOutputResolutions(filteredItems, faceCollections, directories, updateDateWhenMatches, updateToWhenMatches: dateTime); {
DateTime? updateToWhenMatches = dateTime;
List<Tuple<string, DateTime>> subFileTuples = new();
List<DistanceHolder> distanceHolders = GetDistanceHolder(filteredItems, directories);
SaveDistanceResults(updateDateWhenMatches, updateToWhenMatches, subFileTuples, distanceHolders);
}
_ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(directoryInfoCollection[0].Replace("<>", "()")); _ = Property.Models.Stateless.IPath.DeleteEmptyDirectories(directoryInfoCollection[0].Replace("<>", "()"));
} }
@ -377,8 +381,6 @@ internal class E_Distance
int filesCount = files.Count; int filesCount = files.Count;
for (int i = 0; i < filesCount; i++) for (int i = 0; i < filesCount; i++)
{ {
if (_Configuration.CrossDirectoryMaxItemsInDistanceCollection is null)
continue;
_Log.Debug(string.Concat("LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions - ", nameof(outputResolution), ' ', outputResolution, " - ", i, " of ", filesCount)); _Log.Debug(string.Concat("LoadOrCreateThenSaveDirectoryDistanceResultsForOutputResolutions - ", nameof(outputResolution), ' ', outputResolution, " - ", i, " of ", filesCount));
for (int j = 0; j < files[i].Item2.Count; j++) for (int j = 0; j < files[i].Item2.Count; j++)
{ {
@ -405,7 +407,7 @@ internal class E_Distance
}); });
if (faceAndFaceDistanceCollection.Any()) if (faceAndFaceDistanceCollection.Any())
{ {
faceAndFaceDistanceCollection = (from l in faceAndFaceDistanceCollection orderby l.Item2 select l).Take(_Configuration.CrossDirectoryMaxItemsInDistanceCollection.Value).ToList(); faceAndFaceDistanceCollection = (from l in faceAndFaceDistanceCollection orderby l.Item2 select l).Take(_Configuration.CrossDirectoryMaxItemsInDistanceCollection).ToList();
Save(configuration, model, predictorModel, outputResolution, eDistanceCollectionDirectory, k, relativePath, face, faceAndFaceDistanceCollection); Save(configuration, model, predictorModel, outputResolution, eDistanceCollectionDirectory, k, relativePath, face, faceAndFaceDistanceCollection);
} }
} }
@ -423,7 +425,7 @@ internal class E_Distance
return result; return result;
} }
private static FaceEncoding? GetFaceEncoding(Shared.Models.Properties.IFace face) private static FaceEncoding? GetFaceEncoding(IFace face)
{ {
FaceEncoding? result; FaceEncoding? result;
if (!face.Populated) if (!face.Populated)
@ -439,14 +441,14 @@ internal class E_Distance
return new(i, faceDistances.Sum()); return new(i, faceDistances.Sum());
} }
private static List<FaceEncoding> GetFaceEncodings(int maxDegreeOfParallelism, List<(DateTime MinimumDateTime, bool? IsWrongYear, Shared.Models.PersonBirthday PersonBirthday, Shared.Models.Properties.IFace Face)> collection) private static List<FaceEncoding> GetFaceEncodings(int maxDegreeOfParallelism, List<(DateTime MinimumDateTime, bool? IsWrongYear, Shared.Models.PersonBirthday PersonBirthday, IFace Face)> collection)
{ {
List<FaceEncoding> results; List<FaceEncoding> results;
if (maxDegreeOfParallelism == 1) if (maxDegreeOfParallelism == 1)
{ {
results = new(); results = new();
FaceEncoding faceEncoding; FaceEncoding faceEncoding;
foreach ((DateTime _, bool? _, Shared.Models.PersonBirthday _, Shared.Models.Properties.IFace face) in collection) foreach ((DateTime _, bool? _, Shared.Models.PersonBirthday _, IFace face) in collection)
{ {
if (!face.Populated) if (!face.Populated)
continue; continue;
@ -518,12 +520,12 @@ internal class E_Distance
return results; return results;
} }
private static List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> GetThreeSigmaFaceEncodings(int maxDegreeOfParallelism, Dictionary<string, List<(DateTime, bool?, Shared.Models.PersonBirthday, Shared.Models.Properties.IFace)>> keyValuePairs) private static List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> GetThreeSigmaFaceEncodings(int maxDegreeOfParallelism, Dictionary<string, List<(DateTime, bool?, Shared.Models.PersonBirthday, IFace)>> keyValuePairs)
{ {
List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> results = new(); List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> results = new();
const int zero = 0; const int zero = 0;
List<FaceEncoding> faceEncodings; List<FaceEncoding> faceEncodings;
foreach (KeyValuePair<string, List<(DateTime MinimumDateTime, bool? IsWrongYear, Shared.Models.PersonBirthday PersonBirthday, Shared.Models.Properties.IFace _)>> keyValuePair in keyValuePairs) foreach (KeyValuePair<string, List<(DateTime MinimumDateTime, bool? IsWrongYear, Shared.Models.PersonBirthday PersonBirthday, IFace _)>> keyValuePair in keyValuePairs)
{ {
faceEncodings = GetFaceEncodings(maxDegreeOfParallelism, keyValuePair.Value); faceEncodings = GetFaceEncodings(maxDegreeOfParallelism, keyValuePair.Value);
results.Add(new(keyValuePair.Value[zero].MinimumDateTime, keyValuePair.Value[zero].IsWrongYear, keyValuePair.Value[zero].PersonBirthday, faceEncodings.ToArray())); results.Add(new(keyValuePair.Value[zero].MinimumDateTime, keyValuePair.Value[zero].IsWrongYear, keyValuePair.Value[zero].PersonBirthday, faceEncodings.ToArray()));
@ -531,7 +533,7 @@ internal class E_Distance
return results; return results;
} }
private static Closest? GetClosestParallelFor(DateTime minimumDateTime, bool? isWrongYear, Shared.Models.Properties.IFace face, FaceEncoding faceEncoding, (DateTime MinimumDateTime, bool? IsWrongYear, Shared.Models.PersonBirthday PersonBirthday, FaceEncoding[] FaceEncodings) tuple) private static Closest? GetClosestParallelFor(DateTime minimumDateTime, bool? isWrongYear, IFace face, FaceEncoding faceEncoding, (DateTime MinimumDateTime, bool? IsWrongYear, Shared.Models.PersonBirthday PersonBirthday, FaceEncoding[] FaceEncodings) tuple)
{ {
Closest? result; Closest? result;
if (isWrongYear.HasValue && !isWrongYear.Value && minimumDateTime < tuple.PersonBirthday.Value) if (isWrongYear.HasValue && !isWrongYear.Value && minimumDateTime < tuple.PersonBirthday.Value)
@ -546,7 +548,7 @@ internal class E_Distance
return result; return result;
} }
private static Closest[] GetClosestCollection(int maxDegreeOfParallelism, List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> collection, DateTime itemMinimumDateTime, bool? itemIsWrongYear, Shared.Models.Properties.IFace face) private static Closest[] GetClosestCollection(int maxDegreeOfParallelism, List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> collection, DateTime itemMinimumDateTime, bool? itemIsWrongYear, IFace face)
{ {
Closest[] results; Closest[] results;
List<Closest> closestCollection; List<Closest> closestCollection;
@ -585,14 +587,16 @@ internal class E_Distance
return results; return results;
} }
private static void AddClosest(int maxDegreeOfParallelism, string argZero, List<Container> containers, List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> collection) private static void AddClosest(int maxDegreeOfParallelism, string argZero, PropertyLogic propertyLogic, List<Container> containers, List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> collection)
{ {
string key; string key;
IFace face;
Closest closest; Closest closest;
string personKey;
bool? itemIsWrongYear; bool? itemIsWrongYear;
Closest[] closestCollection; Closest[] closestCollection;
DateTime? itemMinimumDateTime; DateTime? itemMinimumDateTime;
Shared.Models.Properties.IFace face; float deterministicHashCodeKey;
Dictionary<string, int> results = new(); Dictionary<string, int> results = new();
foreach (Container container in containers) foreach (Container container in containers)
{ {
@ -618,12 +622,16 @@ internal class E_Distance
item.Closest.Add(closest); item.Closest.Add(closest);
if (!face.Populated) if (!face.Populated)
continue; continue;
deterministicHashCodeKey = Named.GetDeterministicHashCodeKey(item, face);
closestCollection = GetClosestCollection(maxDegreeOfParallelism, collection, itemMinimumDateTime.Value, itemIsWrongYear, face); closestCollection = GetClosestCollection(maxDegreeOfParallelism, collection, itemMinimumDateTime.Value, itemIsWrongYear, face);
for (int j = 0; j < closestCollection.Length; j++) for (int j = 0; j < closestCollection.Length; j++)
{ {
closest = closestCollection[j]; closest = closestCollection[j];
if (closest.PersonBirthday is null) if (closest.PersonBirthday is null)
continue; continue;
personKey = Shared.Models.Stateless.Methods.IPersonBirthday.GetFormatted(closest.PersonBirthday);
if (propertyLogic.IncorrectDeterministicHashCodeKeyValuePairs.ContainsKey(deterministicHashCodeKey) && propertyLogic.IncorrectDeterministicHashCodeKeyValuePairs[deterministicHashCodeKey].Contains(personKey))
continue;
key = Item.GetKey(closest.MinimumDateTime, closest.IsWrongYear, closest.PersonBirthday); key = Item.GetKey(closest.MinimumDateTime, closest.IsWrongYear, closest.PersonBirthday);
if (!results.ContainsKey(key)) if (!results.ContainsKey(key))
results.Add(key, 0); results.Add(key, 0);
@ -638,12 +646,12 @@ internal class E_Distance
} }
} }
internal static List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> ParallelWork(int maxDegreeOfParallelism, string argZero, List<Container> containers) internal static List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> ParallelWork(int maxDegreeOfParallelism, string argZero, PropertyLogic propertyLogic, List<Container> containers)
{ {
List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> results; List<(DateTime, bool?, Shared.Models.PersonBirthday, FaceEncoding[])> results;
Dictionary<string, List<(DateTime, bool?, Shared.Models.PersonBirthday, Shared.Models.Properties.IFace)>> keyValuePairs = Item.GetKeyValuePairs(argZero, containers); Dictionary<string, List<(DateTime, bool?, Shared.Models.PersonBirthday, IFace)>> keyValuePairs = Item.GetKeyValuePairs(argZero, containers);
results = GetThreeSigmaFaceEncodings(maxDegreeOfParallelism, keyValuePairs); results = GetThreeSigmaFaceEncodings(maxDegreeOfParallelism, keyValuePairs);
AddClosest(maxDegreeOfParallelism, argZero, containers, results); AddClosest(maxDegreeOfParallelism, argZero, propertyLogic, containers, results);
return results; return results;
} }
@ -707,7 +715,7 @@ internal class E_Distance
} }
} }
internal static List<(FileHolder? resizedFileHolder, string directory, FileInfo? faceFileInfo, string checkFile, string shortcutFile)> GetClosest(string argZero, List<Container> containers, Dictionary<string, List<Shared.Models.Person>> peopleCollection, PropertyLogic propertyLogic, string eDistanceContentDirectory, string dFacesContentDirectory) internal static List<(FileHolder? resizedFileHolder, string directory, FileInfo? faceFileInfo, string checkFile, string shortcutFile)> GetClosest(string argZero, List<Container> containers, Dictionary<string, List<Shared.Models.Person>> peopleCollection, string eDistanceContentDirectory, string dFacesContentDirectory)
{ {
List<(FileHolder?, string, FileInfo?, string, string)> results = new(); List<(FileHolder?, string, FileInfo?, string, string)> results = new();
string checkFile; string checkFile;
@ -720,8 +728,8 @@ internal class E_Distance
string facesDirectory; string facesDirectory;
string personDirectory; string personDirectory;
Shared.Models.Person person; Shared.Models.Person person;
float deterministicHashCodeKey;
const string facePopulatedKey = "Closest"; const string facePopulatedKey = "Closest";
string deterministicHashCodeIdAndFaceLocationIndex;
const string pattern = @"[\\,\/,\:,\*,\?,\"",\<,\>,\|]"; const string pattern = @"[\\,\/,\:,\*,\?,\"",\<,\>,\|]";
foreach (Container container in containers) foreach (Container container in containers)
{ {
@ -740,14 +748,10 @@ internal class E_Distance
throw new Exception(); throw new Exception();
foreach (Closest closest in item.Closest) foreach (Closest closest in item.Closest)
{ {
if (closest.Average is null || closest.FaceLocationIndex is null || closest.PersonBirthday is null) if (closest.Average is null || closest.NormalizedPixelPercentage is null || closest.PersonBirthday is null)
continue;
deterministicHashCodeIdAndFaceLocationIndex = $"{closest.FaceLocationIndex.Value} - {item.Property.Id.Value}";
if (propertyLogic.NamedDeterministicHashCodeIdAndFaceLocationIndex.Contains(deterministicHashCodeIdAndFaceLocationIndex))
continue; continue;
personKey = Shared.Models.Stateless.Methods.IPersonBirthday.GetFormatted(closest.PersonBirthday); personKey = Shared.Models.Stateless.Methods.IPersonBirthday.GetFormatted(closest.PersonBirthday);
directory = Item.GetDirectory(eDistanceContentDirectory, facePopulatedKey, closest.MinimumDateTime, closest.IsWrongYear, closest.PersonBirthday, personKey); directory = Item.GetDirectory(eDistanceContentDirectory, facePopulatedKey, closest.MinimumDateTime, closest.IsWrongYear, closest.PersonBirthday, personKey);
// checkFile = Path.Combine(directory, item.ImageFileHolder.Name);
if (!peopleCollection.ContainsKey(personKey)) if (!peopleCollection.ContainsKey(personKey))
personDirectory = string.Empty; personDirectory = string.Empty;
else else
@ -758,12 +762,13 @@ internal class E_Distance
results.Add(new(null, personDirectory, null, string.Empty, string.Empty)); results.Add(new(null, personDirectory, null, string.Empty, string.Empty));
} }
facesDirectory = string.Concat(dFacesContentDirectory, Path.Combine(directoryName, item.ImageFileHolder.NameWithoutExtension)); facesDirectory = string.Concat(dFacesContentDirectory, Path.Combine(directoryName, item.ImageFileHolder.NameWithoutExtension));
faceFileInfo = new(Path.Combine(facesDirectory, $"{closest.FaceLocationIndex.Value} - {item.ImageFileHolder.NameWithoutExtension}.png")); faceFileInfo = new(Path.Combine(facesDirectory, $"{closest.NormalizedPixelPercentage.Value} - {item.ImageFileHolder.NameWithoutExtension}.png"));
checkFile = Path.Combine(directory, $"{deterministicHashCodeIdAndFaceLocationIndex}{item.ImageFileHolder.ExtensionLowered}"); deterministicHashCodeKey = Named.GetDeterministicHashCodeKey(item, closest);
checkFile = Path.Combine(directory, $"{deterministicHashCodeKey}{item.ImageFileHolder.ExtensionLowered}");
if (string.IsNullOrEmpty(personDirectory)) if (string.IsNullOrEmpty(personDirectory))
shortcutFile = string.Empty; shortcutFile = string.Empty;
else else
shortcutFile = Path.Combine(personDirectory, $"{deterministicHashCodeIdAndFaceLocationIndex}{item.ImageFileHolder.ExtensionLowered}.lnk"); shortcutFile = Path.Combine(personDirectory, $"{item.ImageFileHolder.ExtensionLowered}.lnk");
results.Add(new(item.ResizedFileHolder, directory, faceFileInfo, checkFile, shortcutFile)); results.Add(new(item.ResizedFileHolder, directory, faceFileInfo, checkFile, shortcutFile));
} }
} }
@ -771,10 +776,10 @@ internal class E_Distance
return results; return results;
} }
internal static void SaveClosest(string argZero, List<Container> containers, Dictionary<string, List<Shared.Models.Person>> peopleCollection, PropertyLogic propertyLogic, string eDistanceContentDirectory, string dFacesContentDirectory) internal static void SaveClosest(string argZero, List<Container> containers, Dictionary<string, List<Shared.Models.Person>> peopleCollection, string eDistanceContentDirectory, string dFacesContentDirectory)
{ {
WindowsShortcut windowsShortcut; WindowsShortcut windowsShortcut;
List<(FileHolder? resizedFileHolder, string directory, FileInfo? faceFileInfo, string checkFile, string shortcutFile)> collection = GetClosest(argZero, containers, peopleCollection, propertyLogic, eDistanceContentDirectory, dFacesContentDirectory); List<(FileHolder? resizedFileHolder, string directory, FileInfo? faceFileInfo, string checkFile, string shortcutFile)> collection = GetClosest(argZero, containers, peopleCollection, eDistanceContentDirectory, dFacesContentDirectory);
string[] directories = (from l in collection select l.directory).Distinct().ToArray(); string[] directories = (from l in collection select l.directory).Distinct().ToArray();
foreach (string directory in directories) foreach (string directory in directories)
{ {

View File

@ -47,8 +47,6 @@ internal class F_Random
internal void Random(Property.Models.Configuration configuration, string outputResolution, List<KeyValuePair<string, string>> fileKeyValuePairs) internal void Random(Property.Models.Configuration configuration, string outputResolution, List<KeyValuePair<string, string>> fileKeyValuePairs)
{ {
if (_Configuration.SaveFullYearOfRandomFiles is null)
throw new Exception();
string json; string json;
string jsonFile; string jsonFile;
Random random = new(); Random random = new();
@ -74,7 +72,7 @@ internal class F_Random
jsonFile = Path.Combine(fRandomCollectionDirectory, $"{dateTime.AddDays(i):MM-dd}.json"); jsonFile = Path.Combine(fRandomCollectionDirectory, $"{dateTime.AddDays(i):MM-dd}.json");
json = JsonSerializer.Serialize(relativePaths, _WriteIndentedJsonSerializerOptions); json = JsonSerializer.Serialize(relativePaths, _WriteIndentedJsonSerializerOptions);
_ = Property.Models.Stateless.IPath.WriteAllText(jsonFile, json, updateDateWhenMatches: false, compareBeforeWrite: false); _ = Property.Models.Stateless.IPath.WriteAllText(jsonFile, json, updateDateWhenMatches: false, compareBeforeWrite: false);
if (!_Configuration.SaveFullYearOfRandomFiles.Value) if (!_Configuration.SaveFullYearOfRandomFiles)
break; break;
} }
} }

View File

@ -144,8 +144,6 @@ public class G_Index : Shared.Models.Properties.IIndex, IIndex
internal void SetIndex(Property.Models.Configuration configuration, Model? model, PredictorModel? predictorModel, string outputResolution, Dictionary<string, List<Tuple<string, A_Property>>> filePropertiesKeyValuePairs) internal void SetIndex(Property.Models.Configuration configuration, Model? model, PredictorModel? predictorModel, string outputResolution, Dictionary<string, List<Tuple<string, A_Property>>> filePropertiesKeyValuePairs)
{ {
if (_Configuration.PropertiesChangedForIndex is null)
throw new Exception();
FileInfo fileInfo; FileInfo fileInfo;
G_Index indexInfo; G_Index indexInfo;
string parentCheck; string parentCheck;
@ -181,7 +179,7 @@ public class G_Index : Shared.Models.Properties.IIndex, IIndex
if (File.Exists(parentCheck)) if (File.Exists(parentCheck))
File.Delete(parentCheck); File.Delete(parentCheck);
} }
if (_Configuration.PropertiesChangedForIndex.Value) if (_Configuration.PropertiesChangedForIndex)
indexInfo = null; indexInfo = null;
else if (!fileInfo.Exists) else if (!fileInfo.Exists)
indexInfo = null; indexInfo = null;

View File

@ -20,10 +20,8 @@ public class Program
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true); .AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true);
IConfigurationRoot configurationRoot = configurationBuilder.Build(); IConfigurationRoot configurationRoot = configurationBuilder.Build();
AppSettings appSettings = Models.Stateless.AppSettings.Get(configurationRoot); AppSettings appSettings = Models.Binder.AppSettings.Get(configurationRoot);
if (appSettings.MaxDegreeOfParallelism is null) if (appSettings.MaxDegreeOfParallelism > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be set!");
if (appSettings.MaxDegreeOfParallelism.Value > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!"); throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!");
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working directory name must have a value!"); throw new Exception("Working directory name must have a value!");

View File

@ -55,6 +55,7 @@
"DateGroup": "2022-08-14", "DateGroup": "2022-08-14",
"DistanceFactor": 8, "DistanceFactor": 8,
"FileNameDirectorySeparator": ".Z.", "FileNameDirectorySeparator": ".Z.",
"ForceFaceLastWriteTimeToCreationTime": false,
"ForceMetadataLastWriteTimeToCreationTime": false, "ForceMetadataLastWriteTimeToCreationTime": false,
"ForcePropertyLastWriteTimeToCreationTime": false, "ForcePropertyLastWriteTimeToCreationTime": false,
"ForceResizeLastWriteTimeToCreationTime": false, "ForceResizeLastWriteTimeToCreationTime": false,

View File

@ -55,6 +55,7 @@
"DateGroup": "2022-08-14", "DateGroup": "2022-08-14",
"DistanceFactor": 8, "DistanceFactor": 8,
"FileNameDirectorySeparator": ".Z.", "FileNameDirectorySeparator": ".Z.",
"ForceFaceLastWriteTimeToCreationTime": false,
"ForceMetadataLastWriteTimeToCreationTime": false, "ForceMetadataLastWriteTimeToCreationTime": false,
"ForcePropertyLastWriteTimeToCreationTime": false, "ForcePropertyLastWriteTimeToCreationTime": false,
"ForceResizeLastWriteTimeToCreationTime": false, "ForceResizeLastWriteTimeToCreationTime": false,

View File

@ -6,24 +6,16 @@ namespace View_by_Distance.Not.Copy.Copy.Models;
public class AppSettings public class AppSettings
{ {
protected string _Company; public string Company { init; get; }
protected string _WorkingDirectoryName; public int MaxDegreeOfParallelism { init; get; }
protected int? _MaxDegreeOfParallelism; public string WorkingDirectoryName { init; get; }
public string Company => _Company;
public string WorkingDirectoryName => _WorkingDirectoryName;
public int? MaxDegreeOfParallelism => _MaxDegreeOfParallelism;
// public AppSettings()
// {
// }
[JsonConstructor] [JsonConstructor]
public AppSettings(string company, string workingDirectoryName, int? maxDegreeOfParallelism) public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{ {
_Company = company; Company = company;
_WorkingDirectoryName = workingDirectoryName; MaxDegreeOfParallelism = maxDegreeOfParallelism;
_MaxDegreeOfParallelism = maxDegreeOfParallelism; WorkingDirectoryName = workingDirectoryName;
} }
public override string ToString() public override string ToString()

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Configuration;
using System.Text.Json; using System.Text.Json;
namespace View_by_Distance.Not.Copy.Copy.Models.Binder; namespace View_by_Distance.Not.Copy.Copy.Models.Binder;
@ -6,16 +6,13 @@ namespace View_by_Distance.Not.Copy.Copy.Models.Binder;
public class AppSettings public class AppSettings
{ {
[Display(Name = "Company"), Required] public string Company { get; set; } #nullable disable
[Display(Name = "Working Directory Name"), Required] public string WorkingDirectoryName { get; set; }
[Display(Name = "Max Degree Of Parallelism"), Required] public int? MaxDegreeOfParallelism { get; set; }
public AppSettings() public string Company { get; set; }
{ public int? MaxDegreeOfParallelism { get; set; }
Company = string.Empty; public string WorkingDirectoryName { get; set; }
WorkingDirectoryName = string.Empty;
MaxDegreeOfParallelism = -1; #nullable restore
}
public override string ToString() public override string ToString()
{ {
@ -23,4 +20,25 @@ public class AppSettings
return result; return result;
} }
private static Models.AppSettings Get(AppSettings appSettings)
{
Models.AppSettings result;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
} }

View File

@ -1,40 +0,0 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.Not.Copy.Copy.Models.Stateless;
public abstract class AppSettings
{
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings? result;
Binder.AppSettings appSettings = configurationRoot.Get<Binder.AppSettings>();
string json = JsonSerializer.Serialize(appSettings, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.AppSettings>(json);
if (result is null)
throw new Exception(json);
if (string.IsNullOrEmpty(result.Company))
throw new Exception(json);
string jsonThis = result.ToString();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -24,8 +24,6 @@ public class NotCopyCopy
if (console is null) if (console is null)
{ } { }
_AppSettings = appSettings; _AppSettings = appSettings;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
_IsEnvironment = isEnvironment; _IsEnvironment = isEnvironment;
_Log = Serilog.Log.ForContext<NotCopyCopy>(); _Log = Serilog.Log.ForContext<NotCopyCopy>();
Property.Models.Configuration propertyConfiguration = Property.Models.Stateless.Configuration.Get(isEnvironment, configurationRoot, workingDirectory); Property.Models.Configuration propertyConfiguration = Property.Models.Stateless.Configuration.Get(isEnvironment, configurationRoot, workingDirectory);
@ -108,11 +106,9 @@ public class NotCopyCopy
private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel) private PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel)
{ {
PropertyLogic result; PropertyLogic result;
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
result = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, reverse, model, predictorModel); result = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, reverse, model, predictorModel);
return result; return result;
} }

View File

@ -21,10 +21,8 @@ public class Program
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true); .AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true);
IConfigurationRoot configurationRoot = configurationBuilder.Build(); IConfigurationRoot configurationRoot = configurationBuilder.Build();
AppSettings appSettings = Models.Stateless.AppSettings.Get(configurationRoot); AppSettings appSettings = Models.Binder.AppSettings.Get(configurationRoot);
if (appSettings.MaxDegreeOfParallelism is null) if (appSettings.MaxDegreeOfParallelism > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be set!");
if (appSettings.MaxDegreeOfParallelism.Value > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!"); throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!");
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working directory name must have a value!"); throw new Exception("Working directory name must have a value!");

View File

@ -6,24 +6,16 @@ namespace View_by_Distance.PrepareForOld.Models;
public class AppSettings public class AppSettings
{ {
protected string _Company; public string Company { init; get; }
protected string _WorkingDirectoryName; public int MaxDegreeOfParallelism { init; get; }
protected int? _MaxDegreeOfParallelism; public string WorkingDirectoryName { init; get; }
public string Company => _Company;
public string WorkingDirectoryName => _WorkingDirectoryName;
public int? MaxDegreeOfParallelism => _MaxDegreeOfParallelism;
// public AppSettings()
// {
// }
[JsonConstructor] [JsonConstructor]
public AppSettings(string company, string workingDirectoryName, int? maxDegreeOfParallelism) public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{ {
_Company = company; Company = company;
_WorkingDirectoryName = workingDirectoryName; MaxDegreeOfParallelism = maxDegreeOfParallelism;
_MaxDegreeOfParallelism = maxDegreeOfParallelism; WorkingDirectoryName = workingDirectoryName;
} }
public override string ToString() public override string ToString()

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Configuration;
using System.Text.Json; using System.Text.Json;
namespace View_by_Distance.PrepareForOld.Models.Binder; namespace View_by_Distance.PrepareForOld.Models.Binder;
@ -6,16 +6,13 @@ namespace View_by_Distance.PrepareForOld.Models.Binder;
public class AppSettings public class AppSettings
{ {
[Display(Name = "Company"), Required] public string Company { get; set; } #nullable disable
[Display(Name = "Working Directory Name"), Required] public string WorkingDirectoryName { get; set; }
[Display(Name = "Max Degree Of Parallelism"), Required] public int? MaxDegreeOfParallelism { get; set; }
public AppSettings() public string Company { get; set; }
{ public int? MaxDegreeOfParallelism { get; set; }
Company = string.Empty; public string WorkingDirectoryName { get; set; }
WorkingDirectoryName = string.Empty;
MaxDegreeOfParallelism = -1; #nullable restore
}
public override string ToString() public override string ToString()
{ {
@ -23,4 +20,25 @@ public class AppSettings
return result; return result;
} }
private static Models.AppSettings Get(AppSettings appSettings)
{
Models.AppSettings result;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
} }

View File

@ -1,40 +0,0 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.PrepareForOld.Models.Stateless;
public abstract class AppSettings
{
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings? result;
Binder.AppSettings appSettings = configurationRoot.Get<Binder.AppSettings>();
string json = JsonSerializer.Serialize(appSettings, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.AppSettings>(json);
if (result is null)
throw new Exception(json);
if (string.IsNullOrEmpty(result.Company))
throw new Exception(json);
string jsonThis = result.ToString();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -29,8 +29,6 @@ public class PrepareForOld
string spellingA; string spellingA;
string spellingB; string spellingB;
_AppSettings = appSettings; _AppSettings = appSettings;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
_SpellingFindReplace = new(); _SpellingFindReplace = new();
_IsEnvironment = isEnvironment; _IsEnvironment = isEnvironment;
_Exceptions = new List<string>(); _Exceptions = new List<string>();
@ -225,8 +223,6 @@ public class PrepareForOld
{ {
if (_Log is null) if (_Log is null)
throw new NullReferenceException(nameof(_Log)); throw new NullReferenceException(nameof(_Log));
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
string? rootDirectoryParent = Path.GetDirectoryName(_Configuration.PropertyConfiguration.RootDirectory); string? rootDirectoryParent = Path.GetDirectoryName(_Configuration.PropertyConfiguration.RootDirectory);
@ -251,7 +247,7 @@ public class PrepareForOld
string infoDirectoryExtra = Path.Combine(imageSharedDirectory, "Images - 4) Info - - - Extra", "2022-04-14"); string infoDirectoryExtra = Path.Combine(imageSharedDirectory, "Images - 4) Info - - - Extra", "2022-04-14");
List<int> mappedIndices = GetUseTabSeparatedValueIndices(useDirectory); List<int> mappedIndices = GetUseTabSeparatedValueIndices(useDirectory);
List<(int Index, string RelativeDirectory, string FileName, string RegexResult, long Ticks, int? PropertyId, long? PropertyTicks)> collection = new(); List<(int Index, string RelativeDirectory, string FileName, string RegexResult, long Ticks, int? PropertyId, long? PropertyTicks)> collection = new();
PropertyCompare.Models.PropertyCompareLogic propertyCompareLogic = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, _SpellingFindReplace, diffRootDirectory); PropertyCompare.Models.PropertyCompareLogic propertyCompareLogic = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, _SpellingFindReplace, diffRootDirectory);
PropertyCompare.Models.PropertyCompare[] propertyCompareCollection = propertyCompareLogic.Get(aPropertySingletonDirectory, loadLessThan, duplicates, deleteExtension: false); PropertyCompare.Models.PropertyCompare[] propertyCompareCollection = propertyCompareLogic.Get(aPropertySingletonDirectory, loadLessThan, duplicates, deleteExtension: false);
{ {
long ticks = DateTime.Now.Ticks; long ticks = DateTime.Now.Ticks;
@ -592,8 +588,6 @@ public class PrepareForOld
{ {
if (_Log is null) if (_Log is null)
throw new NullReferenceException(nameof(_Log)); throw new NullReferenceException(nameof(_Log));
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
string? rootDirectoryParent = Path.GetDirectoryName(_Configuration.PropertyConfiguration.RootDirectory); string? rootDirectoryParent = Path.GetDirectoryName(_Configuration.PropertyConfiguration.RootDirectory);
@ -612,7 +606,7 @@ public class PrepareForOld
string namedFaceInfoFile = Path.Combine(imageSharedDirectory, "NamedFaceInfo.json"); string namedFaceInfoFile = Path.Combine(imageSharedDirectory, "NamedFaceInfo.json");
string infoDirectory = Path.Combine(imageSharedDirectory, "Images - 4) Info", "2020-06-07"); string infoDirectory = Path.Combine(imageSharedDirectory, "Images - 4) Info", "2020-06-07");
List<(int Index, string RelativeDirectory, string FileName, string RegexResult, long Ticks, int? PropertyId, long? PropertyTicks)> collection = new(); List<(int Index, string RelativeDirectory, string FileName, string RegexResult, long Ticks, int? PropertyId, long? PropertyTicks)> collection = new();
PropertyCompare.Models.PropertyCompareLogic propertyCompareLogic = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, _SpellingFindReplace, diffRootDirectory); PropertyCompare.Models.PropertyCompareLogic propertyCompareLogic = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, _SpellingFindReplace, diffRootDirectory);
PropertyCompare.Models.PropertyCompare[] propertyCompareCollection = propertyCompareLogic.Get(aPropertySingletonDirectory, loadLessThan); PropertyCompare.Models.PropertyCompare[] propertyCompareCollection = propertyCompareLogic.Get(aPropertySingletonDirectory, loadLessThan);
{ {
long ticks = DateTime.Now.Ticks; long ticks = DateTime.Now.Ticks;

View File

@ -21,10 +21,8 @@ public class Program
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true); .AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true);
IConfigurationRoot configurationRoot = configurationBuilder.Build(); IConfigurationRoot configurationRoot = configurationBuilder.Build();
AppSettings appSettings = Models.Stateless.AppSettings.Get(configurationRoot); AppSettings appSettings = Models.Binder.AppSettings.Get(configurationRoot);
if (appSettings.MaxDegreeOfParallelism is null) if (appSettings.MaxDegreeOfParallelism > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be set!");
if (appSettings.MaxDegreeOfParallelism.Value > Environment.ProcessorCount)
throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!"); throw new Exception("MaxDegreeOfParallelism must be =< Environment.ProcessorCount!");
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working directory name must have a value!"); throw new Exception("Working directory name must have a value!");

View File

@ -11,36 +11,36 @@ public class Closest
public const float MinimumMinimum = 0.05f; public const float MinimumMinimum = 0.05f;
protected readonly double? _Average; protected readonly double? _Average;
protected readonly int? _FaceLocationIndex; protected readonly int? _NormalizedPixelPercentage;
protected readonly bool? _IsWrongYear; protected readonly bool? _IsWrongYear;
protected readonly double? _Minimum; protected readonly double? _Minimum;
protected readonly DateTime _MinimumDateTime; protected readonly DateTime _MinimumDateTime;
protected readonly PersonBirthday? _PersonBirthday; protected readonly PersonBirthday? _PersonBirthday;
public double? Average => _Average; public double? Average => _Average;
public int? FaceLocationIndex => _FaceLocationIndex; public int? NormalizedPixelPercentage => _NormalizedPixelPercentage;
public bool? IsWrongYear => _IsWrongYear; public bool? IsWrongYear => _IsWrongYear;
public double? Minimum => _Minimum; public double? Minimum => _Minimum;
public DateTime MinimumDateTime => _MinimumDateTime; public DateTime MinimumDateTime => _MinimumDateTime;
public PersonBirthday? PersonBirthday => _PersonBirthday; public PersonBirthday? PersonBirthday => _PersonBirthday;
[JsonConstructor] [JsonConstructor]
public Closest(double? average, int? faceLocationIndex, bool? isWrongYear, double? minimum, DateTime minimumDateTime, PersonBirthday? personBirthday) public Closest(double? average, int? normalizedPixelPercentage, bool? isWrongYear, double? minimum, DateTime minimumDateTime, PersonBirthday? personBirthday)
{ {
_Average = average; _Average = average;
_FaceLocationIndex = faceLocationIndex; _NormalizedPixelPercentage = normalizedPixelPercentage;
_IsWrongYear = isWrongYear; _IsWrongYear = isWrongYear;
_Minimum = minimum; _Minimum = minimum;
_MinimumDateTime = minimumDateTime; _MinimumDateTime = minimumDateTime;
_PersonBirthday = personBirthday; _PersonBirthday = personBirthday;
} }
public Closest(int? faceLocationIndex, DateTime minimumDateTime, bool? isWrongYear) : public Closest(int? normalizedPixelPercentage, DateTime minimumDateTime, bool? isWrongYear) :
this(null, faceLocationIndex, isWrongYear, null, minimumDateTime, null) this(null, normalizedPixelPercentage, isWrongYear, null, minimumDateTime, null)
{ {
} }
public Closest(int? faceLocationIndex, DateTime minimumDateTime, bool? isWrongYear, PersonBirthday? personBirthday, List<double> faceDistances) : public Closest(int? normalizedPixelPercentage, DateTime minimumDateTime, bool? isWrongYear, PersonBirthday? personBirthday, List<double> faceDistances) :
this(faceDistances.Average(), faceLocationIndex, isWrongYear, faceDistances.Min(), minimumDateTime, personBirthday) this(faceDistances.Average(), normalizedPixelPercentage, isWrongYear, faceDistances.Min(), minimumDateTime, personBirthday)
{ {
} }

View File

@ -58,6 +58,7 @@ public class Item
_Named = new(); _Named = new();
_Closest = new(); _Closest = new();
_Changed = changed; _Changed = changed;
_Property = property;
_Abandoned = abandoned; _Abandoned = abandoned;
_NoJson = abandoned is null; _NoJson = abandoned is null;
_RelativePath = relativePath; _RelativePath = relativePath;
@ -90,43 +91,57 @@ public class Item
return result; return result;
} }
public static void AddToNamed(PropertyLogic propertyLogic, Item[] filteredItems) public static void AddToNamed(PropertyLogic propertyLogic, List<Item> items)
{ {
Item item;
bool? isWrongYear; bool? isWrongYear;
string[] segments;
string[] personKeys;
double? pixelPercentage;
DateTime minimumDateTime; DateTime minimumDateTime;
PersonBirthday? personBirthday; PersonBirthday? personBirthday;
for (int i = 0; i < filteredItems.Length; i++) float deterministicHashCodeKey;
List<string> personKeys = new();
foreach (Item item in items)
{ {
item = filteredItems[i];
if (item.ImageFileHolder is null) if (item.ImageFileHolder is null)
continue; continue;
if (item.Property?.Id is null || item.ResizedFileHolder is null) if (item.Property?.Id is null || item.ResizedFileHolder is null)
continue; continue;
if (!propertyLogic.NamedFaceInfoDeterministicHashCodeIds.ContainsKey(item.Property.Id.Value)) foreach (IFace face in item.Faces)
{
personKeys.Clear();
if (face.LocationIndex is null)
continue;
deterministicHashCodeKey = Models.Named.GetDeterministicHashCodeKey(item, face);
if (!propertyLogic.NamedDeterministicHashCodeKeyValuePairs.ContainsKey(deterministicHashCodeKey))
continue; continue;
minimumDateTime = Stateless.A_Property.GetMinimumDateTime(item.Property); minimumDateTime = Stateless.A_Property.GetMinimumDateTime(item.Property);
personKeys = propertyLogic.NamedFaceInfoDeterministicHashCodeIds[item.Property.Id.Value]; personKeys.AddRange(propertyLogic.NamedDeterministicHashCodeKeyValuePairs[deterministicHashCodeKey]);
(isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder.FullName, minimumDateTime); (isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder.FullName, minimumDateTime);
for (int j = 0; j < personKeys.Length; j++) for (int i = 0; i < personKeys.Count; i++)
{ {
segments = Shared.Models.Stateless.Methods.IPersonBirthday.GetSegments(personKeys[j]); personBirthday = Shared.Models.Stateless.Methods.IPersonBirthday.GetPersonBirthday(personKeys[i]);
personBirthday = Shared.Models.Stateless.Methods.IPersonBirthday.GetPersonBirthday(personKeys[j]);
if (personBirthday is null) if (personBirthday is null)
continue; continue;
if (segments.Length <= 1 || !double.TryParse(segments[1], out double value)) item.Named.Add(new(isWrongYear, minimumDateTime, face.Location.NormalizedPixelPercentage, personBirthday));
pixelPercentage = null; }
else }
pixelPercentage = value; if (!personKeys.Any())
item.Named.Add(new(isWrongYear, minimumDateTime, personBirthday, pixelPercentage)); {
if (!propertyLogic.NamedFaceInfoDeterministicHashCodeKeyValuePairs.ContainsKey(item.Property.Id.Value))
continue;
minimumDateTime = Stateless.A_Property.GetMinimumDateTime(item.Property);
personKeys.AddRange(propertyLogic.NamedFaceInfoDeterministicHashCodeKeyValuePairs[item.Property.Id.Value]);
(isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder.FullName, minimumDateTime);
for (int i = 0; i < personKeys.Count; i++)
{
personBirthday = Shared.Models.Stateless.Methods.IPersonBirthday.GetPersonBirthday(personKeys[i]);
if (personBirthday is null)
continue;
item.Named.Add(new(isWrongYear, minimumDateTime, personBirthday));
}
} }
} }
} }
public static List<(Item, (string, IFace?, (string, string, string, string))[])> GetCollection(PropertyLogic propertyLogic, Item[] filteredItems, string dFacesContentDirectory) public static List<(Item, (string, IFace?, (string, string, string, string))[])> GetCollection(PropertyLogic propertyLogic, List<Item> items, string dFacesContentDirectory)
{ {
List<(Item, (string, IFace?, (string, string, string, string))[])> results = new(); List<(Item, (string, IFace?, (string, string, string, string))[])> results = new();
Item item; Item item;
@ -134,7 +149,6 @@ public class Item
string directory; string directory;
string personKey; string personKey;
bool? isWrongYear; bool? isWrongYear;
string[] segments;
const int zero = 0; const int zero = 0;
TimeSpan? timeSpan; TimeSpan? timeSpan;
string copyFileName; string copyFileName;
@ -148,13 +162,12 @@ public class Item
List<IFace> faceCollection; List<IFace> faceCollection;
PersonBirthday? personBirthday; PersonBirthday? personBirthday;
List<(string, IFace?, (string, string, string, string))> collection; List<(string, IFace?, (string, string, string, string))> collection;
for (int i = 0; i < filteredItems.Length; i++) for (int i = 0; i < items.Count; i++)
{ {
indices.Clear(); indices.Clear();
personKey = string.Empty;
copyFileName = string.Empty; copyFileName = string.Empty;
copyDirectory = string.Empty; copyDirectory = string.Empty;
item = filteredItems[i]; item = items[i];
if (item.ImageFileHolder is null) if (item.ImageFileHolder is null)
continue; continue;
relativePath = Path.GetDirectoryName($"C:{item.RelativePath}"); relativePath = Path.GetDirectoryName($"C:{item.RelativePath}");
@ -163,15 +176,16 @@ public class Item
if (item.Property?.Id is null || item.ResizedFileHolder is null) if (item.Property?.Id is null || item.ResizedFileHolder is null)
continue; continue;
collection = new(); collection = new();
if (!propertyLogic.NamedFaceInfoDeterministicHashCodeIds.ContainsKey(item.Property.Id.Value)) if (!propertyLogic.NamedFaceInfoDeterministicHashCodeKeyValuePairs.ContainsKey(item.Property.Id.Value))
{ {
faceCollection = new(); faceCollection = new();
personKey = string.Empty;
directory = Path.Combine(dFacesContentDirectory, $"Unnamed{relativePath[2..]}"); directory = Path.Combine(dFacesContentDirectory, $"Unnamed{relativePath[2..]}");
} }
else else
{ {
faceCollection = item.Faces; faceCollection = item.Faces;
keys = propertyLogic.NamedFaceInfoDeterministicHashCodeIds[item.Property.Id.Value]; keys = propertyLogic.NamedFaceInfoDeterministicHashCodeKeyValuePairs[item.Property.Id.Value];
minimumDateTime = Stateless.A_Property.GetMinimumDateTime(item.Property); minimumDateTime = Stateless.A_Property.GetMinimumDateTime(item.Property);
if (minimumDateTime is null) if (minimumDateTime is null)
continue; continue;
@ -179,16 +193,25 @@ public class Item
isWrongYearFlag = GetWrongYearFlag(isWrongYear); isWrongYearFlag = GetWrongYearFlag(isWrongYear);
subDirectoryName = $"{isWrongYearFlag}{minimumDateTime.Value:yyyy}"; subDirectoryName = $"{isWrongYearFlag}{minimumDateTime.Value:yyyy}";
if (!faceCollection.Any()) if (!faceCollection.Any())
{
personKey = string.Empty;
directory = Path.Combine(dFacesContentDirectory, $"None{relativePath[2..]}", subDirectoryName); directory = Path.Combine(dFacesContentDirectory, $"None{relativePath[2..]}", subDirectoryName);
}
else if (keys.Length != 1) else if (keys.Length != 1)
{
personKey = string.Empty;
directory = Path.Combine(dFacesContentDirectory, $"Not Supported{relativePath[2..]}", subDirectoryName); directory = Path.Combine(dFacesContentDirectory, $"Not Supported{relativePath[2..]}", subDirectoryName);
}
else if (faceCollection.Count != 1) else if (faceCollection.Count != 1)
{
personKey = string.Empty;
directory = Path.Combine(dFacesContentDirectory, $"Many{relativePath[2..]}", subDirectoryName); directory = Path.Combine(dFacesContentDirectory, $"Many{relativePath[2..]}", subDirectoryName);
}
else else
{ {
indices.Add(zero); indices.Add(zero);
segments = Shared.Models.Stateless.Methods.IPersonBirthday.GetSegments(keys[zero]); personKey = keys[zero];
personBirthday = Shared.Models.Stateless.Methods.IPersonBirthday.GetPersonBirthday(keys[zero]); personBirthday = Shared.Models.Stateless.Methods.IPersonBirthday.GetPersonBirthday(personKey);
if (personBirthday is null) if (personBirthday is null)
continue; continue;
timeSpan = Shared.Models.Stateless.Methods.IPersonBirthday.GetTimeSpan(minimumDateTime.Value, isWrongYear, personBirthday); timeSpan = Shared.Models.Stateless.Methods.IPersonBirthday.GetTimeSpan(minimumDateTime.Value, isWrongYear, personBirthday);
@ -199,7 +222,6 @@ public class Item
else else
subDirectoryName = $"^{Math.Floor(timeSpan.Value.TotalDays / 365):000}"; subDirectoryName = $"^{Math.Floor(timeSpan.Value.TotalDays / 365):000}";
} }
personKey = segments[zero];
directory = Path.Combine(dFacesContentDirectory, "Shortcuts", personKey, subDirectoryName); directory = Path.Combine(dFacesContentDirectory, "Shortcuts", personKey, subDirectoryName);
if (faceCollection[zero].Populated) if (faceCollection[zero].Populated)
copyDirectory = Path.Combine(dFacesContentDirectory, "Images", personKey, subDirectoryName); copyDirectory = Path.Combine(dFacesContentDirectory, "Images", personKey, subDirectoryName);
@ -270,7 +292,7 @@ public class Item
continue; continue;
foreach (Named named in item.Named) foreach (Named named in item.Named)
{ {
if (named.PixelPercentage is null && (item.Named.Count != 1 || item.Faces.Count != 1)) if (named.NormalizedPixelPercentage is null && (item.Named.Count != 1 || item.Faces.Count != 1))
continue; continue;
foreach (IFace face in item.Faces) foreach (IFace face in item.Faces)
{ {
@ -278,13 +300,13 @@ public class Item
continue; continue;
if (named.PersonBirthday is null) if (named.PersonBirthday is null)
continue; continue;
if (named.PixelPercentage.HasValue && named.PixelPercentage.Value != face.Location.PixelPercentage) if (named.NormalizedPixelPercentage.HasValue && named.NormalizedPixelPercentage.Value != face.Location.NormalizedPixelPercentage)
continue; continue;
key = GetKey(named.MinimumDateTime, named.IsWrongYear, named.PersonBirthday); key = GetKey(named.MinimumDateTime, named.IsWrongYear, named.PersonBirthday);
if (!results.ContainsKey(key)) if (!results.ContainsKey(key))
results.Add(key, new()); results.Add(key, new());
results[key].Add(new(named.MinimumDateTime, named.IsWrongYear, named.PersonBirthday, face)); results[key].Add(new(named.MinimumDateTime, named.IsWrongYear, named.PersonBirthday, face));
if (named.PixelPercentage is null) if (named.NormalizedPixelPercentage is null)
break; break;
} }
} }

View File

@ -1,5 +1,6 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using View_by_Distance.Shared.Models; using View_by_Distance.Shared.Models;
using View_by_Distance.Shared.Models.Properties;
namespace View_by_Distance.Property.Models; namespace View_by_Distance.Property.Models;
@ -8,20 +9,77 @@ public class Named
protected readonly bool? _IsWrongYear; protected readonly bool? _IsWrongYear;
protected readonly DateTime _MinimumDateTime; protected readonly DateTime _MinimumDateTime;
protected readonly int? _NormalizedPixelPercentage;
protected readonly PersonBirthday? _PersonBirthday; protected readonly PersonBirthday? _PersonBirthday;
protected readonly double? _PixelPercentage;
public bool? IsWrongYear => _IsWrongYear; public bool? IsWrongYear => _IsWrongYear;
public DateTime MinimumDateTime => _MinimumDateTime; public DateTime MinimumDateTime => _MinimumDateTime;
public int? NormalizedPixelPercentage => _NormalizedPixelPercentage;
public PersonBirthday? PersonBirthday => _PersonBirthday; public PersonBirthday? PersonBirthday => _PersonBirthday;
public double? PixelPercentage => _PixelPercentage;
[JsonConstructor] [JsonConstructor]
public Named(bool? isWrongYear, DateTime minimumDateTime, PersonBirthday? personBirthday, double? pixelPercentage) public Named(bool? isWrongYear, DateTime minimumDateTime, int? normalizedPixelPercentage, PersonBirthday? personBirthday)
{ {
_IsWrongYear = isWrongYear; _IsWrongYear = isWrongYear;
_MinimumDateTime = minimumDateTime; _MinimumDateTime = minimumDateTime;
_NormalizedPixelPercentage = normalizedPixelPercentage;
_PersonBirthday = personBirthday; _PersonBirthday = personBirthday;
_PixelPercentage = pixelPercentage; }
public Named(bool? isWrongYear, DateTime minimumDateTime, PersonBirthday? personBirthday) :
this(isWrongYear, minimumDateTime, null, personBirthday)
{ }
private static float GetDeterministicHashCodeFileName(int id, int normalizedPixelPercentage)
=> float.Parse($"{id}.{normalizedPixelPercentage}");
public static float GetDeterministicHashCodeKey(Item item, Closest closest)
{
float result;
if (item.Property?.Id is null || item.ImageFileHolder is null || closest.NormalizedPixelPercentage is null)
throw new NullReferenceException();
result = GetDeterministicHashCodeFileName(item.Property.Id.Value, closest.NormalizedPixelPercentage.Value);
return result;
}
public static float GetDeterministicHashCodeKey(Item item, IFace face)
{
float result;
if (item.Property?.Id is null || item.ImageFileHolder is null || face.Location?.NormalizedPixelPercentage is null)
throw new NullReferenceException();
result = GetDeterministicHashCodeFileName(item.Property.Id.Value, face.Location.NormalizedPixelPercentage.Value);
return result;
}
public static float? GetReversedDeterministicHashCode(Dictionary<int, List<IFace>> keyValuePairs, string fileName)
{
float? result;
string[] segments = fileName.Split('.');
if (segments.Length < 2)
throw new Exception();
string id = segments[0];
string normalizedPixelPercentage;
if (!id.Contains('-'))
normalizedPixelPercentage = segments[1];
else
{
segments = fileName.Split(' ');
if (segments.Length < 3)
throw new Exception();
id = segments[2];
string locationIdex = segments[0];
if (int.TryParse(id, out int idValue) && int.TryParse(locationIdex, out int locationIndexValue) && keyValuePairs.ContainsKey(idValue) && keyValuePairs[idValue].Count > locationIndexValue)
normalizedPixelPercentage = string.Concat(keyValuePairs[idValue][locationIndexValue].Location.NormalizedPixelPercentage);
else
{
id = string.Empty;
normalizedPixelPercentage = string.Empty;
}
}
if (!float.TryParse(string.Concat(id, '.', normalizedPixelPercentage), out float resultValue))
result = null;
else
result = resultValue;
return result;
} }
} }

View File

@ -7,6 +7,7 @@ using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using View_by_Distance.Property.Models.Stateless; using View_by_Distance.Property.Models.Stateless;
using View_by_Distance.Shared.Models.Properties;
using View_by_Distance.Shared.Models.Stateless; using View_by_Distance.Shared.Models.Stateless;
namespace View_by_Distance.Property.Models; namespace View_by_Distance.Property.Models;
@ -18,17 +19,21 @@ public class PropertyLogic
protected readonly List<string> _ExceptionsDirectories; protected readonly List<string> _ExceptionsDirectories;
protected readonly Dictionary<int, int[]> _KeyValuePairs; protected readonly Dictionary<int, int[]> _KeyValuePairs;
protected readonly Dictionary<int, int[]> _IndicesFromNew; protected readonly Dictionary<int, int[]> _IndicesFromNew;
protected readonly string _DeterministicHashCodeRootDirectory;
protected readonly Dictionary<int, string[]> _SixCharacterNamedFaceInfo; protected readonly Dictionary<int, string[]> _SixCharacterNamedFaceInfo;
protected readonly List<string> _NamedDeterministicHashCodeIdAndFaceLocationIndex; protected readonly Dictionary<int, string[]> _NamedFaceInfoDeterministicHashCodeKeyValuePairs;
protected readonly Dictionary<int, string[]> _NamedFaceInfoDeterministicHashCodeIds; protected readonly Dictionary<float, string[]> _NamedDeterministicHashCodeKeyValuePairs;
protected readonly Dictionary<float, string[]> _IncorrectDeterministicHashCodeKeyValuePairs;
public bool Reverse { get; } public bool Reverse { get; }
public List<string> AngleBracketCollection { get; } public List<string> AngleBracketCollection { get; }
public Dictionary<int, int[]> KeyValuePairs => _KeyValuePairs; public Dictionary<int, int[]> KeyValuePairs => _KeyValuePairs;
public Dictionary<int, int[]> IndicesFromNew => _IndicesFromNew; public Dictionary<int, int[]> IndicesFromNew => _IndicesFromNew;
public List<string> ExceptionsDirectories => _ExceptionsDirectories; public List<string> ExceptionsDirectories => _ExceptionsDirectories;
public Dictionary<int, string[]> NamedFaceInfoDeterministicHashCodeIds => _NamedFaceInfoDeterministicHashCodeIds; public string DeterministicHashCodeRootDirectory => _DeterministicHashCodeRootDirectory;
public List<string> NamedDeterministicHashCodeIdAndFaceLocationIndex => _NamedDeterministicHashCodeIdAndFaceLocationIndex; public Dictionary<float, string[]> NamedDeterministicHashCodeKeyValuePairs => _NamedDeterministicHashCodeKeyValuePairs;
public Dictionary<float, string[]> IncorrectDeterministicHashCodeKeyValuePairs => _IncorrectDeterministicHashCodeKeyValuePairs;
public Dictionary<int, string[]> NamedFaceInfoDeterministicHashCodeKeyValuePairs => _NamedFaceInfoDeterministicHashCodeKeyValuePairs;
private readonly Model? _Model; private readonly Model? _Model;
private readonly Serilog.ILogger? _Log; private readonly Serilog.ILogger? _Log;
@ -51,7 +56,7 @@ public class PropertyLogic
AngleBracketCollection = new List<string>(); AngleBracketCollection = new List<string>();
_Log = Serilog.Log.ForContext<A_Property>(); _Log = Serilog.Log.ForContext<A_Property>();
_MaxDegreeOfParallelism = maxDegreeOfParallelism; _MaxDegreeOfParallelism = maxDegreeOfParallelism;
Dictionary<int, string[]>? namedFaceInfoDeterministicHashCodeIndices; Dictionary<int, string[]>? namedFaceInfoDeterministicHashCode;
_WriteIndentedJsonSerializerOptions = new JsonSerializerOptions { WriteIndented = true }; _WriteIndentedJsonSerializerOptions = new JsonSerializerOptions { WriteIndented = true };
if (configuration.VerifyToSeason is null || !configuration.VerifyToSeason.Any()) if (configuration.VerifyToSeason is null || !configuration.VerifyToSeason.Any())
throw new Exception(); throw new Exception();
@ -59,41 +64,29 @@ public class PropertyLogic
string json; string json;
string[] files; string[] files;
string fullPath; string fullPath;
List<string> namedDeterministicHashCodeIdAndFaceLocationIndex = new();
Dictionary<int, int[]>? keyValuePairs; Dictionary<int, int[]>? keyValuePairs;
string deterministicHashCodeRootDirectory;
List<KeyValuePair<int, int[]>>? collection; List<KeyValuePair<int, int[]>>? collection;
Dictionary<int, int[]> indicesFromNew = new(); Dictionary<int, int[]> indicesFromNew = new();
Dictionary<int, string[]>? sixCharacterNamedFaceInfo; Dictionary<int, string[]>? sixCharacterNamedFaceInfo;
Dictionary<float, string[]> namedDeterministicHashCode = new();
Dictionary<float, string[]> incorrectDeterministicHashCode = new();
string? rootDirectoryParent = Path.GetDirectoryName(configuration.RootDirectory); string? rootDirectoryParent = Path.GetDirectoryName(configuration.RootDirectory);
if (string.IsNullOrEmpty(rootDirectoryParent)) if (string.IsNullOrEmpty(rootDirectoryParent))
throw new NullReferenceException(nameof(rootDirectoryParent)); throw new NullReferenceException(nameof(rootDirectoryParent));
files = Directory.GetFiles(rootDirectoryParent, "*DeterministicHashCode*.json", SearchOption.TopDirectoryOnly); files = Directory.GetFiles(rootDirectoryParent, "*DeterministicHashCode*.json", SearchOption.TopDirectoryOnly);
if (files.Length != 1) if (files.Length != 1)
namedFaceInfoDeterministicHashCodeIndices = new(); namedFaceInfoDeterministicHashCode = new();
else else
{ {
json = File.ReadAllText(files[0]); json = File.ReadAllText(files[0]);
namedFaceInfoDeterministicHashCodeIndices = JsonSerializer.Deserialize<Dictionary<int, string[]>>(json); namedFaceInfoDeterministicHashCode = JsonSerializer.Deserialize<Dictionary<int, string[]>>(json);
if (namedFaceInfoDeterministicHashCodeIndices is null) if (namedFaceInfoDeterministicHashCode is null)
throw new NullReferenceException(nameof(namedFaceInfoDeterministicHashCodeIndices)); throw new NullReferenceException(nameof(namedFaceInfoDeterministicHashCode));
} }
if (namedFaceInfoDeterministicHashCodeIndices.Any()) if (namedFaceInfoDeterministicHashCode.Any())
{
sixCharacterNamedFaceInfo = new();
string[] directories = Directory.GetDirectories(rootDirectoryParent, "*DeterministicHashCode*", SearchOption.TopDirectoryOnly);
if (directories.Any())
{
Dictionary<int, string[]> ticksKeyValuePairs = GetKeyValuePairs(namedDeterministicHashCodeIdAndFaceLocationIndex, directories[0]);
foreach (KeyValuePair<int, string[]> keyValuePair in ticksKeyValuePairs)
{
if (namedFaceInfoDeterministicHashCodeIndices.ContainsKey(keyValuePair.Key))
continue;
namedFaceInfoDeterministicHashCodeIndices.Add(keyValuePair.Key, keyValuePair.Value);
}
}
}
else
{ {
deterministicHashCodeRootDirectory = string.Empty;
files = Directory.GetFiles(rootDirectoryParent, "*SixCharacter*.json", SearchOption.TopDirectoryOnly); files = Directory.GetFiles(rootDirectoryParent, "*SixCharacter*.json", SearchOption.TopDirectoryOnly);
if (files.Length != 1) if (files.Length != 1)
sixCharacterNamedFaceInfo = new(); sixCharacterNamedFaceInfo = new();
@ -105,6 +98,19 @@ public class PropertyLogic
throw new NullReferenceException(nameof(sixCharacterNamedFaceInfo)); throw new NullReferenceException(nameof(sixCharacterNamedFaceInfo));
} }
} }
else
{
sixCharacterNamedFaceInfo = new();
string[] directories = Directory.GetDirectories(rootDirectoryParent, "*DeterministicHashCode*", SearchOption.TopDirectoryOnly);
if (!directories.Any())
deterministicHashCodeRootDirectory = string.Empty;
else
{
Dictionary<int, List<IFace>> faces = new();
deterministicHashCodeRootDirectory = directories[0];
SetKeyValuePairs(deterministicHashCodeRootDirectory, namedDeterministicHashCode, incorrectDeterministicHashCode, faces);
}
}
files = Directory.GetFiles(rootDirectoryParent, "*keyValuePairs*.json", SearchOption.TopDirectoryOnly); files = Directory.GetFiles(rootDirectoryParent, "*keyValuePairs*.json", SearchOption.TopDirectoryOnly);
if (files.Length != 1) if (files.Length != 1)
keyValuePairs = new(); keyValuePairs = new();
@ -133,26 +139,25 @@ public class PropertyLogic
indicesFromNew.Add(keyValuePair.Key, keyValuePair.Value); indicesFromNew.Add(keyValuePair.Key, keyValuePair.Value);
} }
} }
_NamedDeterministicHashCodeIdAndFaceLocationIndex = namedDeterministicHashCodeIdAndFaceLocationIndex;
_KeyValuePairs = keyValuePairs; _KeyValuePairs = keyValuePairs;
_IndicesFromNew = indicesFromNew; _IndicesFromNew = indicesFromNew;
_SixCharacterNamedFaceInfo = sixCharacterNamedFaceInfo; _SixCharacterNamedFaceInfo = sixCharacterNamedFaceInfo;
_NamedFaceInfoDeterministicHashCodeIds = namedFaceInfoDeterministicHashCodeIndices; _NamedDeterministicHashCodeKeyValuePairs = namedDeterministicHashCode;
_DeterministicHashCodeRootDirectory = deterministicHashCodeRootDirectory;
_IncorrectDeterministicHashCodeKeyValuePairs = incorrectDeterministicHashCode;
_NamedFaceInfoDeterministicHashCodeKeyValuePairs = namedFaceInfoDeterministicHashCode;
} }
private static Dictionary<int, string[]> GetKeyValuePairs(List<string> namedDeterministicHashCodeIdAndFaceLocationIndex, string rootDirectory) private static void SetKeyValuePairs(string deterministicHashCodeRootDirectory, List<(string, float)> named, List<(string, float)> incorrect, Dictionary<int, List<IFace>> keyValuePairs)
{ {
Dictionary<int, string[]> results = new();
string id;
string[] files; string[] files;
string fileName;
string personKey; string personKey;
string[] segments;
string faceLocationIndex;
string[] yearDirectories; string[] yearDirectories;
string[] personKeyDirectories; string[] personKeyDirectories;
string[] personNameDirectories; string[] personNameDirectories;
string fileNameWithoutExtension; float? idAndNormalizedPixelPercentage;
string[] ticksDirectories = Directory.GetDirectories(rootDirectory, "*", SearchOption.TopDirectoryOnly); string[] ticksDirectories = Directory.GetDirectories(deterministicHashCodeRootDirectory, "*", SearchOption.TopDirectoryOnly);
foreach (string ticksDirectory in ticksDirectories) foreach (string ticksDirectory in ticksDirectories)
{ {
if (!ticksDirectory.EndsWith(')')) if (!ticksDirectory.EndsWith(')'))
@ -164,7 +169,18 @@ public class PropertyLogic
yearDirectories = Directory.GetDirectories(personKeyDirectory, "*", SearchOption.TopDirectoryOnly); yearDirectories = Directory.GetDirectories(personKeyDirectory, "*", SearchOption.TopDirectoryOnly);
foreach (string yearDirectory in yearDirectories) foreach (string yearDirectory in yearDirectories)
{ {
files = Directory.GetFiles(yearDirectory, "*", SearchOption.TopDirectoryOnly);
personNameDirectories = Directory.GetDirectories(yearDirectory, "*", SearchOption.TopDirectoryOnly); personNameDirectories = Directory.GetDirectories(yearDirectory, "*", SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
if (file.EndsWith(".lnk"))
continue;
fileName = Path.GetFileName(file);
idAndNormalizedPixelPercentage = Named.GetReversedDeterministicHashCode(keyValuePairs, fileName);
if (idAndNormalizedPixelPercentage is null)
break;
incorrect.Add(new(personKey, idAndNormalizedPixelPercentage.Value));
}
foreach (string personNameDirectory in personNameDirectories) foreach (string personNameDirectory in personNameDirectories)
{ {
files = Directory.GetFiles(personNameDirectory, "*", SearchOption.TopDirectoryOnly); files = Directory.GetFiles(personNameDirectory, "*", SearchOption.TopDirectoryOnly);
@ -172,24 +188,64 @@ public class PropertyLogic
{ {
if (file.EndsWith(".lnk")) if (file.EndsWith(".lnk"))
continue; continue;
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); fileName = Path.GetFileNameWithoutExtension(file);
segments = fileNameWithoutExtension.Split(' '); idAndNormalizedPixelPercentage = Named.GetReversedDeterministicHashCode(keyValuePairs, fileName);
if (segments.Length < 2) if (idAndNormalizedPixelPercentage is null)
break;
named.Add(new(personKey, idAndNormalizedPixelPercentage.Value));
}
}
}
}
}
}
private static void SetKeyValuePairs(string deterministicHashCodeRootDirectory, Dictionary<float, string[]> namedDeterministicHashCode, Dictionary<float, string[]> incorrectDeterministicHashCode, Dictionary<int, List<IFace>> keyValuePairs)
{
Dictionary<float, List<string>> namedKeyValuePairs = new();
Dictionary<float, List<string>> incorrectKeyValuePairs = new();
List<(string PersonKey, float IdAndNormalizedPixelPercentage)> named = new();
List<(string PersonKey, float IdAndNormalizedPixelPercentage)> incorrect = new();
SetKeyValuePairs(deterministicHashCodeRootDirectory, named, incorrect, keyValuePairs);
named = (from l in named orderby l.IdAndNormalizedPixelPercentage select l).ToList();
incorrect = (from l in incorrect orderby l.IdAndNormalizedPixelPercentage select l).ToList();
foreach ((string personKey, float idAndNormalizedPixelPercentage) in named)
{
if (!namedKeyValuePairs.ContainsKey(idAndNormalizedPixelPercentage))
namedKeyValuePairs.Add(idAndNormalizedPixelPercentage, new());
namedKeyValuePairs[idAndNormalizedPixelPercentage].Add(personKey);
}
foreach ((string personKey, float idAndNormalizedPixelPercentage) in incorrect)
{
if (!incorrectKeyValuePairs.ContainsKey(idAndNormalizedPixelPercentage))
incorrectKeyValuePairs.Add(idAndNormalizedPixelPercentage, new());
incorrectKeyValuePairs[idAndNormalizedPixelPercentage].Add(personKey);
}
foreach (KeyValuePair<float, List<string>> keyValuePair in namedKeyValuePairs)
namedDeterministicHashCode.Add(keyValuePair.Key, keyValuePair.Value.Distinct().ToArray());
foreach (KeyValuePair<float, List<string>> keyValuePair in incorrectKeyValuePairs)
incorrectDeterministicHashCode.Add(keyValuePair.Key, keyValuePair.Value.Distinct().ToArray());
}
public void UpdateKeyValuePairs(List<Container> containers)
{
Dictionary<int, List<IFace>> keyValuePairs = new();
Dictionary<float, string[]> namedDeterministicHashCode = new();
Dictionary<float, string[]> incorrectDeterministicHashCode = new();
foreach (Container container in containers)
{
foreach (Item item in container.Items)
{
if (item.ImageFileHolder is null || item.Property?.Id is null || !item.Faces.Any())
continue; continue;
id = segments[2]; keyValuePairs.Add(item.Property.Id.Value, item.Faces);
faceLocationIndex = segments[0];
if (!int.TryParse(id, out int idValue))
continue;
namedDeterministicHashCodeIdAndFaceLocationIndex.Add(fileNameWithoutExtension);
if (results.ContainsKey(idValue))
continue;
results.Add(idValue, new string[] { personKey });
} }
} }
} SetKeyValuePairs(_DeterministicHashCodeRootDirectory, namedDeterministicHashCode, incorrectDeterministicHashCode, keyValuePairs);
} foreach (KeyValuePair<float, string[]> keyValuePair in namedDeterministicHashCode)
} _NamedDeterministicHashCodeKeyValuePairs.Add(keyValuePair.Key, keyValuePair.Value);
return results; foreach (KeyValuePair<float, string[]> keyValuePair in incorrectDeterministicHashCode)
_IncorrectDeterministicHashCodeKeyValuePairs.Add(keyValuePair.Key, keyValuePair.Value);
} }
public override string ToString() public override string ToString()

View File

@ -13,7 +13,7 @@ public class Container
string[] sourceDirectoryFiles; string[] sourceDirectoryFiles;
List<string[]> fileCollections = new(); List<string[]> fileCollections = new();
if (!topDirectories.Any()) if (!topDirectories.Any())
topDirectories.AddRange(from l in Directory.GetDirectories(rootDirectory, "*", SearchOption.TopDirectoryOnly) select Path.GetFullPath(l)); topDirectories.AddRange(from l in Directory.GetDirectories(rootDirectory, "*", SearchOption.TopDirectoryOnly) orderby Path.GetFileName(l)[..1], l select Path.GetFullPath(l));
for (int g = 1; g < 5; g++) for (int g = 1; g < 5; g++)
{ {
if (g == 4) if (g == 4)

View File

@ -300,8 +300,10 @@ public class C_Resize
return results; return results;
} }
public void SaveResizedSubfile(string outputResolution, string cResultsFullGroupDirectory, List<Tuple<string, DateTime>> subFileTuples, Item item, string original, A_Property property, Dictionary<string, int[]> imageResizes) public void SaveResizedSubfile(string outputResolution, string cResultsFullGroupDirectory, List<Tuple<string, DateTime>> subFileTuples, Item item, string original, Dictionary<string, int[]> imageResizes)
{ {
if (item.Property is null)
throw new NullReferenceException(nameof(item.Property));
if (item.ImageFileHolder is null) if (item.ImageFileHolder is null)
throw new NullReferenceException(nameof(item.ImageFileHolder)); throw new NullReferenceException(nameof(item.ImageFileHolder));
if (item.ResizedFileHolder is null) if (item.ResizedFileHolder is null)
@ -347,7 +349,7 @@ public class C_Resize
check = true; check = true;
if (check) if (check)
{ {
_ = SaveResizedSubfile(item.ImageFileHolder.FullName, property, resize, fileHolder); _ = SaveResizedSubfile(item.ImageFileHolder.FullName, item.Property, resize, fileHolder);
subFileTuples.Add(new Tuple<string, DateTime>(nameof(C_Resize), DateTime.Now)); subFileTuples.Add(new Tuple<string, DateTime>(nameof(C_Resize), DateTime.Now));
} }
} }
@ -422,7 +424,7 @@ public class C_Resize
return results; return results;
} }
public Dictionary<string, int[]> GetResizeKeyValuePairs(string cResultsFullGroupDirectory, List<Tuple<string, DateTime>> subFileTuples, List<string> parseExceptions, string original, List<KeyValuePair<string, string>> metadataCollection, A_Property property, Item item) public Dictionary<string, int[]> GetResizeKeyValuePairs(string cResultsFullGroupDirectory, List<Tuple<string, DateTime>> subFileTuples, List<string> parseExceptions, string original, List<KeyValuePair<string, string>> metadataCollection, Item item)
{ {
Dictionary<string, int[]> results; Dictionary<string, int[]> results;
if (item.Property?.Id is null) if (item.Property?.Id is null)
@ -484,7 +486,7 @@ public class C_Resize
results = keyValuePairs; results = keyValuePairs;
if ((from l in results where l.Value[0] == l.Value[1] select true).Any()) if ((from l in results where l.Value[0] == l.Value[1] select true).Any())
{ {
results = GetImageResizes(property, metadataCollection, original); results = GetImageResizes(item.Property, metadataCollection, original);
if (!(from l in results where l.Value[0] == l.Value[1] select true).Any()) if (!(from l in results where l.Value[0] == l.Value[1] select true).Any())
throw new Exception("Was square!"); throw new Exception("Was square!");
} }
@ -498,7 +500,7 @@ public class C_Resize
} }
if (results is null || !results.Any()) if (results is null || !results.Any())
{ {
results = GetImageResizes(property, metadataCollection, original); results = GetImageResizes(item.Property, metadataCollection, original);
json = JsonSerializer.Serialize(results, _WriteIndentedJsonSerializerOptions); json = JsonSerializer.Serialize(results, _WriteIndentedJsonSerializerOptions);
bool updateDateWhenMatches = dateTimes.Any() && fileInfo.Exists && dateTimes.Max() > fileInfo.LastWriteTime; bool updateDateWhenMatches = dateTimes.Any() && fileInfo.Exists && dateTimes.Max() > fileInfo.LastWriteTime;
DateTime? dateTime = !updateDateWhenMatches ? null : dateTimes.Max(); DateTime? dateTime = !updateDateWhenMatches ? null : dateTimes.Max();

View File

@ -7,40 +7,40 @@ namespace View_by_Distance.Shared.Models;
public class Location : Properties.ILocation, ILocation, IEquatable<Location> public class Location : Properties.ILocation, ILocation, IEquatable<Location>
{ {
public double Confidence => _Confidence;
protected double _Confidence;
protected int _Bottom; protected int _Bottom;
protected double _Confidence;
protected int _Left; protected int _Left;
protected double? _PixelPercentage; protected readonly int? _NormalizedPixelPercentage;
protected int _Right; protected int _Right;
protected int _Top; protected int _Top;
public int Bottom => _Bottom; public int Bottom => _Bottom;
public double Confidence => _Confidence;
public int Left => _Left; public int Left => _Left;
public double? PixelPercentage => _PixelPercentage; public int? NormalizedPixelPercentage => _NormalizedPixelPercentage;
public int Right => _Right; public int Right => _Right;
public int Top => _Top; public int Top => _Top;
[JsonConstructor] [JsonConstructor]
public Location(double confidence, int bottom, int left, double? pixelPercentage, int right, int top) public Location(int bottom, double confidence, int left, int? normalizedPixelPercentage, int right, int top)
{ {
_Confidence = confidence; _Confidence = confidence;
_Bottom = bottom; _Bottom = bottom;
_Left = left; _Left = left;
_PixelPercentage = pixelPercentage; _NormalizedPixelPercentage = normalizedPixelPercentage;
_Right = right; _Right = right;
_Top = top; _Top = top;
} }
public Location(double confidence, int bottom, int left, int right, int top, int width, int height) : public Location(double confidence, int bottom, int left, int right, int top, int width, int height) :
this(confidence, bottom, left, GetPixelPercentage(bottom, left, right, top, width, height), right, top) this(bottom, confidence, left, GetNormalizedPixelPercentage(bottom, height, left, right, top, width), right, top)
{ } { }
public Location(double confidence, Location location, int width, int height) : public Location(double confidence, Location location, int width, int height) :
this(confidence, location.Bottom, location.Left, location.Right, location.Top, width, height) this(location.Bottom, confidence, location.Left, GetNormalizedPixelPercentage(location.Bottom, height, location.Left, location.Right, location.Top, width), location.Right, location.Top)
{ } { }
public Location(int left, int top, int right, int bottom, int width, int height) : public Location(int left, int top, int right, int bottom, int width, int height) :
this(-1.0d, bottom, left, right, top, width, height) this(bottom, -1.0d, left, GetNormalizedPixelPercentage(bottom, height, left, right, top, width), right, top)
{ } { }
public override bool Equals(object? obj) => Equals(obj as Location); public override bool Equals(object? obj) => Equals(obj as Location);
@ -61,13 +61,13 @@ public class Location : Properties.ILocation, ILocation, IEquatable<Location>
return hashCode; return hashCode;
} }
public static double GetPixelPercentage(int left, int top, int right, int bottom, int width, int height) public static int GetNormalizedPixelPercentage(int bottom, int height, int left, int right, int top, int width)
{ {
double result; double result;
double xCenter = left + ((right - left) / 2); double xCenter = left + ((right - left) / 2);
double yCenter = top + ((bottom - top) / 2); double yCenter = top + ((bottom - top) / 2);
result = ((yCenter * width) + xCenter) / (width * height); result = ((yCenter * width) + xCenter) / (width * height);
return (double)Math.Round((decimal)result, 4); return (int)(Math.Round((decimal)result, 4) * Stateless.Methods.ILocation.Factor);
} }
public bool Equals(Location? location) public bool Equals(Location? location)

View File

@ -3,9 +3,10 @@ namespace View_by_Distance.Shared.Models.Properties;
public interface ILocation public interface ILocation
{ {
public double Confidence { get; }
public int Bottom { get; } public int Bottom { get; }
public double Confidence { get; }
public int Left { get; } public int Left { get; }
public int? NormalizedPixelPercentage { get; }
public int Right { get; } public int Right { get; }
public int Top { get; } public int Top { get; }

View File

@ -0,0 +1,8 @@
namespace View_by_Distance.Shared.Models.Stateless.Methods;
public interface ILocation
{ // ...
public const int Factor = 10000;
}

View File

@ -12,9 +12,6 @@ public interface IPersonBirthday
string TestStatic_GetFormat() => PersonBirthday.GetFormat(); string TestStatic_GetFormat() => PersonBirthday.GetFormat();
static string GetFormat() => PersonBirthday.GetFormat(); static string GetFormat() => PersonBirthday.GetFormat();
string[] TestStatic_GetSegments(string personKey) => PersonBirthday.GetSegments(personKey);
static string[] GetSegments(string personKey) => PersonBirthday.GetSegments(personKey);
DateTime? TestStatic_GetDateTime(string personKey) => PersonBirthday.GetDateTime(personKey); DateTime? TestStatic_GetDateTime(string personKey) => PersonBirthday.GetDateTime(personKey);
static DateTime? GetDateTime(string personKey) => PersonBirthday.GetDateTime(personKey); static DateTime? GetDateTime(string personKey) => PersonBirthday.GetDateTime(personKey);

View File

@ -10,7 +10,6 @@ internal abstract class PersonBirthday
// ... // ...
internal static string GetFormat() => "yyyy-MM-dd_HH"; internal static string GetFormat() => "yyyy-MM-dd_HH";
internal static string[] GetSegments(string personKey) => personKey.Split('\t');
internal static string GetFormatted(Models.PersonBirthday personBirthday) => personBirthday.Value.ToString(GetFormat()); internal static string GetFormatted(Models.PersonBirthday personBirthday) => personBirthday.Value.ToString(GetFormat());
internal static string GetFileName(Models.PersonBirthday personBirthday) => $"{personBirthday.Value.ToString(GetFormat())}.json"; internal static string GetFileName(Models.PersonBirthday personBirthday) => $"{personBirthday.Value.ToString(GetFormat())}.json";
internal static bool DoesBirthDateExits(Properties.IStorage storage, Models.PersonBirthday personBirthday) => File.Exists(GetFileFullName(storage, personBirthday)); internal static bool DoesBirthDateExits(Properties.IStorage storage, Models.PersonBirthday personBirthday) => File.Exists(GetFileFullName(storage, personBirthday));
@ -21,8 +20,7 @@ internal abstract class PersonBirthday
internal static Models.PersonBirthday? GetPersonBirthday(string personKey) internal static Models.PersonBirthday? GetPersonBirthday(string personKey)
{ {
Models.PersonBirthday? result; Models.PersonBirthday? result;
string[] segments = GetSegments(personKey); DateTime? dateTime = GetDateTime(personKey);
DateTime? dateTime = GetDateTime(segments[0]);
if (dateTime is null) if (dateTime is null)
result = null; result = null;
else else

View File

@ -6,24 +6,16 @@ namespace View_by_Distance.Tests.Models;
public class AppSettings public class AppSettings
{ {
protected string _Company; public string Company { init; get; }
protected string _WorkingDirectoryName; public int MaxDegreeOfParallelism { init; get; }
protected int? _MaxDegreeOfParallelism; public string WorkingDirectoryName { init; get; }
public string Company => _Company;
public string WorkingDirectoryName => _WorkingDirectoryName;
public int? MaxDegreeOfParallelism => _MaxDegreeOfParallelism;
// public AppSettings()
// {
// }
[JsonConstructor] [JsonConstructor]
public AppSettings(string company, string workingDirectoryName, int? maxDegreeOfParallelism) public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{ {
_Company = company; Company = company;
_WorkingDirectoryName = workingDirectoryName; MaxDegreeOfParallelism = maxDegreeOfParallelism;
_MaxDegreeOfParallelism = maxDegreeOfParallelism; WorkingDirectoryName = workingDirectoryName;
} }
public override string ToString() public override string ToString()

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Configuration;
using System.Text.Json; using System.Text.Json;
namespace View_by_Distance.Tests.Models.Binder; namespace View_by_Distance.Tests.Models.Binder;
@ -6,16 +6,13 @@ namespace View_by_Distance.Tests.Models.Binder;
public class AppSettings public class AppSettings
{ {
[Display(Name = "Company"), Required] public string Company { get; set; } #nullable disable
[Display(Name = "Working Directory Name"), Required] public string WorkingDirectoryName { get; set; }
[Display(Name = "Max Degree Of Parallelism"), Required] public int? MaxDegreeOfParallelism { get; set; }
public AppSettings() public string Company { get; set; }
{ public int? MaxDegreeOfParallelism { get; set; }
Company = string.Empty; public string WorkingDirectoryName { get; set; }
WorkingDirectoryName = string.Empty;
MaxDegreeOfParallelism = -1; #nullable restore
}
public override string ToString() public override string ToString()
{ {
@ -23,4 +20,25 @@ public class AppSettings
return result; return result;
} }
private static Models.AppSettings Get(AppSettings appSettings)
{
Models.AppSettings result;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
} }

View File

@ -1,40 +0,0 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.Tests.Models.Stateless;
public abstract class AppSettings
{
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings? result;
Binder.AppSettings appSettings = configurationRoot.Get<Binder.AppSettings>();
string json = JsonSerializer.Serialize(appSettings, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.AppSettings>(json);
if (result is null)
throw new Exception(json);
if (string.IsNullOrEmpty(result.Company))
throw new Exception(json);
string jsonThis = result.ToString();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -38,7 +38,7 @@ public class UnitTestExample
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName); .AddJsonFile(isEnvironment.AppSettingsFileName);
configurationRoot = configurationBuilder.Build(); configurationRoot = configurationBuilder.Build();
appSettings = Models.Stateless.AppSettings.Get(configurationRoot); appSettings = Models.Binder.AppSettings.Get(configurationRoot);
workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName); workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName);
Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory); Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory);
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot); _ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot);

View File

@ -42,7 +42,7 @@ public class UnitTestResize
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName); .AddJsonFile(isEnvironment.AppSettingsFileName);
configurationRoot = configurationBuilder.Build(); configurationRoot = configurationBuilder.Build();
appSettings = Models.Stateless.AppSettings.Get(configurationRoot); appSettings = Models.Binder.AppSettings.Get(configurationRoot);
workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName); workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName);
Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory); Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory);
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot); _ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot);
@ -75,11 +75,9 @@ public class UnitTestResize
private Property.Models.PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel) private Property.Models.PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel)
{ {
Property.Models.PropertyLogic result; Property.Models.PropertyLogic result;
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
result = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, reverse, model, predictorModel); result = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, reverse, model, predictorModel);
return result; return result;
} }
@ -161,12 +159,16 @@ public class UnitTestResize
sourceDirectory = Path.Combine(aPropertySingletonDirectory, sourceDirectoryName); sourceDirectory = Path.Combine(aPropertySingletonDirectory, sourceDirectoryName);
item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false); item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false);
Assert.IsNotNull(item.ImageFileHolder); Assert.IsNotNull(item.ImageFileHolder);
if (item.Property is null)
{
property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions); property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions);
item.Update(property);
}
(int _, metadataCollection) = metadata.GetMetadataCollection(bResultsFullGroupDirectory, subFileTuples, parseExceptions, item); (int _, metadataCollection) = metadata.GetMetadataCollection(bResultsFullGroupDirectory, subFileTuples, parseExceptions, item);
imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, property, item); imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item);
Property.Models.FileHolder resizedFileHolder = new(Path.Combine(resize.AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName))); Property.Models.FileHolder resizedFileHolder = new(Path.Combine(resize.AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName)));
item.SetResizedFileHolder(resizedFileHolder); item.SetResizedFileHolder(resizedFileHolder);
resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, property, imageResizeKeyValuePairs); resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, imageResizeKeyValuePairs);
item.SetResizedFileHolder(Property.Models.FileHolder.Refresh(resizedFileHolder)); item.SetResizedFileHolder(Property.Models.FileHolder.Refresh(resizedFileHolder));
} }

View File

@ -6,24 +6,16 @@ namespace View_by_Distance.TestsWithFaceRecognitionDotNet.Models;
public class AppSettings public class AppSettings
{ {
protected string _Company; public string Company { init; get; }
protected string _WorkingDirectoryName; public int MaxDegreeOfParallelism { init; get; }
protected int? _MaxDegreeOfParallelism; public string WorkingDirectoryName { init; get; }
public string Company => _Company;
public string WorkingDirectoryName => _WorkingDirectoryName;
public int? MaxDegreeOfParallelism => _MaxDegreeOfParallelism;
// public AppSettings()
// {
// }
[JsonConstructor] [JsonConstructor]
public AppSettings(string company, string workingDirectoryName, int? maxDegreeOfParallelism) public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{ {
_Company = company; Company = company;
_WorkingDirectoryName = workingDirectoryName; MaxDegreeOfParallelism = maxDegreeOfParallelism;
_MaxDegreeOfParallelism = maxDegreeOfParallelism; WorkingDirectoryName = workingDirectoryName;
} }
public override string ToString() public override string ToString()

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Configuration;
using System.Text.Json; using System.Text.Json;
namespace View_by_Distance.TestsWithFaceRecognitionDotNet.Models.Binder; namespace View_by_Distance.TestsWithFaceRecognitionDotNet.Models.Binder;
@ -6,16 +6,13 @@ namespace View_by_Distance.TestsWithFaceRecognitionDotNet.Models.Binder;
public class AppSettings public class AppSettings
{ {
[Display(Name = "Company"), Required] public string Company { get; set; } #nullable disable
[Display(Name = "Working Directory Name"), Required] public string WorkingDirectoryName { get; set; }
[Display(Name = "Max Degree Of Parallelism"), Required] public int? MaxDegreeOfParallelism { get; set; }
public AppSettings() public string Company { get; set; }
{ public int? MaxDegreeOfParallelism { get; set; }
Company = string.Empty; public string WorkingDirectoryName { get; set; }
WorkingDirectoryName = string.Empty;
MaxDegreeOfParallelism = -1; #nullable restore
}
public override string ToString() public override string ToString()
{ {
@ -23,4 +20,25 @@ public class AppSettings
return result; return result;
} }
private static Models.AppSettings Get(AppSettings appSettings)
{
Models.AppSettings result;
if (appSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
} }

View File

@ -1,40 +0,0 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.TestsWithFaceRecognitionDotNet.Models.Stateless;
public abstract class AppSettings
{
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings? result;
Binder.AppSettings appSettings = configurationRoot.Get<Binder.AppSettings>();
string json = JsonSerializer.Serialize(appSettings, new JsonSerializerOptions() { WriteIndented = true });
result = JsonSerializer.Deserialize<Models.AppSettings>(json);
if (result is null)
throw new Exception(json);
if (string.IsNullOrEmpty(result.Company))
throw new Exception(json);
string jsonThis = result.ToString();
if (jsonThis != json)
{
int? check = null;
int min = new int[] { json.Length, jsonThis.Length }.Min();
for (int i = 0; i < min; i++)
{
if (json[i] == jsonThis[i])
continue;
check = i;
break;
}
if (check is null)
throw new Exception();
string a = json[..check.Value].Split(',')[^1];
string b = json[check.Value..].Split(',')[0];
throw new Exception($"{a}{b}");
}
return result;
}
}

View File

@ -7,6 +7,11 @@
<RuntimeIdentifier>win-x64</RuntimeIdentifier> <RuntimeIdentifier>win-x64</RuntimeIdentifier>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<VSTestLogger>trx</VSTestLogger>
<VSTestCollect>XPlat Code Coverage</VSTestCollect>
<VSTestResultsDirectory>../.vscode/TestResults</VSTestResultsDirectory>
</PropertyGroup>
<PropertyGroup> <PropertyGroup>
<IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows> <IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows>
<IsOSX Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true'">true</IsOSX> <IsOSX Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true'">true</IsOSX>

View File

@ -38,7 +38,7 @@ public class UnitTestExample
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName); .AddJsonFile(isEnvironment.AppSettingsFileName);
configurationRoot = configurationBuilder.Build(); configurationRoot = configurationBuilder.Build();
appSettings = Models.Stateless.AppSettings.Get(configurationRoot); appSettings = Models.Binder.AppSettings.Get(configurationRoot);
workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName); workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName);
Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory); Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory);
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot); _ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot);

View File

@ -44,7 +44,7 @@ public class UnitTestFace
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile(isEnvironment.AppSettingsFileName); .AddJsonFile(isEnvironment.AppSettingsFileName);
configurationRoot = configurationBuilder.Build(); configurationRoot = configurationBuilder.Build();
appSettings = Models.Stateless.AppSettings.Get(configurationRoot); appSettings = Models.Binder.AppSettings.Get(configurationRoot);
workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName); workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName);
Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory); Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory);
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot); _ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot);
@ -77,11 +77,9 @@ public class UnitTestFace
private Property.Models.PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel) private Property.Models.PropertyLogic GetPropertyLogic(bool reverse, Model? model, PredictorModel? predictorModel)
{ {
Property.Models.PropertyLogic result; Property.Models.PropertyLogic result;
if (_AppSettings.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(_AppSettings.MaxDegreeOfParallelism));
if (_Configuration?.PropertyConfiguration is null) if (_Configuration?.PropertyConfiguration is null)
throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration)); throw new NullReferenceException(nameof(_Configuration.PropertyConfiguration));
result = new(_AppSettings.MaxDegreeOfParallelism.Value, _Configuration.PropertyConfiguration, reverse, model, predictorModel); result = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, reverse, model, predictorModel);
return result; return result;
} }
@ -129,11 +127,32 @@ public class UnitTestFace
[TestMethod] [TestMethod]
public void TestGetPixelPercentage() public void TestGetPixelPercentage()
{ {
double pixelPercentage; int normalizedPixelPercentage;
pixelPercentage = Location.GetPixelPercentage(1, 1, 10, 10, 100, 100); int left, top, right, bottom, width, height;
Assert.IsTrue(pixelPercentage == 0.0505d); left = 1;
pixelPercentage = Location.GetPixelPercentage(50, 50, 60, 60, 100, 100); top = 1;
Assert.IsTrue(pixelPercentage == 0.5555d); right = 10;
bottom = 10;
width = 100;
height = 100;
normalizedPixelPercentage = Location.GetNormalizedPixelPercentage(bottom, height, left, right, top, width);
Assert.IsTrue(normalizedPixelPercentage == 0505);
left = 50;
top = 50;
right = 60;
bottom = 60;
width = 100;
height = 100;
normalizedPixelPercentage = Location.GetNormalizedPixelPercentage(bottom, height, left, right, top, width);
Assert.IsTrue(normalizedPixelPercentage == 5555);
left = 20;
top = 40;
right = 60;
bottom = 80;
width = 100;
height = 100;
normalizedPixelPercentage = Location.GetNormalizedPixelPercentage(bottom, height, left, right, top, width);
Assert.IsTrue(normalizedPixelPercentage == 6040);
} }
[TestMethod] [TestMethod]
@ -223,18 +242,22 @@ public class UnitTestFace
sourceDirectory = Path.Combine(aPropertySingletonDirectory, sourceDirectoryName); sourceDirectory = Path.Combine(aPropertySingletonDirectory, sourceDirectoryName);
item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false); item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false);
Assert.IsNotNull(item.ImageFileHolder); Assert.IsNotNull(item.ImageFileHolder);
if (item.Property is null)
{
property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions); property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions);
item.Update(property);
}
(int _, metadataCollection) = metadata.GetMetadataCollection(bResultsFullGroupDirectory, subFileTuples, parseExceptions, item); (int _, metadataCollection) = metadata.GetMetadataCollection(bResultsFullGroupDirectory, subFileTuples, parseExceptions, item);
imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, property, item); imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item);
Property.Models.FileHolder resizedFileHolder = new(Path.Combine(resize.AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName))); Property.Models.FileHolder resizedFileHolder = new(Path.Combine(resize.AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName)));
item.SetResizedFileHolder(resizedFileHolder); item.SetResizedFileHolder(resizedFileHolder);
resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, property, imageResizeKeyValuePairs); resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, imageResizeKeyValuePairs);
item.SetResizedFileHolder(Property.Models.FileHolder.Refresh(resizedFileHolder)); item.SetResizedFileHolder(Property.Models.FileHolder.Refresh(resizedFileHolder));
Assert.IsNotNull(item.ResizedFileHolder); Assert.IsNotNull(item.ResizedFileHolder);
Image? image = FaceRecognition.LoadImageFile(item.ResizedFileHolder.FullName); Image? image = FaceRecognition.LoadImageFile(item.ResizedFileHolder.FullName);
Assert.IsNotNull(image); Assert.IsNotNull(image);
FaceRecognition faceRecognition = FaceRecognition.Create(modelParameter); FaceRecognition faceRecognition = FaceRecognition.Create(modelParameter);
List<Location> locations = faceRecognition.FaceLocations(model, image, _Configuration.NumberOfTimesToUpsample.Value, sortByPixelPercentage: true); List<Location> locations = faceRecognition.FaceLocations(model, image, _Configuration.NumberOfTimesToUpsample.Value, sortByNormalizedPixelPercentage: true);
Assert.IsTrue(locations.Count == 2); Assert.IsTrue(locations.Count == 2);
List<(FacePart, FacePoint[])[]> faceLandmarks = faceRecognition.GetFaceLandmarkCollection(image, _Configuration.NumberOfTimesToUpsample.Value, locations, predictorModel, model); List<(FacePart, FacePoint[])[]> faceLandmarks = faceRecognition.GetFaceLandmarkCollection(image, _Configuration.NumberOfTimesToUpsample.Value, locations, predictorModel, model);
Assert.IsTrue(faceLandmarks.Count == 2); Assert.IsTrue(faceLandmarks.Count == 2);