diff --git a/.editorconfig b/.editorconfig index 2656b69..7f34a0d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -81,8 +81,12 @@ dotnet_diagnostic.CA1825.severity = warning # CA1823: Avoid zero-length array al dotnet_diagnostic.CA1829.severity = warning # CA1829: Use Length/Count property instead of Count() when available dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name -dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) System.Version.Equals("1", "2"); Version.Equals("1", "2"); -dotnet_diagnostic.IDE0005.severity = warning # Using directive is unnecessary using System.Text; +dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant. +dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2"); +dotnet_diagnostic.IDE0005.severity = warning # Using directive is unnecessary +dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031) +dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed +dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049) dotnet_diagnostic.IDE0060.severity = warning # IDE0060: Remove unused parameter dotnet_naming_rule.abstract_method_should_be_pascal_case.severity = warning dotnet_naming_rule.abstract_method_should_be_pascal_case.style = pascal_case @@ -215,7 +219,7 @@ dotnet_style_parentheses_in_other_binary_operators = always_for_clarity dotnet_style_parentheses_in_other_operators = never_if_unnecessary dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true +dotnet_style_predefined_type_for_member_access = true:warning dotnet_style_prefer_auto_properties = true:warning dotnet_style_prefer_compound_assignment = true:warning dotnet_style_prefer_conditional_expression_over_assignment = false diff --git a/.txt b/.txt index 50f3116..377b236 100644 --- a/.txt +++ b/.txt @@ -1,13 +1,14 @@ - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Compare" "L:\Git\View-by-Distance\Compare" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Date-Group" "L:\Git\View-by-Distance\Date-Group" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Distance" "L:\Git\View-by-Distance\Distance" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Face" "L:\Git\View-by-Distance\Face" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\FaceParts" "L:\Git\View-by-Distance\FaceParts" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Instance" "L:\Git\View-by-Distance\Instance" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Metadata" "L:\Git\View-by-Distance\Metadata" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Not-Copy-Copy" "L:\Git\View-by-Distance\Not-Copy-Copy" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\PrepareForOld" "L:\Git\View-by-Distance\PrepareForOld" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Property" "L:\Git\View-by-Distance\Property" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Property-Compare" "L:\Git\View-by-Distance\Property-Compare" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Resize" "L:\Git\View-by-Distance\Resize" - mklink /J "L:\Git\View-by-Distance-MKLink-Console\Shared" "L:\Git\View-by-Distance\Shared" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Compare" -Target "L:\Git\View-by-Distance\Compare" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Date-Group" -Target "L:\Git\View-by-Distance\Date-Group" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Distance" -Target "L:\Git\View-by-Distance\Distance" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Face" -Target "L:\Git\View-by-Distance\Face" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\FaceParts" -Target "L:\Git\View-by-Distance\FaceParts" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Instance" -Target "L:\Git\View-by-Distance\Instance" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Metadata" -Target "L:\Git\View-by-Distance\Metadata" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Not-Copy-Copy" -Target "L:\Git\View-by-Distance\Not-Copy-Copy" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\PrepareForOld" -Target "L:\Git\View-by-Distance\PrepareForOld" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Property" -Target "L:\Git\View-by-Distance\Property" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Property-Compare" -Target "L:\Git\View-by-Distance\Property-Compare" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Resize" -Target "L:\Git\View-by-Distance\Resize" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Shared" -Target "L:\Git\View-by-Distance\Shared" +New-Item -ItemType "junction" -Path "L:\Git\View-by-Distance-MKLink-Console\Rename" -Target "L:\Git\View-by-Distance\Rename" diff --git a/.vscode/launch.json b/.vscode/launch.json index cac894c..39acf54 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,12 +10,12 @@ "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. - "programC": "${workspaceFolder}/Compare/bin/Debug/net6.0/win-x64/Compare.dll", - "programD": "${workspaceFolder}/Date-Group/bin/Debug/net6.0/win-x64/Date-Group.dll", - "programDD": "${workspaceFolder}/Drag-Drop/bin/Debug/net6.0-windows/win-x64/Drag-Drop.dll", - "program": "${workspaceFolder}/Instance/bin/Debug/net6.0/win-x64/Instance.dll", - "programN": "${workspaceFolder}/Not-Copy-Copy/bin/Debug/net6.0/win-x64/Not-Copy-Copy.dll", - "programP": "${workspaceFolder}/PrepareForOld/bin/Debug/net6.0/win-x64/PrepareForOld.dll", + "programC": "${workspaceFolder}/Compare/bin/Debug/net7.0/win-x64/Compare.dll", + "programD": "${workspaceFolder}/Date-Group/bin/Debug/net7.0/win-x64/Date-Group.dll", + "programDD": "${workspaceFolder}/Drag-Drop/bin/Debug/net7.0-windows/win-x64/Drag-Drop.dll", + "program": "${workspaceFolder}/Instance/bin/Debug/net7.0/win-x64/Instance.dll", + "programN": "${workspaceFolder}/Not-Copy-Copy/bin/Debug/net7.0/win-x64/Not-Copy-Copy.dll", + "programP": "${workspaceFolder}/PrepareForOld/bin/Debug/net7.0/win-x64/PrepareForOld.dll", "args": [ "s" ], @@ -146,4 +146,42 @@ // https://scontent-lax3-2.xx.fbcdn.net/v/t39.30808-6/280689051_10209840036394561_8737214584492733274_n.jpg?_nc_cat=101&ccb=1-7&_nc_sid=8bfeb9&_nc_ohc=iMAAHqNekCgAX8fvEAm&_nc_ht=scontent-lax3-2.xx&oh=00_AT8b7_ODsDN7lNgTKr7JZiUE65R7WWYxENl1vOUGeobpBw&oe=6336E678 // https://scontent-lax3-1.xx.fbcdn.net/v/t1.18169-9/25110_107749419250772_1842086_n.jpg?_nc_cat=104&ccb=1-7&_nc_sid=09cbfe&_nc_ohc=xPyRCvImlaoAX9Z_UTs&_nc_ht=scontent-lax3-1.xx&oh=00_AT85xffhHDJlhzyFTBvWs8j3Gd4GyDCte_Pnd7hNM006sw&oe=635880C2 // https://scontent-lax3-2.xx.fbcdn.net/v/t1.18169-9/10259940_10153561109653458_6837681277740526675_n.jpg?_nc_cat=100&ccb=1-7&_nc_sid=8bfeb9&_nc_ohc=T1v9Wfqz8rUAX8y6bxq&tn=D0unuoVdv--xjhpM&_nc_ht=scontent-lax3-2.xx&oh=00_AT9Y9j5s19n0EzgO_dZMom8tAweFYIrJLOEsrsr4HAWHkQ&oe=63588CAE -// https://scontent-lax3-1.xx.fbcdn.net/v/t31.18172-8/17621858_10154253751886426_3939148233753829194_o.jpg?_nc_cat=104&ccb=1-7&_nc_sid=ad2b24&_nc_ohc=yMOqJQQBV80AX8Xlzr-&_nc_ht=scontent-lax3-1.xx&oh=00_AT_z0oeHJ0fqKhVA4WdgGE2cZSgL0bIKNXzPsY0zeLipAg&oe=6356AF4C \ No newline at end of file +// https://scontent-lax3-1.xx.fbcdn.net/v/t31.18172-8/17621858_10154253751886426_3939148233753829194_o.jpg?_nc_cat=104&ccb=1-7&_nc_sid=ad2b24&_nc_ohc=yMOqJQQBV80AX8Xlzr-&_nc_ht=scontent-lax3-1.xx&oh=00_AT_z0oeHJ0fqKhVA4WdgGE2cZSgL0bIKNXzPsY0zeLipAg&oe=6356AF4C +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// FileSizeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// LastWriteTimeChanged +// - Device Videos 2_0_0_3 - Current - Kristy Google +// - Device Videos 2_0_0_3 - Current - Mike Google +// - Device Videos 2_0_0_3 - Current - Tracy +// Chester & Linores ?Pearson? \ No newline at end of file diff --git a/Compare/Compare.csproj b/Compare/Compare.csproj index b1e4352..39f6d9d 100644 --- a/Compare/Compare.csproj +++ b/Compare/Compare.csproj @@ -5,7 +5,7 @@ enable Exe win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Compare @@ -34,22 +34,18 @@ - - - - - - - - + + + + + + - - - - - - - + + + + + diff --git a/Compare/Models/Binder/AppSettings.cs b/Compare/Models/Binder/AppSettings.cs index ef8806e..db68777 100644 --- a/Compare/Models/Binder/AppSettings.cs +++ b/Compare/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/Compare/Models/Stateless/Configuration.cs b/Compare/Models/Stateless/Configuration.cs index f86b786..fef7e4c 100644 --- a/Compare/Models/Stateless/Configuration.cs +++ b/Compare/Models/Stateless/Configuration.cs @@ -13,7 +13,7 @@ public abstract class Configuration 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? configuration = configurationSection.Get(); string json = JsonSerializer.Serialize(configuration, new JsonSerializerOptions() { WriteIndented = true }); result = JsonSerializer.Deserialize(json); if (result is null) diff --git a/Compare/appsettings.Development.json b/Compare/appsettings.Development.json index 56accd0..e71121a 100644 --- a/Compare/appsettings.Development.json +++ b/Compare/appsettings.Development.json @@ -79,7 +79,7 @@ "/zzz Phares Slides/Slides 2015-06-10/Magazine 01" ], "Configuration": { - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "DiffPropertyDirectory": "", "FileNameDirectorySeparator": ".Z.", "ForcePropertyLastWriteTimeToCreationTime": false, @@ -87,20 +87,20 @@ "Pattern": "[^ABCDEFGHIJKLMNOPQRSTUVWXYZbcdfghjklmnpqrstvwxyz0-9]", "PopulatePropertyId": true, "PropertiesChangedForProperty": false, - "RootDirectory": "C:/Tmp/Phares/Compare/Images 2022-10-23 - 239acf2 - III", + "RootDirectory": "C:/Tmp/Phares/Compare/Images 2022-11-12 - c6aa7e8 - III", "WriteBitmapDataBytes": false, "IgnoreExtensions": [ ".gif", ".GIF" ], "PropertyContentCollectionFiles": [ - "/Images 2022-10-23 - 239acf2 - III - Results/A) Property/2022-10-23/[()]/637869381676042455.json", - "/Not-Copy-Copy/Images 2019-06-08 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869733124119330.json", - "/Not-Copy-Copy/Images 2018-12-25 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869734240700328.json", - "/Not-Copy-Copy/Images 2018-05-12 - b01d4763d8853b6d6057a3870b2723449726da75 - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869734970730630.json", - "/Not-Copy-Copy/Images 2013-12-15 - d02c8791fa0b130c0bce2d39ee684e50f7ee7a97 - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869743752078399.json", - "/Not-Copy-Copy - Delta/Amazon Drive - Results/A) Property/2022-10-23/[()]/637869744751177715.json", - "/Not-Copy-Copy - Delta/Blackberry - Results/A) Property/2022-10-23/[()]/637869745134124462.json" + "/Images 2022-11-12 - c6aa7e8 - III - Results/A) Property/2022-11-12/[()]/637869381676042455.json", + "/Not-Copy-Copy/Images 2019-06-08 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869733124119330.json", + "/Not-Copy-Copy/Images 2018-12-25 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869734240700328.json", + "/Not-Copy-Copy/Images 2018-05-12 - b01d4763d8853b6d6057a3870b2723449726da75 - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869734970730630.json", + "/Not-Copy-Copy/Images 2013-12-15 - d02c8791fa0b130c0bce2d39ee684e50f7ee7a97 - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869743752078399.json", + "/Not-Copy-Copy - Delta/Amazon Drive - Results/A) Property/2022-11-12/[()]/637869744751177715.json", + "/Not-Copy-Copy - Delta/Blackberry - Results/A) Property/2022-11-12/[()]/637869745134124462.json" ], "ValidImageFormatExtensions": [ ".bmp", @@ -119,8 +119,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/Compare/appsettings.json b/Compare/appsettings.json index bf46a1a..43832f5 100644 --- a/Compare/appsettings.json +++ b/Compare/appsettings.json @@ -50,7 +50,7 @@ "WorkingDirectoryName": "PharesApps", "Windows": { "Configuration": { - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "DiffPropertyDirectory": "", "FileNameDirectorySeparator": ".Z.", "ForcePropertyLastWriteTimeToCreationTime": false, @@ -94,13 +94,13 @@ ".GIF" ], "PropertyContentCollectionFiles": [ - "/Images 2022-10-23 - 239acf2 - III - Results/A) Property/2022-10-23/[()]/637869381676042455.json", - "/Not-Copy-Copy/Images 2019-06-08 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869733124119330.json", - "/Not-Copy-Copy/Images 2018-12-25 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869734240700328.json", - "/Not-Copy-Copy/Images 2018-05-12 - b01d4763d8853b6d6057a3870b2723449726da75 - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869734970730630.json", - "/Not-Copy-Copy/Images 2013-12-15 - d02c8791fa0b130c0bce2d39ee684e50f7ee7a97 - Not-Copy-Copy - Results/A) Property/2022-10-23/[()]/637869743752078399.json", - "/Not-Copy-Copy - Delta/Amazon Drive - Results/A) Property/2022-10-23/[()]/637869744751177715.json", - "/Not-Copy-Copy - Delta/Blackberry - Results/A) Property/2022-10-23/[()]/637869745134124462.json" + "/Images 2022-11-12 - c6aa7e8 - III - Results/A) Property/2022-11-12/[()]/637869381676042455.json", + "/Not-Copy-Copy/Images 2019-06-08 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869733124119330.json", + "/Not-Copy-Copy/Images 2018-12-25 - 34a9240ac28b52da97428d7725153a80a757ee6b - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869734240700328.json", + "/Not-Copy-Copy/Images 2018-05-12 - b01d4763d8853b6d6057a3870b2723449726da75 - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869734970730630.json", + "/Not-Copy-Copy/Images 2013-12-15 - d02c8791fa0b130c0bce2d39ee684e50f7ee7a97 - Not-Copy-Copy - Results/A) Property/2022-11-12/[()]/637869743752078399.json", + "/Not-Copy-Copy - Delta/Amazon Drive - Results/A) Property/2022-11-12/[()]/637869744751177715.json", + "/Not-Copy-Copy - Delta/Blackberry - Results/A) Property/2022-11-12/[()]/637869745134124462.json" ], "ValidImageFormatExtensions": [ ".bmp", @@ -119,8 +119,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/Date-Group/Date-Group.csproj b/Date-Group/Date-Group.csproj index 7c6f7e7..15f10ef 100644 --- a/Date-Group/Date-Group.csproj +++ b/Date-Group/Date-Group.csproj @@ -5,7 +5,7 @@ enable Exe win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Date.Group @@ -34,23 +34,19 @@ - - - - - - - - - + + + + + + + - - - - - - - + + + + + diff --git a/Date-Group/DateGroup.cs b/Date-Group/DateGroup.cs index 3c1adc8..be7ef19 100644 --- a/Date-Group/DateGroup.cs +++ b/Date-Group/DateGroup.cs @@ -37,15 +37,11 @@ public class DateGroup _FilePropertiesKeyValuePairs = new Dictionary>>(); Property.Models.Configuration propertyConfiguration = Property.Models.Binder.Configuration.Get(isEnvironment, configurationRoot); Property.Models.Configuration.Verify(propertyConfiguration, requireExist: true); - Models.Configuration configuration = Models.Stateless.Configuration.Get(isEnvironment, configurationRoot, workingDirectory, propertyConfiguration); + Models.Configuration configuration = Models.Binder.Configuration.Get(isEnvironment, configurationRoot, propertyConfiguration); Verify(configuration); bool reverse = false; _Configuration = configuration; string outputExtension = ".jpg"; - if (configuration.ByHash is null) - throw new NullReferenceException(nameof(configuration.ByHash)); - if (configuration.ByCreateDateShortcut is null) - throw new NullReferenceException(nameof(configuration.ByCreateDateShortcut)); if (!_IsEnvironment.Development) throw new Exception("This program only allows development environments!"); long ticks = DateTime.Now.Ticks; @@ -59,10 +55,70 @@ public class DateGroup _ = Shared.Models.Stateless.Methods.IPath.DeleteEmptyDirectories(propertyConfiguration.RootDirectory); if (true || appSettings.MaxDegreeOfParallelism < 2) ticks = LogDelta(ticks, nameof(Shared.Models.Stateless.Methods.IPath.DeleteEmptyDirectories)); + string destinationRoot = Property.Models.Stateless.IResult.GetResultsGroupDirectory(propertyConfiguration, "Z) Moved"); + // string[] moveBackFileNames = Directory.GetFiles(destinationRoot, "*", SearchOption.AllDirectories); + // if (moveBackFileNames is not null) + // { + // string checkFile; + // string? directory; + // bool check = false; + // string directoryName; + // string checkDirectory; + // string moveBackFileNameWithExtension; + // foreach (string moveBackFileName in moveBackFileNames) + // { + // moveBackFileNameWithExtension = Path.GetFileName(moveBackFileName); + // foreach ((int g, string sourceDirectory, string[] sourceDirectoryFiles) in jsonCollection) + // { + // foreach (string sourceDirectoryFile in sourceDirectoryFiles) + // { + // check = false; + // if (!sourceDirectoryFile.Contains(moveBackFileNameWithExtension)) + // continue; + // directory = Path.GetDirectoryName(sourceDirectoryFile); + // if (directory is null) + // continue; + // directoryName = Path.GetFileName(directory); + // checkDirectory = Path.Combine(configuration.RootDirectory, directoryName); + // if (!Directory.Exists(checkDirectory)) + // continue; + // checkFile = Path.Combine(checkDirectory, moveBackFileNameWithExtension); + // if (File.Exists(checkFile)) + // continue; + // File.Move(moveBackFileName, checkFile); + // check = true; + // break; + // } + // if (check) + // break; + // } + // if (!check) + // continue; + // } + // // string destinationRoot = Property.Models.Stateless.IResult.GetResultsGroupDirectory(propertyConfiguration, "Z) Moved"); + // // for (int i = 1; i < 10; i++) + // // _ = Shared.Models.Stateless.Methods.IPath.DeleteEmptyDirectories(destinationRoot); + // } + // string[] moveBackFileNames = Directory.GetFiles(aPropertySingletonDirectory, "*.jpg", SearchOption.AllDirectories); + // foreach (string moveBackFileName in moveBackFileNames) + // { + // string? directory = Path.GetDirectoryName(moveBackFileName); + // if (directory is null) + // continue; + // string directoryName = Path.GetFileName(directory); + // string moveBackFileNameWithExtension = Path.GetFileName(moveBackFileName); + // string checkDirectory = Path.Combine(configuration.RootDirectory, directoryName); + // if (!Directory.Exists(checkDirectory)) + // continue; + // string checkFile = Path.Combine(checkDirectory, moveBackFileNameWithExtension); + // if (File.Exists(checkFile)) + // continue; + // File.Move(moveBackFileName, checkFile); + // } (int j, int f, int t, Container[] containers) = Property.Models.Stateless.Container.GetContainers(propertyConfiguration, propertyLogic); if (propertyLogic.ExceptionsDirectories.Any()) throw new Exception(); - if (propertyConfiguration.PopulatePropertyId && (configuration.ByCreateDateShortcut.Value || configuration.ByHash.Value) && Shared.Models.Stateless.Methods.IProperty.Any(containers)) + if (propertyConfiguration.PopulatePropertyId && (configuration.ByCreateDateShortcut || configuration.ByHash) && Shared.Models.Stateless.Methods.IProperty.Any(containers)) { propertyLogic.SavePropertyParallelWork(ticks, containers); if (appSettings.MaxDegreeOfParallelism < 2) @@ -70,35 +126,34 @@ public class DateGroup if (propertyLogic.ExceptionsDirectories.Any()) throw new Exception(); } - if (configuration.ByCreateDateShortcut.HasValue && configuration.ByCreateDateShortcut.Value) + if (configuration.ByCreateDateShortcut) CreateDateShortcut(propertyConfiguration, containers); else - MoveFiles(propertyConfiguration, containers); + MoveFiles(propertyConfiguration, destinationRoot, containers); } private static void Verify(Models.Configuration configuration) { - if (configuration.ByCreateDateShortcut is null) - throw new NullReferenceException(nameof(configuration.ByCreateDateShortcut)); - if (configuration.ByDay is null) - throw new NullReferenceException(nameof(configuration.ByDay)); - if (configuration.ByHash is null) - throw new NullReferenceException(nameof(configuration.ByHash)); - if (configuration.BySeason is null) - throw new NullReferenceException(nameof(configuration.BySeason)); - if (configuration.ByWeek is null) - throw new NullReferenceException(nameof(configuration.ByWeek)); - if (!configuration.ByCreateDateShortcut.Value && !configuration.ByDay.Value && !configuration.ByWeek.Value && !configuration.BySeason.Value && !configuration.ByHash.Value) + int check = 0; + if (configuration.ByCreateDateShortcut) + check += 1; + if (configuration.ByDay) + check += 1; + if (configuration.ByHash) + check += 1; + if (configuration.ByNone) + check += 1; + if (configuration.BySeason) + check += 1; + if (configuration.ByWeek) + check += 1; + if (check != 1) throw new Exception("Change configuration!"); - if (configuration.KeepFullPath is null) - throw new NullReferenceException(nameof(configuration.KeepFullPath)); if (configuration?.PropertyConfiguration?.PopulatePropertyId is null) throw new NullReferenceException(nameof(configuration.PropertyConfiguration.PopulatePropertyId)); - if (configuration.PropertyConfiguration.PopulatePropertyId && !configuration.ByCreateDateShortcut.Value && !configuration.ByHash.Value) + if (configuration.PropertyConfiguration.PopulatePropertyId && !configuration.ByCreateDateShortcut && !configuration.ByHash) throw new Exception("Change configuration!"); - if (!configuration.PropertyConfiguration.PopulatePropertyId && configuration.ByHash.Value) - throw new Exception("Change configuration!"); - if (configuration.ByCreateDateShortcut.Value && configuration.ByDay.Value && configuration.ByWeek.Value && configuration.BySeason.Value && configuration.ByHash.Value) + if (!configuration.PropertyConfiguration.PopulatePropertyId && configuration.ByHash) throw new Exception("Change configuration!"); } @@ -148,18 +203,6 @@ public class DateGroup private List<(Item Item, long LastWriteTimeTicks, long MinimumDateTimeTicks, string[] Destination)> GetMoveFileCollection(string destinationDirectory, string topDirectory, Item[] filteredItems) { List<(Item Item, long LastWriteTimeTicks, long MinimumDateTimeTicks, string[] Destination)> results = new(); - if (_Configuration.ByCreateDateShortcut is null) - throw new NullReferenceException(nameof(_Configuration.ByCreateDateShortcut)); - if (_Configuration.ByDay is null) - throw new NullReferenceException(nameof(_Configuration.ByDay)); - if (_Configuration.ByHash is null) - throw new NullReferenceException(nameof(_Configuration.ByHash)); - if (_Configuration.BySeason is null) - throw new NullReferenceException(nameof(_Configuration.BySeason)); - if (_Configuration.ByWeek is null) - throw new NullReferenceException(nameof(_Configuration.ByWeek)); - if (_Configuration.KeepFullPath is null) - throw new NullReferenceException(nameof(_Configuration.KeepFullPath)); char flag; string day; int season; @@ -213,11 +256,10 @@ public class DateGroup if (matches is not null && matches.Any()) break; } - if (matches is null) - matches = Array.Empty(); + matches ??= Array.Empty(); foreach (Item item in filteredItems) { - if (item.ImageFileHolder is null || item.Property is null || (_Configuration.PropertyConfiguration.PopulatePropertyId && item.Property.Id is null)) + if (item.Property is null || (_Configuration.PropertyConfiguration.PopulatePropertyId && item.Property.Id is null)) continue; directoryNames.Clear(); destinationCollection = new(); @@ -261,20 +303,23 @@ public class DateGroup } topDirectoryName = Path.GetFileName(topDirectory); weekOfYear = calendar.GetWeekOfYear(minimumDateTime.Value, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00"); - if (_Configuration.ByHash.Value) + if (_Configuration.ByNone) + directoryNames.Clear(); + else if (_Configuration.ByHash) directoryNames.Add($"{year} {seasonName}"); - else if (_Configuration.BySeason.Value && topDirectoryName.Length == 1 && topDirectoryName[0] == '_') + else if (_Configuration.BySeason && topDirectoryName.Length == 1 && topDirectoryName[0] == '_') directoryNames.Add($"{year} {seasonName}"); else { - if (!_Configuration.KeepFullPath.Value) + if (!_Configuration.KeepFullPath) { - _ = destinationDirectoryName.Append(topDirectoryName); - if (_Configuration.BySeason.Value) + if (topDirectoryName.Length > 1) + _ = destinationDirectoryName.Append(topDirectoryName); + if (_Configuration.BySeason) directoryNames.AddRange(new string[] { $"{destinationDirectoryName} {year} {seasonName}" }); - else if (_Configuration.ByDay.Value) + else if (_Configuration.ByDay) directoryNames.AddRange(new string[] { $"{destinationDirectoryName} {year}", $"{weekOfYear}) {year}-{day}" }); - else if (_Configuration.ByWeek.Value) + else if (_Configuration.ByWeek) directoryNames.AddRange(new string[] { $"{destinationDirectoryName} {year}", $"{weekOfYear}) {year} {month}" }); else throw new Exception(); @@ -288,17 +333,17 @@ public class DateGroup else _ = destinationDirectoryName.Append(sourceDirectoryNameSegment); } - if (_Configuration.BySeason.Value) + if (_Configuration.BySeason) directoryNames.Add($"{year} {seasonName}"); - else if (_Configuration.ByDay.Value) + else if (_Configuration.ByDay) directoryNames.Add($"{weekOfYear}) {year} {day}"); - else if (_Configuration.ByWeek.Value) + else if (_Configuration.ByWeek) directoryNames.Add($"{weekOfYear}) {month} {year}"); else throw new Exception(); } } - if (!_Configuration.ByHash.Value || item.Property.Id is null) + if (!_Configuration.ByHash || item.Property.Id is null) fileName = item.ImageFileHolder.Name; else fileName = $"{item.Property.Id.Value}{item.ImageFileHolder.ExtensionLowered}"; @@ -325,18 +370,15 @@ public class DateGroup foreach (Item item in container.Items) { if (item.ImageFileHolder is not null - && (item.Abandoned is null || !item.Abandoned.Value) - && item.ValidImageFormatExtension) + && (item.Abandoned is null || !item.Abandoned.Value)) results.Add(item); } return results.ToArray(); } - private (Item Item, long LastWriteTimeTicks, long MinimumDateTimeTicks, string[] Destination)[] GetFileMoveCollectionAll(Property.Models.Configuration configuration, Container[] containers, string destinationRoot) + private (Item Item, long LastWriteTimeTicks, long MinimumDateTimeTicks, string[] Destination)[] GetFileMoveCollectionAll(Property.Models.Configuration configuration, string destinationRoot, Container[] containers) { (Item Item, long LastWriteTimeTicks, long MinimumDateTimeTicks, string[] Destination)[] results; - if (_Configuration.KeepFullPath is null) - throw new NullReferenceException(nameof(_Configuration.KeepFullPath)); string? topDirectory; string? checkDirectory; string destinationDirectory; @@ -347,7 +389,7 @@ public class DateGroup { if (!container.Items.Any()) continue; - if (!_Configuration.KeepFullPath.Value) + if (!_Configuration.KeepFullPath) destinationDirectory = destinationRoot; else destinationDirectory = string.Concat(destinationRoot, container.SourceDirectory[configuration.RootDirectory.Length..]); @@ -373,12 +415,10 @@ public class DateGroup return results; } - private void MoveFiles(Property.Models.Configuration configuration, Container[] containers) + private void MoveFiles(Property.Models.Configuration configuration, string destinationRoot, Container[] containers) { if (_Log is null) throw new NullReferenceException(nameof(_Log)); - if (_Configuration.ByHash is null) - throw new NullReferenceException(nameof(_Configuration.ByHash)); bool hasDuplicate; string fullFileName; string directoryName; @@ -387,12 +427,9 @@ public class DateGroup List filesDistinct = new(); List filesDuplicate = new(); List directoriesDistinct = new(); - string destinationRoot = Property.Models.Stateless.IResult.GetResultsGroupDirectory(configuration, "Z) Moved"); - (Item Item, long LastWriteTimeTicks, long MinimumDateTimeTicks, string[] Destination)[] fileMoveCollectionAll = GetFileMoveCollectionAll(configuration, containers, destinationRoot); + (Item Item, long LastWriteTimeTicks, long MinimumDateTimeTicks, string[] Destination)[] fileMoveCollectionAll = GetFileMoveCollectionAll(configuration, destinationRoot, containers); foreach ((Item item, long lastWriteTimeTicks, long minimumDateTimeTicks, string[] destination) in fileMoveCollectionAll) { - if (item.ImageFileHolder is null) - continue; fullFileName = Path.Combine(destination); if (filesDistinct.Contains(fullFileName)) filesDuplicate.Add(fullFileName); @@ -403,13 +440,10 @@ public class DateGroup directoriesDistinct.Add(directoryName); if (!Directory.Exists(directoryName)) _ = Directory.CreateDirectory(directoryName); - if (_Configuration.ByHash.Value) - { - if (!Directory.Exists(string.Concat(directoryName, duplicate, " I"))) - _ = Directory.CreateDirectory(string.Concat(directoryName, duplicate, " I")); - if (!Directory.Exists(string.Concat(directoryName, duplicate, " II"))) - _ = Directory.CreateDirectory(string.Concat(directoryName, duplicate, " II")); - } + if (!Directory.Exists(string.Concat(directoryName, duplicate, " I"))) + _ = Directory.CreateDirectory(string.Concat(directoryName, duplicate, " I")); + if (!Directory.Exists(string.Concat(directoryName, duplicate, " II"))) + _ = Directory.CreateDirectory(string.Concat(directoryName, duplicate, " II")); } _Log.Information("Ready to move files?"); for (int y = 0; y < int.MaxValue; y++) @@ -422,8 +456,6 @@ public class DateGroup int moved = 0; foreach ((Item item, long lastWriteTimeTicks, long minimumDateTimeTicks, string[] destination) in fileMoveCollectionAll) { - if (item.ImageFileHolder is null) - continue; fullFileName = Path.Combine(destination); hasDuplicate = filesDuplicate.Contains(fullFileName); if (hasDuplicate) @@ -431,10 +463,10 @@ public class DateGroup destination[1] = string.Concat(destination[1], duplicate, " I"); fullFileName = Path.Combine(destination); } - if (File.Exists(fullFileName)) + for (int i = 0; i < 256 - destination[1].Length; i++) { - if (!_Configuration.ByHash.Value) - continue; + if (!File.Exists(fullFileName)) + break; else { destination[1] = string.Concat(destination[1], "I"); @@ -456,8 +488,7 @@ public class DateGroup catch (Exception) { } } } - if (_Configuration.ByHash.Value) - _ = Shared.Models.Stateless.Methods.IPath.DeleteEmptyDirectories(destinationRoot); + _ = Shared.Models.Stateless.Methods.IPath.DeleteEmptyDirectories(destinationRoot); _Log.Information($"{moved} file(s) moved"); for (int y = 0; y < int.MaxValue; y++) { @@ -468,8 +499,6 @@ public class DateGroup _Log.Information(". . ."); foreach ((Item item, long lastWriteTimeTicks, long minimumDateTimeTicks, string[] destination) in fileMoveCollectionAll) { - if (item.ImageFileHolder is null) - continue; fullFileName = Path.Combine(destination); if (File.Exists(item.ImageFileHolder.FullName)) continue; diff --git a/Date-Group/Models/Binder/AppSettings.cs b/Date-Group/Models/Binder/AppSettings.cs index ec9380a..50825ef 100644 --- a/Date-Group/Models/Binder/AppSettings.cs +++ b/Date-Group/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/Date-Group/Models/Binder/Configuration.cs b/Date-Group/Models/Binder/Configuration.cs index 6a49f15..2bf92f8 100644 --- a/Date-Group/Models/Binder/Configuration.cs +++ b/Date-Group/Models/Binder/Configuration.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.Configuration; +using Phares.Shared; using System.ComponentModel.DataAnnotations; using System.Text.Json; @@ -11,6 +13,7 @@ public class Configuration [Display(Name = "By Create Date Shortcut"), Required] public bool? ByCreateDateShortcut { get; set; } [Display(Name = "By Date"), Required] public bool? ByDay { get; set; } [Display(Name = "By Hash"), Required] public bool? ByHash { get; set; } + [Display(Name = "By None"), Required] public bool? ByNone { get; set; } [Display(Name = "By Season"), Required] public bool? BySeason { get; set; } [Display(Name = "By Week"), Required] public bool? ByWeek { get; set; } [Display(Name = "Ignore Subdirectories for Rename"), Required] public bool? KeepFullPath { get; set; } @@ -24,4 +27,47 @@ public class Configuration return result; } + private static Models.Configuration Get(Configuration? configuration) + { + Models.Configuration result; + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); + if (configuration.ByCreateDateShortcut is null) + throw new NullReferenceException(nameof(configuration.ByCreateDateShortcut)); + if (configuration.ByDay is null) + throw new NullReferenceException(nameof(configuration.ByDay)); + if (configuration.ByHash is null) + throw new NullReferenceException(nameof(configuration.ByHash)); + if (configuration.ByNone is null) + throw new NullReferenceException(nameof(configuration.ByNone)); + if (configuration.BySeason is null) + throw new NullReferenceException(nameof(configuration.BySeason)); + if (configuration.ByWeek is null) + throw new NullReferenceException(nameof(configuration.ByWeek)); + if (configuration.KeepFullPath is null) + throw new NullReferenceException(nameof(configuration.KeepFullPath)); + result = new(configuration.PropertyConfiguration, configuration.ByCreateDateShortcut.Value, configuration.ByDay.Value, configuration.ByHash.Value, configuration.ByNone.Value, configuration.BySeason.Value, configuration.ByWeek.Value, configuration.KeepFullPath.Value); + 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(); + else + { + string environmentName = IsEnvironment.GetEnvironmentName(isEnvironment); + string section = string.Concat(environmentName, ":", nameof(Configuration)); + IConfigurationSection configurationSection = configurationRoot.GetSection(section); + configuration = configurationSection.Get(); + } + result = Get(configuration); + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); + result.SetAndUpdate(propertyConfiguration, numberOfJitters: null, numberOfTimesToUpsample: null, modelName: null, predictorModelName: null); + return result; + } + } \ No newline at end of file diff --git a/Date-Group/Models/Configuration.cs b/Date-Group/Models/Configuration.cs index b164f13..994da49 100644 --- a/Date-Group/Models/Configuration.cs +++ b/Date-Group/Models/Configuration.cs @@ -6,30 +6,27 @@ namespace View_by_Distance.Date.Group.Models; public class Configuration { - protected readonly bool? _ByCreateDateShortcut; - protected readonly bool? _ByDay; - protected readonly bool? _ByHash; - protected readonly bool? _BySeason; - protected readonly bool? _ByWeek; - protected readonly bool? _KeepFullPath; protected Property.Models.Configuration _PropertyConfiguration; - public bool? ByCreateDateShortcut => _ByCreateDateShortcut; - public bool? ByDay => _ByDay; - public bool? ByHash => _ByHash; - public bool? BySeason => _BySeason; - public bool? ByWeek => _ByWeek; - public bool? KeepFullPath => _KeepFullPath; public Property.Models.Configuration PropertyConfiguration => _PropertyConfiguration; + public bool ByCreateDateShortcut { init; get; } + public bool ByDay { init; get; } + public bool ByHash { init; get; } + public bool ByNone { init; get; } + public bool BySeason { init; get; } + public bool ByWeek { init; get; } + public bool KeepFullPath { init; get; } + [JsonConstructor] - public Configuration(bool? byCreateDateShortcut, bool? byDay, bool? byHash, bool? bySeason, bool? byWeek, bool? keepFullPath, Property.Models.Configuration propertyConfiguration) + public Configuration(Property.Models.Configuration propertyConfiguration, bool byCreateDateShortcut, bool byDay, bool byHash, bool byNone, bool bySeason, bool byWeek, bool keepFullPath) { - _ByCreateDateShortcut = byCreateDateShortcut; - _ByDay = byDay; - _ByHash = byHash; - _BySeason = bySeason; - _ByWeek = byWeek; - _KeepFullPath = keepFullPath; + ByDay = byDay; + ByHash = byHash; + ByNone = byNone; + ByWeek = byWeek; + BySeason = bySeason; + KeepFullPath = keepFullPath; + ByCreateDateShortcut = byCreateDateShortcut; _PropertyConfiguration = propertyConfiguration; } diff --git a/Date-Group/Models/Stateless/Configuration.cs b/Date-Group/Models/Stateless/Configuration.cs deleted file mode 100644 index 1262308..0000000 --- a/Date-Group/Models/Stateless/Configuration.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Phares.Shared; -using System.Text.Json; - -namespace View_by_Distance.Date.Group.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(); - string json = JsonSerializer.Serialize(configuration, new JsonSerializerOptions() { WriteIndented = true }); - result = JsonSerializer.Deserialize(json); - if (result is null) - throw new Exception(json); - string jsonThis = result.ToString(); - result.SetAndUpdate(propertyConfiguration, null, null, null, null); - 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; - } - -} \ No newline at end of file diff --git a/Date-Group/appsettings.Development.json b/Date-Group/appsettings.Development.json index ec359c6..71babed 100644 --- a/Date-Group/appsettings.Development.json +++ b/Date-Group/appsettings.Development.json @@ -50,20 +50,29 @@ "WorkingDirectoryName": "PharesApps", "Windows": { "Configuration": { - "ByCreateDateShortcut": true, + "ByCreateDateShortcut": false, "ByDay": false, "ByHash": false, - "BySeason": false, + "ByNone": false, + "BySeason": true, "ByWeek": false, - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "FileNameDirectorySeparator": ".Z.", "ForcePropertyLastWriteTimeToCreationTime": false, "KeepFullPath": false, "MaxImagesInDirectoryForTopLevelFirstPass": 10, "Pattern": "[^ABCDEFGHIJKLMNOPQRSTUVWXYZbcdfghjklmnpqrstvwxyz0-9]", - "PopulatePropertyId": true, + "PopulatePropertyId": false, "PropertiesChangedForProperty": false, - "RootDirectory": "C:/Tmp/Phares/Compare/Images 2022-10-23 - 239acf2 - III", + "ResultAllInOne": "_ _ _", + "ResultCollection": "[]", + "ResultContent": "()", + "ResultSingleton": "{}", + "xRootDirectory": "C:/Tmp/phares/Pictures", + "xxRootDirectory": "C:/Tmp/Phares/Compare/Images 2022-11-12 - c6aa7e8 - III", + "xxxRootDirectory": "F:/Tmp/Phares/Compare/Images 2022-11-12 - c6aa7e8 - III", + "xxxxRootDirectory": "F:/Tmp/Phares/2022-11-03-DCIM/DCIM/100D3400 2022", + "RootDirectory": "F:/Tmp/Phares/Compare/Images 2022-11-12 - c6aa7e8 - III/D", "WriteBitmapDataBytes": false, "IgnoreExtensions": [ ".gif", @@ -87,8 +96,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/Distance/Distance.csproj b/Distance/Distance.csproj index 4397f8b..94917fd 100644 --- a/Distance/Distance.csproj +++ b/Distance/Distance.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Distance @@ -34,14 +34,12 @@ - - - - - - - - + + + + + + diff --git a/Distance/Models/MapLogicSupport.cs b/Distance/Models/MapLogicSupport.cs index f14ea05..f64a915 100644 --- a/Distance/Models/MapLogicSupport.cs +++ b/Distance/Models/MapLogicSupport.cs @@ -4,6 +4,7 @@ using View_by_Distance.FaceRecognitionDotNet; using View_by_Distance.Map.Models; using View_by_Distance.Shared.Models; using View_by_Distance.Shared.Models.Properties; +using WindowsShortcutFactory; namespace View_by_Distance.Distance.Models; @@ -354,4 +355,55 @@ public class MapLogicSupport : Shared.Models.Methods.IMapLogicSupport return result; } + private static bool TryToFind(string a2PeopleSingletonDirectory, string file, string path) + { + bool result = false; + string? pathName = Path.GetFileName(path); + string? group = Path.GetDirectoryName(path); + string? groupName = Path.GetFileName(group); + if (pathName is not null && group is not null && groupName is not null) + { + WindowsShortcut windowsShortcut; + string checkDirectory = Path.Combine(a2PeopleSingletonDirectory, groupName, pathName); + if (Directory.Exists(checkDirectory)) + { + try + { + windowsShortcut = new() { Path = checkDirectory }; + windowsShortcut.Save(file); + windowsShortcut.Dispose(); + result = true; + } + catch (Exception) + { } + } + } + return result; + } + + public static void BeforeSaveResizedImagesByPersonKeyFormatted(string[] jLinks, string a2PeopleSingletonDirectory) + { + string[] files; + string checkDirectory; + WindowsShortcut windowsShortcut; + foreach (string directoryName in jLinks) + { + checkDirectory = Path.Combine(a2PeopleSingletonDirectory, directoryName); + if (!Directory.Exists(checkDirectory)) + continue; + files = Directory.GetFiles(checkDirectory, "*.lnk", SearchOption.TopDirectoryOnly); + foreach (string file in files) + { + windowsShortcut = WindowsShortcut.Load(file); + if (windowsShortcut.Path is null) + continue; + if (!Directory.Exists(windowsShortcut.Path)) + { + if (!TryToFind(a2PeopleSingletonDirectory, file, windowsShortcut.Path)) + continue; + } + } + } + } + } \ No newline at end of file diff --git a/Drag-Drop/Drag-Drop.csproj b/Drag-Drop/Drag-Drop.csproj index 27fe8c0..8027297 100644 --- a/Drag-Drop/Drag-Drop.csproj +++ b/Drag-Drop/Drag-Drop.csproj @@ -1,11 +1,11 @@ - + enable 10.0 enable WinExe win-x64 - net6.0-windows + net7.0-windows true @@ -26,14 +26,16 @@ - - - - - - + + + + + + + + - + diff --git a/Drag-Drop/Form.cs b/Drag-Drop/Form.cs index ccba340..2472a75 100644 --- a/Drag-Drop/Form.cs +++ b/Drag-Drop/Form.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Configuration; +using Microsoft.WindowsAPICodePack.Shell; using Phares.Shared; using Serilog; using System.Diagnostics; @@ -15,7 +16,9 @@ public partial class Form : System.Windows.Forms.Form private readonly ILogger _Logger; private readonly TextBox _TextBox; + private readonly List _Lines; private readonly AppSettings _AppSettings; + private readonly ProgressBar _ProgressBar; private readonly string _WorkingDirectory; private readonly Configuration _Configuration; private readonly IsEnvironment _IsEnvironment; @@ -27,6 +30,7 @@ public partial class Form : System.Windows.Forms.Form public Form() { InitializeComponent(); + _Lines = new(); ILogger logger; AppSettings appSettings; string workingDirectory; @@ -62,7 +66,9 @@ public partial class Form : System.Windows.Forms.Form _PropertyConfiguration = propertyConfiguration; _ResizeFileNameExtension = resizeFileNameExtension; _TextBox = new() { Location = new(5, 5), Dock = DockStyle.Top }; + _ProgressBar = new() { Location = new(5, 5), Dock = DockStyle.Top, Visible = false }; Load += new EventHandler(Form1_Load); + Controls.Add(_ProgressBar); Controls.Add(_TextBox); } @@ -70,30 +76,23 @@ public partial class Form : System.Windows.Forms.Form { try { - int j; - int f; - int t; AllowDrop = true; - Container[] containers; DragDrop += new DragEventHandler(Form1_DragDrop); DragEnter += new DragEventHandler(Form1_DragEnter); - Property.Models.A_Property propertyLogic = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, _ResizeFileNameExtension, _Configuration.Reverse); - (j, f, t, containers) = Property.Models.Stateless.Container.GetContainers(_Configuration.PropertyConfiguration, propertyLogic); - List collection = Program.GetMappingFromItemCollection(_Configuration, containers); - foreach (MappingFromItem mappingFromItem in collection) - { - if (_IdToMappingFromItem.ContainsKey(mappingFromItem.Id)) - continue; - _IdToMappingFromItem.Add(mappingFromItem.Id, mappingFromItem); - } - if (_Logger is null) - throw new NullReferenceException(nameof(_Logger)); - _Logger.Debug((_AppSettings is null).ToString()); - _Logger.Debug((_Configuration is null).ToString()); - _Logger.Debug((_IsEnvironment is null).ToString()); - _Logger.Debug((_WorkingDirectory is null).ToString()); - _Logger.Debug((_ConfigurationRoot is null).ToString()); - _Logger.Debug((_PropertyConfiguration is null).ToString()); + _TextBox.LostFocus += new EventHandler(TextBox_LostFocus); + } + catch (Exception) + { + throw; + } + } + + void TextBox_LostFocus(object? sender, EventArgs e) + { + try + { + if (_TextBox.Text == "ps") + throw new NotImplementedException(); } catch (Exception) { @@ -114,29 +113,166 @@ public partial class Form : System.Windows.Forms.Form } } + void LoadData() + { + Container[] containers; + Property.Models.A_Property propertyLogic = new(_AppSettings.MaxDegreeOfParallelism, _Configuration.PropertyConfiguration, _ResizeFileNameExtension, _Configuration.Reverse); + (_, _, _, containers) = Property.Models.Stateless.Container.GetContainers(_Configuration.PropertyConfiguration, propertyLogic); + List collection = Program.GetMappingFromItemCollection(_Configuration, containers); + foreach (MappingFromItem mappingFromItem in collection) + { + if (_IdToMappingFromItem.ContainsKey(mappingFromItem.Id)) + continue; + _IdToMappingFromItem.Add(mappingFromItem.Id, mappingFromItem); + } + if (_Logger is null) + throw new NullReferenceException(nameof(_Logger)); + _Logger.Debug((_AppSettings is null).ToString()); + _Logger.Debug((_Configuration is null).ToString()); + _Logger.Debug((_IsEnvironment is null).ToString()); + _Logger.Debug((_WorkingDirectory is null).ToString()); + _Logger.Debug((_ConfigurationRoot is null).ToString()); + _Logger.Debug((_PropertyConfiguration is null).ToString()); + } + + private void RenameDirectory(string path, string searchPattern) + { + string[] directories = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly); + foreach (string directory in directories) + RenameDirectory(directory, searchPattern); + int? id; + string? message; + string checkFile; + DateTime? dateTime; + FileHolder fileHolder; + _ProgressBar.Step = 1; + bool isIgnoreExtension; + _ProgressBar.Value = 0; + DateTime? minimumDateTime; + _ProgressBar.Visible = true; + bool isValidImageFormatExtension; + string? extraLargeBitmapThumbnail; + string[] files = Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); + _ProgressBar.Maximum = files.Length; + foreach (string file in files) + { + fileHolder = new(file); + _Lines.Add(fileHolder.NameWithoutExtension); + isValidImageFormatExtension = _Configuration.PropertyConfiguration.ValidImageFormatExtensions.Contains(fileHolder.ExtensionLowered); + isIgnoreExtension = isValidImageFormatExtension && _Configuration.IgnoreExtensions.Contains(fileHolder.ExtensionLowered); + if (fileHolder.CreationTime is null || fileHolder.Name.Contains(fileHolder.CreationTime.Value.ToString("yy"))) + continue; + if (fileHolder.LastWriteTime is null || fileHolder.Name.Contains(fileHolder.LastWriteTime.Value.ToString("yy"))) + continue; + if (fileHolder.NameWithoutExtension.Length == 1 || fileHolder.NameWithoutExtension[1..].All(l => char.IsNumber(l))) + continue; + if (fileHolder.NameWithoutExtension.Length == 1 || fileHolder.NameWithoutExtension[1..].All(l => char.IsNumber(l))) + continue; + if (!isIgnoreExtension && isValidImageFormatExtension) + extraLargeBitmapThumbnail = null; + else + { + extraLargeBitmapThumbnail = SaveExtraLargeBitmapThumbnail(fileHolder); + if (extraLargeBitmapThumbnail is null) + continue; + fileHolder = new(extraLargeBitmapThumbnail); + isValidImageFormatExtension = _Configuration.PropertyConfiguration.ValidImageFormatExtensions.Contains(fileHolder.ExtensionLowered); + isIgnoreExtension = isValidImageFormatExtension && _Configuration.IgnoreExtensions.Contains(fileHolder.ExtensionLowered); + if (isIgnoreExtension || !isValidImageFormatExtension) + continue; + } + if (fileHolder.DirectoryName is null) + continue; + dateTime = IProperty.GetDateTimeFromName(fileHolder); + if (dateTime is not null && fileHolder.Name.Contains(dateTime.Value.ToString("yy"))) + continue; + (minimumDateTime, id, message) = IProperty.Get(fileHolder); + if (id is null) + continue; + if (minimumDateTime is not null && fileHolder.Name.Contains(minimumDateTime.Value.ToString("yy"))) + continue; + if (dateTime is not null && minimumDateTime is not null && minimumDateTime.Value != dateTime.Value) + continue; + if (extraLargeBitmapThumbnail is not null) + { + File.Delete(fileHolder.FullName); + fileHolder = new(file); + if (fileHolder.DirectoryName is null) + continue; + } + checkFile = Path.Combine(fileHolder.DirectoryName, $"{id}{fileHolder.ExtensionLowered}"); + if (File.Exists(checkFile)) + continue; + File.Move(fileHolder.FullName, checkFile); + _ProgressBar.PerformStep(); + } + _ProgressBar.Visible = false; + } + + private string? SaveExtraLargeBitmapThumbnail(FileHolder fileHolder) + { + string? result; + ShellFile shellFile = ShellFile.FromFilePath(fileHolder.FullName); + if (shellFile is null || shellFile.Thumbnail is null || shellFile.Thumbnail.ExtraLargeBitmap.Clone() is not Bitmap bitmap || bitmap.Width == 0) + result = null; + else + { + result = $"{fileHolder.FullName}{_ResizeFileNameExtension}"; + bitmap.Save(result); + bitmap.Dispose(); + shellFile.Dispose(); + } + return result; + } + void Form1_DragDrop(object? sender, DragEventArgs e) { try { - if (e.Data is not null) + if (e.Data is null) + _TextBox.Text = string.Empty; + else { - string fileName; + string name; string[] segments; - string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); - foreach (string file in files) + for (int i = 1; i < 3; i++) { - fileName = Path.GetFileNameWithoutExtension(file); - Text = fileName; - segments = fileName.Split('.'); - if (int.TryParse(segments[0], out int id) && _IdToMappingFromItem.ContainsKey(id)) + if (e.Data.GetData(DataFormats.FileDrop) is not string[] paths) + continue; + foreach (string path in paths) { - MappingFromItem mappingFromItem = _IdToMappingFromItem[id]; - Text = mappingFromItem.ImageFileHolder.Name; - _TextBox.Text = mappingFromItem.ImageFileHolder.FullName; - _Logger.Information(mappingFromItem.ImageFileHolder.DirectoryName); - if (!string.IsNullOrEmpty(mappingFromItem.ImageFileHolder.DirectoryName)) - _ = Process.Start("explorer.exe", string.Concat("\"", mappingFromItem.ImageFileHolder.DirectoryName, "\"")); + name = Path.GetFileNameWithoutExtension(path); + Text = name; + segments = name.Split('.'); + if (Directory.Exists(path)) + { + if (i == 1) + RenameDirectory(path, "*Rename*"); + else if (i == 2) + RenameDirectory(path, "*"); + else + continue; + } + else + { + if (i != 1) + continue; + if (!_IdToMappingFromItem.Any()) + LoadData(); + if (int.TryParse(segments[0], out int id) && _IdToMappingFromItem.TryGetValue(id, out MappingFromItem? value)) + { + MappingFromItem mappingFromItem = value; + Text = mappingFromItem.ImageFileHolder.Name; + _TextBox.Text = mappingFromItem.ImageFileHolder.FullName; + if (mappingFromItem.ImageFileHolder.DirectoryName is not null) + _Logger.Information(mappingFromItem.ImageFileHolder.DirectoryName); + if (!string.IsNullOrEmpty(mappingFromItem.ImageFileHolder.DirectoryName)) + _ = Process.Start("explorer.exe", string.Concat("\"", mappingFromItem.ImageFileHolder.DirectoryName, "\"")); + } + } } + File.WriteAllLines($"D:/Tmp/Phares/{DateTime.Now.Ticks}.tsv", _Lines); + _Lines.Clear(); } } } diff --git a/Drag-Drop/Models/Binder/AppSettings.cs b/Drag-Drop/Models/Binder/AppSettings.cs index 61008e0..853d9c3 100644 --- a/Drag-Drop/Models/Binder/AppSettings.cs +++ b/Drag-Drop/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/Drag-Drop/Models/Binder/Configuration.cs b/Drag-Drop/Models/Binder/Configuration.cs index 594f779..2713d8d 100644 --- a/Drag-Drop/Models/Binder/Configuration.cs +++ b/Drag-Drop/Models/Binder/Configuration.cs @@ -60,9 +60,11 @@ public class Configuration return result; } - private static Models.Configuration Get(Configuration configuration) + private static Models.Configuration Get(Configuration? configuration) { Models.Configuration result; + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); if (configuration.CheckDFaceAndUpWriteDates is null) throw new NullReferenceException(nameof(configuration.CheckDFaceAndUpWriteDates)); if (configuration.CheckJsonForDistanceResults is null) @@ -81,10 +83,8 @@ public class Configuration throw new NullReferenceException(nameof(configuration.IgnoreExtensions)); if (configuration.IgnoreRelativePaths is null) throw new NullReferenceException(nameof(configuration.IgnoreRelativePaths)); - if (configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions = Array.Empty(); - if (configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = Array.Empty(); + configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions ??= Array.Empty(); + configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions ??= Array.Empty(); if (configuration.LoadOrCreateThenSaveIndex is null) throw new NullReferenceException(nameof(configuration.LoadOrCreateThenSaveIndex)); if (configuration.MixedYearRelativePaths is null) @@ -115,16 +115,13 @@ public class Configuration throw new NullReferenceException(nameof(configuration.PropertiesChangedForResize)); if (configuration.Reverse is null) throw new NullReferenceException(nameof(configuration.Reverse)); - if (configuration.SaveFaceLandmarkForOutputResolutions is null) - configuration.SaveFaceLandmarkForOutputResolutions = Array.Empty(); + configuration.SaveFaceLandmarkForOutputResolutions ??= Array.Empty(); if (configuration.SaveFullYearOfRandomFiles is null) throw new NullReferenceException(nameof(configuration.SaveFullYearOfRandomFiles)); - if (configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions is null) - configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions = Array.Empty(); + configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions ??= Array.Empty(); if (configuration.SaveResizedSubfiles is null) throw new NullReferenceException(nameof(configuration.SaveResizedSubfiles)); - if (configuration.SaveShortcutsForOutputResolutions is null) - configuration.SaveShortcutsForOutputResolutions = Array.Empty(); + configuration.SaveShortcutsForOutputResolutions ??= Array.Empty(); if (configuration.SkipSearch is null) throw new NullReferenceException(nameof(configuration.SkipSearch)); if (configuration.TestDistanceResults is null) @@ -178,7 +175,7 @@ public class Configuration public static Models.Configuration Get(IsEnvironment isEnvironment, IConfigurationRoot configurationRoot, Property.Models.Configuration propertyConfiguration) { Models.Configuration result; - Configuration configuration; + Configuration? configuration; if (isEnvironment is null) configuration = configurationRoot.Get(); else diff --git a/Drag-Drop/Program.cs b/Drag-Drop/Program.cs index adb1e2d..7072468 100644 --- a/Drag-Drop/Program.cs +++ b/Drag-Drop/Program.cs @@ -50,9 +50,7 @@ static class Program public static List GetMappingFromItemCollection(Models.Configuration configuration, Container[] containers) { List results = new(); - bool? isWrongYear; Item[] filteredItems; - DateTime minimumDateTime; MappingFromItem mappingFromItem; foreach (Container container in containers) { @@ -65,11 +63,9 @@ static class Program continue; foreach (Item item in filteredItems) { - if (item.Property?.Id is null || item.ImageFileHolder is null) + if (item.Property?.Id is null) continue; - minimumDateTime = IProperty.GetMinimumDateTime(item.Property); - (isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder, minimumDateTime); - mappingFromItem = new(item.Property.Id.Value, item.ImageFileHolder, isWrongYear, minimumDateTime, item.RelativePath, item.ImageFileHolder); + mappingFromItem = IMappingFromItem.GetMappingFromItem(item); results.Add(mappingFromItem); } } diff --git a/Face/Face.csproj b/Face/Face.csproj index ca67660..db03be4 100644 --- a/Face/Face.csproj +++ b/Face/Face.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Face @@ -34,10 +34,8 @@ - - - - + + diff --git a/Face/Models/_D_Face.cs b/Face/Models/_D_Face.cs index c7d92ec..9030e25 100644 --- a/Face/Models/_D_Face.cs +++ b/Face/Models/_D_Face.cs @@ -8,6 +8,7 @@ using View_by_Distance.Face.Models.Stateless; using View_by_Distance.FaceRecognitionDotNet; using View_by_Distance.Metadata.Models; using View_by_Distance.Property.Models; +using View_by_Distance.Property.Models.Stateless; using View_by_Distance.Resize.Models; using View_by_Distance.Shared.Models; using View_by_Distance.Shared.Models.Stateless; @@ -248,14 +249,14 @@ public class D_Face } } if (unknownImage is null) - results.Add(new(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, mappingFromItem.RelativePath, location: null)); + results.Add(new(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, location: null)); else { List<(Location Location, FaceRecognitionDotNet.FaceEncoding? FaceEncoding, Dictionary? FaceParts)> collection; FaceRecognition faceRecognition = new(_NumberOfTimesToUpsample, _NumberOfJitters, _PredictorModel, _Model, _ModelParameter); collection = faceRecognition.GetCollection(unknownImage, includeFaceEncoding: true, includeFaceParts: true); if (!collection.Any()) - results.Add(new(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, mappingFromItem.RelativePath, location: null)); + results.Add(new(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, location: null)); else { double[] rawEncoding; @@ -263,7 +264,7 @@ public class D_Face Shared.Models.FaceEncoding convertedFaceEncoding; foreach ((Location location, FaceRecognitionDotNet.FaceEncoding? faceEncoding, Dictionary? faceParts) in collection) { - face = new(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, mappingFromItem.RelativePath, location); + face = new(property, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation, location); if (faceEncoding is not null) { rawEncoding = faceEncoding.GetRawEncoding(); @@ -283,6 +284,34 @@ public class D_Face return results; } + public void SetAngleBracketCollection(string dResultsFullGroupDirectory, string sourceDirectory) + { + AngleBracketCollection.Clear(); + AngleBracketCollection.AddRange(IResult.GetDirectoryInfoCollection(_Configuration, + sourceDirectory, + dResultsFullGroupDirectory, + contentDescription: "n png file(s) for each face found", + singletonDescription: string.Empty, + collectionDescription: "For each image a json file with all faces found", + converted: true)); + } + + public string GetFacesDirectory(string dResultsFullGroupDirectory, Item item) + { + string result; + bool angleBracketCollectionAny = AngleBracketCollection.Any(); + if (!angleBracketCollectionAny) + { + if (item.ImageFileHolder.DirectoryName is null) + throw new NullReferenceException(nameof(item.ImageFileHolder.DirectoryName)); + SetAngleBracketCollection(dResultsFullGroupDirectory, item.ImageFileHolder.DirectoryName); + } + if (!angleBracketCollectionAny) + AngleBracketCollection.Clear(); + result = Path.Combine(AngleBracketCollection[0].Replace("<>", "()"), item.ImageFileHolder.NameWithoutExtension); + return result; + } + #pragma warning restore CA1416 public List GetFaces(string dResultsFullGroupDirectory, List> subFileTuples, List parseExceptions, Shared.Models.Property property, MappingFromItem mappingFromItem, int outputResolutionWidth, int outputResolutionHeight, int outputResolutionOrientation) @@ -293,27 +322,18 @@ public class D_Face string json; string[] changesFrom = new string[] { nameof(A_Property), nameof(B_Metadata), nameof(C_Resize) }; List dateTimes = (from l in subFileTuples where changesFrom.Contains(l.Item1) select l.Item2).ToList(); - string usingRelativePath = Path.Combine(AngleBracketCollection[0].Replace("<>", "[]"), $"{mappingFromItem.ImageFileHolder.NameWithoutExtension}.json"); string dCollectionFile = Path.Combine(dResultsFullGroupDirectory, "[]", _Configuration.ResultAllInOne, $"{mappingFromItem.Id}{mappingFromItem.ImageFileHolder.ExtensionLowered}.json"); FileInfo fileInfo = new(dCollectionFile); - if (!fileInfo.Exists) + if (!fileInfo.FullName.Contains(_Configuration.ResultAllInOne) && !fileInfo.Exists) { - if (File.Exists(usingRelativePath)) + if (fileInfo.Directory?.Parent is null) + throw new Exception(); + string parentCheck = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name); + if (File.Exists(parentCheck)) { - File.Move(usingRelativePath, fileInfo.FullName); + File.Move(parentCheck, fileInfo.FullName); fileInfo.Refresh(); } - if (!fileInfo.Exists) - { - if (fileInfo.Directory?.Parent is null) - throw new Exception(); - string parentCheck = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name); - if (File.Exists(parentCheck)) - { - File.Move(parentCheck, fileInfo.FullName); - fileInfo.Refresh(); - } - } } if (_ForceFaceLastWriteTimeToCreationTime && !fileInfo.Exists && File.Exists(Path.ChangeExtension(fileInfo.FullName, ".delete"))) { @@ -376,7 +396,7 @@ public class D_Face return results; } - public bool SaveFaces(string dResultsFullGroupDirectory, List> subFileTuples, List parseExceptions, MappingFromItem mappingFromItem, List faces) + public bool SaveFaces(string dResultsFullGroupDirectory, List> subFileTuples, List parseExceptions, MappingFromItem mappingFromItem, string facesDirectory, List faces) { FileInfo fileInfo; bool result = false; @@ -384,7 +404,6 @@ public class D_Face string deterministicHashCodeKey; List<(Shared.Models.Face, FileInfo?, string)> collection = new(); string[] changesFrom = new string[] { nameof(A_Property), nameof(B_Metadata), nameof(C_Resize) }; - string facesDirectory = Path.Combine(AngleBracketCollection[0].Replace("<>", "()"), mappingFromItem.ImageFileHolder.NameWithoutExtension); List dateTimes = (from l in subFileTuples where changesFrom.Contains(l.Item1) select l.Item2).ToList(); if (!Directory.Exists(facesDirectory)) _ = Directory.CreateDirectory(facesDirectory); @@ -397,7 +416,7 @@ public class D_Face } deterministicHashCodeKey = Shared.Models.Stateless.Methods.IMapping.GetDeterministicHashCodeKey(mappingFromItem.Id, face.Location, ILocation.Digits, ILocation.Factor, face.OutputResolution); fileInfo = new FileInfo(Path.Combine(facesDirectory, $"{deterministicHashCodeKey}{mappingFromItem.ImageFileHolder.ExtensionLowered}{_FileNameExtension}")); - if (!fileInfo.Exists) + if (!fileInfo.FullName.Contains(_Configuration.ResultAllInOne) && !fileInfo.Exists) { if (fileInfo.Directory?.Parent is null) throw new Exception(); diff --git a/FaceParts/FaceParts.csproj b/FaceParts/FaceParts.csproj index b8000a5..5b9d33f 100644 --- a/FaceParts/FaceParts.csproj +++ b/FaceParts/FaceParts.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.FaceParts @@ -34,10 +34,8 @@ - - - - + + diff --git a/FaceParts/Models/_D2_FaceParts.cs b/FaceParts/Models/_D2_FaceParts.cs index 03630af..adab701 100644 --- a/FaceParts/Models/_D2_FaceParts.cs +++ b/FaceParts/Models/_D2_FaceParts.cs @@ -129,8 +129,7 @@ public class D2_FaceParts Bitmap result; Bitmap bitmap = new(image); result = RotateBitmap(bitmap, angle); - if (bitmap is not null) - bitmap.Dispose(); + bitmap?.Dispose(); return result; } @@ -202,12 +201,8 @@ public class D2_FaceParts #pragma warning restore CA1416 - public void SaveFaceLandmarkImages(string facesDirectory, List> subFileTuples, List parseExceptions, Item item, List faceCollection, bool saveRotated) + public void SaveFaceLandmarkImages(Property.Models.Configuration configuration, string facesDirectory, List> subFileTuples, List parseExceptions, MappingFromItem mappingFromItem, List faceCollection, bool saveRotated) { - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); - if (item.ResizedFileHolder is null) - throw new NullReferenceException(nameof(item.ResizedFileHolder)); FileInfo fileInfo; bool check = false; string parentCheck; @@ -224,14 +219,14 @@ public class D2_FaceParts _ = Directory.CreateDirectory(facesDirectory); foreach (Shared.Models.Face face in faceCollection) { - if (item.Property?.Id is null || face.FaceEncoding is null || face.Location is null || face.OutputResolution is null) + if (face.FaceEncoding is null || face.Location is null || face.OutputResolution is null) { collection.Add(new(face, string.Empty, string.Empty)); continue; } - deterministicHashCodeKey = Shared.Models.Stateless.Methods.IMapping.GetDeterministicHashCodeKey(item.Property.Id.Value, face.Location, Shared.Models.Stateless.ILocation.Digits, Shared.Models.Stateless.ILocation.Factor, face.OutputResolution); - fileInfo = new FileInfo(Path.Combine(facesDirectory, $"{deterministicHashCodeKey}{item.ImageFileHolder.ExtensionLowered}{_FileNameExtension}")); - if (!fileInfo.Exists) + deterministicHashCodeKey = Shared.Models.Stateless.Methods.IMapping.GetDeterministicHashCodeKey(mappingFromItem.Id, face.Location, Shared.Models.Stateless.ILocation.Digits, Shared.Models.Stateless.ILocation.Factor, face.OutputResolution); + fileInfo = new FileInfo(Path.Combine(facesDirectory, $"{deterministicHashCodeKey}{mappingFromItem.ImageFileHolder.ExtensionLowered}{_FileNameExtension}")); + if (!fileInfo.FullName.Contains(configuration.ResultAllInOne) && !fileInfo.Exists) { if (fileInfo.Directory?.Parent is null) throw new Exception(); @@ -241,7 +236,7 @@ public class D2_FaceParts } if (string.IsNullOrEmpty(fileInfo.DirectoryName)) continue; - rotatedFileInfo = new FileInfo(Path.Combine(fileInfo.DirectoryName, $"{deterministicHashCodeKey} - R{item.ImageFileHolder.ExtensionLowered}{_FileNameExtension}")); + rotatedFileInfo = new FileInfo(Path.Combine(fileInfo.DirectoryName, $"{deterministicHashCodeKey} - R{mappingFromItem.ImageFileHolder.ExtensionLowered}{_FileNameExtension}")); collection.Add(new(face, fileInfo.FullName, rotatedFileInfo.FullName)); if (check) continue; @@ -260,7 +255,7 @@ public class D2_FaceParts } } if (check) - SaveFaceParts(pointSize, item.ResizedFileHolder, saveRotated, collection); + SaveFaceParts(pointSize, mappingFromItem.ResizedFileHolder, saveRotated, collection); } } \ No newline at end of file diff --git a/FaceRecognitionDotNet/FaceRecognitionDotNet.csproj b/FaceRecognitionDotNet/FaceRecognitionDotNet.csproj index d7a5796..e577bd5 100644 --- a/FaceRecognitionDotNet/FaceRecognitionDotNet.csproj +++ b/FaceRecognitionDotNet/FaceRecognitionDotNet.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.FaceRecognitionDotNet diff --git a/FaceRecognitionDotNet/Point.cs b/FaceRecognitionDotNet/Point.cs index 7f29bc2..a599ea9 100644 --- a/FaceRecognitionDotNet/Point.cs +++ b/FaceRecognitionDotNet/Point.cs @@ -63,9 +63,9 @@ public struct Point : IEquatable #region overrides /// - /// Determines whether the specified is a and whether it contains the same coordinates as this . + /// Determines whether the specified is a and whether it contains the same coordinates as this . /// - /// The to compare. + /// The to compare. /// true if is a and contains the same and values as this ; otherwise, false. public override bool Equals(object? obj) => obj is Point point && Equals(point); diff --git a/Instance/DlibDotNet.cs b/Instance/DlibDotNet.cs index b5a7bc9..48f6b2e 100644 --- a/Instance/DlibDotNet.cs +++ b/Instance/DlibDotNet.cs @@ -278,42 +278,20 @@ public partial class DlibDotNet return result; } - private static MappingFromItem GetMappingFromItem(Item item) + private void FullParallelForWork(A_Property propertyLogic, Dictionary> idToMappedFaceFilesCollection, string outputResolution, string bResultsFullGroupDirectory, string cResultsFullGroupDirectory, string dResultsFullGroupDirectory, string? eDistanceContentDirectory, List> sourceDirectoryChanges, List propertyFileHolderCollection, List propertyCollection, List>> metadataCollections, List> resizeKeyValuePairs, List> imageFaceCollections, Container container, int index, Item item) { - MappingFromItem result; - bool? isWrongYear; - DateTime minimumDateTime; - if (item.Property?.Id is null) - throw new NotSupportedException(); - if (item.Property?.Id is null || item.ImageFileHolder is null || item.ResizedFileHolder is null) - throw new NotSupportedException(); - minimumDateTime = Shared.Models.Stateless.Methods.IProperty.GetMinimumDateTime(item.Property); - (isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder, minimumDateTime); - result = new(item.Property.Id.Value, item.ImageFileHolder, isWrongYear, minimumDateTime, item.RelativePath, item.ResizedFileHolder); - return result; - } - - private void FullParallelForWork(A_Property propertyLogic, Dictionary> idToMappedFaceFilesCollection, string outputResolution, string bResultsFullGroupDirectory, string cResultsFullGroupDirectory, string dResultsFullGroupDirectory, string? eDistanceContentDirectory, List> sourceDirectoryChanges, List propertyFileHolderCollection, List propertyCollection, List>> metadataCollections, List> resizeKeyValuePairs, List?> imageFaceCollections, Container container, int index, Item item) - { - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); + if (_Log is null) + throw new NullReferenceException(nameof(_Log)); string original = "Original"; - FileHolder? resizedFileHolder; + List faces; Shared.Models.Property property; long ticks = DateTime.Now.Ticks; DateTime dateTime = DateTime.Now; - List? faces; List parseExceptions = new(); Dictionary imageResizeKeyValuePairs; List> subFileTuples = new(); List> metadataCollection; - if (item.Property is not null) - { - property = item.Property; - if ((item.Changed.HasValue && item.Changed.Value) || (item.Moved.HasValue && item.Moved.Value) || (item.Abandoned.HasValue && item.Abandoned.Value)) - throw new NotImplementedException(); - } - else + if (item.Property is null || item.Property.Id is null) { property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions); item.Update(property); @@ -323,31 +301,48 @@ public partial class DlibDotNet sourceDirectoryChanges.Add(new Tuple(nameof(A_Property), (from l in subFileTuples select l.Item2).Max())); } } - (int metadataGroups, metadataCollection) = _Metadata.GetMetadataCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, subFileTuples, parseExceptions, item); + else + { + property = item.Property; + if (item.Abandoned.HasValue && item.Abandoned.Value) + _Log.Information(string.Concat("Abandoned <", item.ImageFileHolder.FullName, '>')); + else if (item.FileSizeChanged.HasValue && item.FileSizeChanged.Value) + _Log.Information(string.Concat("FileSizeChanged <", item.ImageFileHolder.FullName, '>')); + else if (item.LastWriteTimeChanged.HasValue && item.LastWriteTimeChanged.Value) + _Log.Information(string.Concat("LastWriteTimeChanged <", item.ImageFileHolder.FullName, '>')); + else if (item.Moved.HasValue && item.Moved.Value) + _Log.Information(string.Concat("Moved <", item.ImageFileHolder.FullName, '>')); + } + if (property is null || item.Property is null) + throw new NullReferenceException(nameof(property)); + FileHolder resizedFileHolder = _Resize.GetResizedFileHolder(item); + item.SetResizedFileHolder(_Resize.FileNameExtension, resizedFileHolder); + string facesDirectory = _Faces.GetFacesDirectory(dResultsFullGroupDirectory, item); + MappingFromItem mappingFromItem = Shared.Models.Stateless.Methods.IMappingFromItem.GetMappingFromItem(item, resizedFileHolder); + (int metadataGroups, metadataCollection) = _Metadata.GetMetadataCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, subFileTuples, parseExceptions, mappingFromItem); if (_AppSettings.MaxDegreeOfParallelism < 2) ticks = LogDelta(ticks, nameof(B_Metadata.GetMetadataCollection)); - imageResizeKeyValuePairs = _Resize.GetResizeKeyValuePairs(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item); + imageResizeKeyValuePairs = _Resize.GetResizeKeyValuePairs(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item.Property, mappingFromItem); if (_AppSettings.MaxDegreeOfParallelism < 2) ticks = LogDelta(ticks, nameof(C_Resize.GetResizeKeyValuePairs)); if (_Configuration.SaveResizedSubfiles) { - _Resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, imageResizeKeyValuePairs); + _Resize.SaveResizedSubfile(_Configuration.PropertyConfiguration, outputResolution, cResultsFullGroupDirectory, subFileTuples, item, item.Property, mappingFromItem, original, imageResizeKeyValuePairs); if (_AppSettings.MaxDegreeOfParallelism < 2) ticks = LogDelta(ticks, nameof(C_Resize.SaveResizedSubfile)); } else if (outputResolution == _Configuration.OutputResolutions[0] && false) { - byte[] bytes = _Resize.GetResizedBytes(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, imageResizeKeyValuePairs); + byte[] bytes = _Resize.GetResizedBytes(outputResolution, cResultsFullGroupDirectory, subFileTuples, item.Property, mappingFromItem, imageResizeKeyValuePairs); if (_AppSettings.MaxDegreeOfParallelism < 2) ticks = LogDelta(ticks, nameof(C_Resize.GetResizedBytes)); string path = Path.Combine(resizedFileHolder.DirectoryName, resizedFileHolder.NameWithoutExtension); File.WriteAllBytes(path, bytes); } if (!_Configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions.Contains(outputResolution)) - faces = null; + faces = new(); else { - MappingFromItem mappingFromItem = GetMappingFromItem(item); int[] outputResolutionCollection = imageResizeKeyValuePairs[outputResolution]; int outputResolutionWidth = outputResolutionCollection[0]; int outputResolutionHeight = outputResolutionCollection[1]; @@ -355,7 +350,7 @@ public partial class DlibDotNet faces = _Faces.GetFaces(dResultsFullGroupDirectory, subFileTuples, parseExceptions, property, mappingFromItem, outputResolutionWidth, outputResolutionHeight, outputResolutionOrientation); if (_AppSettings.MaxDegreeOfParallelism < 2) ticks = LogDelta(ticks, nameof(D_Face.GetFaces)); - bool anyFacesSaved = _Faces.SaveFaces(dResultsFullGroupDirectory, subFileTuples, parseExceptions, mappingFromItem, faces); + bool anyFacesSaved = _Faces.SaveFaces(dResultsFullGroupDirectory, subFileTuples, parseExceptions, mappingFromItem, facesDirectory, faces); if (_AppSettings.MaxDegreeOfParallelism < 2) ticks = LogDelta(ticks, nameof(D_Face.SaveFaces)); if (!anyFacesSaved && item.Property?.Id is not null @@ -366,7 +361,7 @@ public partial class DlibDotNet throw new NotImplementedException(); // bool saveRotated = _Configuration.SaveFaceLandmarkForOutputResolutions.Contains(outputResolution); // string sourceDirectorySegment = Property.Models.Stateless.IResult.GetRelativePath(_Configuration.PropertyConfiguration, container.SourceDirectory); - // string facesDirectory = Path.GetFullPath(Path.Combine($"{Path.Combine(d2FacePartsContentDirectory, "()")}{sourceDirectorySegment}", item.ImageFileHolder.NameWithoutExtension)); + // string facePartsDirectoryX = Path.GetFullPath(Path.Combine($"{Path.Combine(d2FacePartsContentDirectory, "()")}{sourceDirectorySegment}", item.ImageFileHolder.NameWithoutExtension)); // _FaceParts.SaveFaceLandmarkImages(facesDirectory, subFileTuples, parseExceptions, item, faceCollection, saveRotated); // if (_AppSettings.MaxDegreeOfParallelism < 2) // ticks = LogDelta(ticks, nameof(D2_FaceParts.SaveFaceLandmarkImages)); @@ -396,7 +391,7 @@ public partial class DlibDotNet List propertyCollection, List>> metadataCollection, List> resizeKeyValuePairs, - List?> imageFaceCollections, + List> imageFaceCollections, Container container, Item[] filteredItems, string message) @@ -415,7 +410,7 @@ public partial class DlibDotNet { propertyCollection.Add(null); metadataCollection.Add(new()); - imageFaceCollections.Add(null); + imageFaceCollections.Add(new()); resizeKeyValuePairs.Add(new()); propertyFileHolderCollection.Add(null); } @@ -491,7 +486,7 @@ public partial class DlibDotNet } } - private void WriteGroup(A_Property propertyLogic, Shared.Models.Property[] propertyCollection, List>> metadataCollection, List> resizeKeyValuePairs, List?> imageFaceCollections, string outputResolution, Container container, Item[] filteredItems) + private void WriteGroup(A_Property propertyLogic, Shared.Models.Property[] propertyCollection, List>> metadataCollection, List> resizeKeyValuePairs, List> imageFaceCollections, string outputResolution, Container container, Item[] filteredItems) { Item item; string key; @@ -504,7 +499,7 @@ public partial class DlibDotNet string checkDirectory; List> propertyCollectionKeyValuePairs = new(); List>> resizeKeyValuePairsCollections = new(); - List?>> imageFaceCollectionsKeyValuePairs = new(); + List>> imageFaceCollectionsKeyValuePairs = new(); List>>> metadataCollectionKeyValuePairs = new(); (int level, List directories) = Shared.Models.Stateless.Methods.IPath.Get( _Configuration.PropertyConfiguration.RootDirectory, @@ -515,12 +510,10 @@ public partial class DlibDotNet item = filteredItems[i]; if (item.Property is null) continue; - if (item.ImageFileHolder is null) - continue; key = Shared.Models.Stateless.Methods.IPath.GetRelativePath(item.ImageFileHolder.FullName, sourceDirectoryLength); propertyCollectionKeyValuePairs.Add(new KeyValuePair(key, propertyCollection[i])); resizeKeyValuePairsCollections.Add(new KeyValuePair>(key, resizeKeyValuePairs[i])); - imageFaceCollectionsKeyValuePairs.Add(new KeyValuePair?>(key, imageFaceCollections[i])); + imageFaceCollectionsKeyValuePairs.Add(new KeyValuePair>(key, imageFaceCollections[i])); metadataCollectionKeyValuePairs.Add(new KeyValuePair>>(key, metadataCollection[i])); } if (propertyLogic.AngleBracketCollection.Any()) @@ -599,45 +592,11 @@ public partial class DlibDotNet return new(aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory); } - private void SetAngleBracketCollections(A_Property propertyLogic, string outputResolution, Container container, string aResultsFullGroupDirectory, string bResultsFullGroupDirectory, string cResultsFullGroupDirectory, string dResultsFullGroupDirectory) + private void SetAngleBracketCollections(A_Property propertyLogic, Container container, string aResultsFullGroupDirectory, string bResultsFullGroupDirectory, string cResultsFullGroupDirectory) { - _Faces.AngleBracketCollection.Clear(); - _Resize.AngleBracketCollection.Clear(); - _Metadata.AngleBracketCollection.Clear(); - propertyLogic.AngleBracketCollection.Clear(); - propertyLogic.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _Configuration.PropertyConfiguration, - container.SourceDirectory, - aResultsFullGroupDirectory, - contentDescription: string.Empty, - singletonDescription: "Properties for each image", - collectionDescription: string.Empty, - converted: false)); - _Metadata.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _Configuration.PropertyConfiguration, - container.SourceDirectory, - bResultsFullGroupDirectory, - contentDescription: string.Empty, - singletonDescription: "Metadata as key value pairs", - collectionDescription: string.Empty, - converted: true)); - _Resize.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _Configuration.PropertyConfiguration, - container.SourceDirectory, - cResultsFullGroupDirectory, - contentDescription: "Resized image", - singletonDescription: "Resize dimensions for each resolution", - collectionDescription: string.Empty, - converted: true)); - if (_Configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions.Contains(outputResolution)) - _Faces.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _Configuration.PropertyConfiguration, - container.SourceDirectory, - dResultsFullGroupDirectory, - contentDescription: "n png file(s) for each face found", - singletonDescription: string.Empty, - collectionDescription: "For each image a json file with all faces found", - converted: true)); + propertyLogic.SetAngleBracketCollection(aResultsFullGroupDirectory, container.SourceDirectory); + _Resize.SetAngleBracketCollection(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, container.SourceDirectory); + _Metadata.SetAngleBracketCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, container.SourceDirectory); } private Item[] GetFilterItems(Container container) @@ -672,10 +631,10 @@ public partial class DlibDotNet Shared.Models.Property[] propertyCollection; List propertyFileHolderCollection = new(); List> resizeKeyValuePairs = new(); + List> imageFaceCollections = new(); List> sourceDirectoryChanges = new(); - List?> imageFaceCollections = new(); - List nullablePropertyCollection = new(); int maxDegreeOfParallelism = _AppSettings.MaxDegreeOfParallelism; + List nullablePropertyCollection = new(); List>> metadataCollection = new(); foreach (string outputResolution in _Configuration.OutputResolutions) { @@ -699,7 +658,9 @@ public partial class DlibDotNet propertyFileHolderCollection.Clear(); totalSeconds = (int)Math.Floor(new TimeSpan(DateTime.Now.Ticks - ticks).TotalSeconds); message = $"{i + 1:000}.{container.G} [{filteredItems.Length:000} files] / {containersLength:000} - {total} / {t} total files - {totalSeconds} total second(s) - {outputResolution} - {container.SourceDirectory}"; - SetAngleBracketCollections(propertyLogic, outputResolution, container, aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory); + if (_Configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions.Contains(outputResolution)) + _Faces.SetAngleBracketCollection(dResultsFullGroupDirectory, container.SourceDirectory); + SetAngleBracketCollections(propertyLogic, container, aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory); exceptionCount = FullParallelWork( maxDegreeOfParallelism, propertyLogic, @@ -781,10 +742,9 @@ public partial class DlibDotNet Shared.Models.Face[] faces; Mapping mapping; int faceAreaPermille; - bool? isWrongYear; Item[] filteredItems; int confidencePercent; - DateTime minimumDateTime; + List distinct = new(); int normalizedPixelPercentage; string deterministicHashCodeKey; MappingFromItem mappingFromItem; @@ -803,20 +763,19 @@ public partial class DlibDotNet continue; foreach (Item item in filteredItems) { - if (item.Property?.Id is null || item.ImageFileHolder is null || item.ResizedFileHolder is null) + if (item.Property?.Id is null || item.ResizedFileHolder is null) continue; + if (distinct.Contains(item.Property.Id.Value)) + continue; + distinct.Add(item.Property.Id.Value); if (!item.Faces.Any(l => l.FaceEncoding is not null && l.Location is not null && l.OutputResolution is not null)) { items.Add(item); continue; } - minimumDateTime = Shared.Models.Stateless.Methods.IProperty.GetMinimumDateTime(item.Property); - (isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder, minimumDateTime); - mappingFromItem = new(item.Property.Id.Value, item.ImageFileHolder, isWrongYear, minimumDateTime, item.RelativePath, item.ResizedFileHolder); + mappingFromItem = Shared.Models.Stateless.Methods.IMappingFromItem.GetMappingFromItem(item); foreach (Shared.Models.Face face in item.Faces) { - if (face.RelativePath != item.RelativePath) - break; if (face.FaceEncoding is null || face.Location is null || face.OutputResolution is null) continue; confidencePercent = Shared.Models.Stateless.Methods.ILocation.GetConfidencePercent(_Configuration.FaceConfidencePercent, _Configuration.RangeFaceConfidence, face.Location.Confidence); @@ -958,9 +917,7 @@ public partial class DlibDotNet private List GetMappingFromItemCollection(Container[] containers) { List results = new(); - bool? isWrongYear; Item[] filteredItems; - DateTime minimumDateTime; MappingFromItem mappingFromItem; foreach (Container container in containers) { @@ -973,11 +930,9 @@ public partial class DlibDotNet continue; foreach (Item item in filteredItems) { - if (item.Property?.Id is null || item.ImageFileHolder is null) + if (item.Property?.Id is null) continue; - minimumDateTime = Shared.Models.Stateless.Methods.IProperty.GetMinimumDateTime(item.Property); - (isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder, minimumDateTime); - mappingFromItem = new(item.Property.Id.Value, item.ImageFileHolder, isWrongYear, minimumDateTime, item.RelativePath, item.ImageFileHolder); + mappingFromItem = Shared.Models.Stateless.Methods.IMappingFromItem.GetMappingFromItem(item); results.Add(mappingFromItem); } } @@ -1033,6 +988,8 @@ public partial class DlibDotNet if (_PropertyRootExistedBefore || container is not null) break; (aResultsFullGroupDirectory, bResultsFullGroupDirectory, cResultsFullGroupDirectory, dResultsFullGroupDirectory) = GetResultsFullGroupDirectories(outputResolution); + if (_Configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions.Contains(outputResolution)) + MapLogicSupport.BeforeSaveResizedImagesByPersonKeyFormatted(_Configuration.JLinks, a2PeopleSingletonDirectory); if (_ArgZeroIsConfigurationRootDirectory && _Configuration.SaveResizedSubfiles && outputResolution == _Configuration.OutputResolutions[0] diff --git a/Instance/Instance.csproj b/Instance/Instance.csproj index 11c4b95..029048a 100644 --- a/Instance/Instance.csproj +++ b/Instance/Instance.csproj @@ -5,7 +5,7 @@ enable Exe win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Instance @@ -34,23 +34,19 @@ - - - - - - - - - - - - - + + + + + + + + + - - - + + + diff --git a/Instance/Models/Binder/AppSettings.cs b/Instance/Models/Binder/AppSettings.cs index e5909f6..00338af 100644 --- a/Instance/Models/Binder/AppSettings.cs +++ b/Instance/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/Instance/Models/Binder/Configuration.cs b/Instance/Models/Binder/Configuration.cs index 727649b..a71d6d1 100644 --- a/Instance/Models/Binder/Configuration.cs +++ b/Instance/Models/Binder/Configuration.cs @@ -86,9 +86,11 @@ public class Configuration return result; } - private static Models.Configuration Get(Configuration configuration) + private static Models.Configuration Get(Configuration? configuration) { Models.Configuration result; + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); if (configuration.CheckDFaceAndUpWriteDates is null) throw new NullReferenceException(nameof(configuration.CheckDFaceAndUpWriteDates)); if (configuration.CheckJsonForDistanceResults is null) @@ -121,10 +123,8 @@ public class Configuration throw new NullReferenceException(nameof(configuration.IgnoreExtensions)); if (configuration.IgnoreRelativePaths is null) throw new NullReferenceException(nameof(configuration.IgnoreRelativePaths)); - if (configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions = Array.Empty(); - if (configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = Array.Empty(); + configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions ??= Array.Empty(); + configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions ??= Array.Empty(); if (configuration.LoadOrCreateThenSaveIndex is null) throw new NullReferenceException(nameof(configuration.LoadOrCreateThenSaveIndex)); if (configuration.LocationDigits is null) @@ -181,24 +181,17 @@ public class Configuration throw new NullReferenceException(nameof(configuration.RetryImagesWithoutAFace)); if (configuration.Reverse is null) throw new NullReferenceException(nameof(configuration.Reverse)); - if (configuration.SaveFaceDistancesForOutputResolutions is null) - configuration.SaveFaceDistancesForOutputResolutions = Array.Empty(); - if (configuration.SaveFaceLandmarkForOutputResolutions is null) - configuration.SaveFaceLandmarkForOutputResolutions = Array.Empty(); + configuration.SaveFaceDistancesForOutputResolutions ??= Array.Empty(); + configuration.SaveFaceLandmarkForOutputResolutions ??= Array.Empty(); if (configuration.SaveFullYearOfRandomFiles is null) throw new NullReferenceException(nameof(configuration.SaveFullYearOfRandomFiles)); - if (configuration.SaveMappedForOutputResolutions is null) - configuration.SaveMappedForOutputResolutions = Array.Empty(); - if (configuration.SaveNotMappedForOutputResolutions is null) - configuration.SaveNotMappedForOutputResolutions = Array.Empty(); - if (configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions is null) - configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions = Array.Empty(); + configuration.SaveMappedForOutputResolutions ??= Array.Empty(); + configuration.SaveNotMappedForOutputResolutions ??= Array.Empty(); + configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions ??= Array.Empty(); if (configuration.SaveResizedSubfiles is null) throw new NullReferenceException(nameof(configuration.SaveResizedSubfiles)); - if (configuration.SaveShortcutsForOutputResolutions is null) - configuration.SaveShortcutsForOutputResolutions = Array.Empty(); - if (configuration.SaveShortcutsForOutputResolutions is null) - configuration.SaveShortcutsForOutputResolutions = Array.Empty(); + configuration.SaveShortcutsForOutputResolutions ??= Array.Empty(); + configuration.SaveShortcutsForOutputResolutions ??= Array.Empty(); if (configuration.SkipSearch is null) throw new NullReferenceException(nameof(configuration.SkipSearch)); if (configuration.SortingMaximumPerFaceShouldBeHigh is null) @@ -285,7 +278,7 @@ public class Configuration public static Models.Configuration Get(IsEnvironment isEnvironment, IConfigurationRoot configurationRoot, Property.Models.Configuration propertyConfiguration) { Models.Configuration result; - Configuration configuration; + Configuration? configuration; if (isEnvironment is null) configuration = configurationRoot.Get(); else @@ -296,6 +289,8 @@ public class Configuration configuration = configurationSection.Get(); } result = Get(configuration); + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); result.SetAndUpdate(propertyConfiguration, configuration.NumberOfJitters, configuration.NumberOfTimesToUpsample, configuration.ModelName, configuration.PredictorModelName); return result; } diff --git a/Instance/Models/_G_Index.cs b/Instance/Models/_G_Index.cs index a3b3df0..38ef6f5 100644 --- a/Instance/Models/_G_Index.cs +++ b/Instance/Models/_G_Index.cs @@ -170,7 +170,7 @@ public class G_Index : Shared.Models.Properties.IIndex, IIndex foreach (Tuple tuple in tuples.Value) { fileInfo = new FileInfo(Path.Combine(directoryInfoCollection[0].Replace("<>", "{}"), string.Concat(Path.GetFileNameWithoutExtension(tuple.Item1), ".json"))); - if (!fileInfo.Exists) + if (!fileInfo.FullName.Contains(configuration.ResultAllInOne) && !fileInfo.Exists) { if (fileInfo.Directory?.Parent is null) throw new Exception(); diff --git a/Instance/appsettings.Development.json b/Instance/appsettings.Development.json index 028c9b0..8dfd976 100644 --- a/Instance/appsettings.Development.json +++ b/Instance/appsettings.Development.json @@ -53,7 +53,7 @@ "CheckDFaceAndUpWriteDates": true, "CheckJsonForDistanceResults": false, "CrossDirectoryMaxItemsInDistanceCollection": 7, - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "DistanceFactor": 8, "DistanceMoveUnableToMatch": false, "DistancePixelDistanceTolerance": 1, @@ -104,8 +104,8 @@ "RetryImagesWithoutAFace": false, "Reverse": false, "xRootDirectory": "C:/Tmp/phares/Pictures", - "RootDirectory": "F:/Tmp/Phares/Compare/Images 2022-10-23 - 239acf2 - III", - "xxRootDirectory": "F:/Tmp/Phares/Compare/Images 2022-10-23 - 239acf2 - III/Facebook/=2022.3 Facebook", + "RootDirectory": "F:/Tmp/Phares/Compare/Images 2022-11-12 - c6aa7e8 - III", + "xxRootDirectory": "F:/Tmp/Phares/Compare/Images 2022-11-12 - c6aa7e8 - III/Facebook/=2022.3 Facebook", "SaveFullYearOfRandomFiles": true, "SaveResizedSubFiles": true, "SkipSearch": false, @@ -182,8 +182,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/Instance/appsettings.Staging.json b/Instance/appsettings.Staging.json index 09eabd0..9bfac95 100644 --- a/Instance/appsettings.Staging.json +++ b/Instance/appsettings.Staging.json @@ -53,7 +53,7 @@ "CheckDFaceAndUpWriteDates": true, "CheckJsonForDistanceResults": false, "CrossDirectoryMaxItemsInDistanceCollection": 7, - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "DistanceFactor": 8, "DistanceMoveUnableToMatch": false, "DistancePixelDistanceTolerance": 1, @@ -174,8 +174,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/Instance/appsettings.json b/Instance/appsettings.json index e6de027..939c88c 100644 --- a/Instance/appsettings.json +++ b/Instance/appsettings.json @@ -53,7 +53,7 @@ "CheckDFaceAndUpWriteDates": true, "CheckJsonForDistanceResults": false, "CrossDirectoryMaxItemsInDistanceCollection": 7, - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "DistanceFactor": 8, "DistanceMoveUnableToMatch": false, "DistancePixelDistanceTolerance": 1, @@ -183,8 +183,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/Map/Map.csproj b/Map/Map.csproj index 3e1b382..c7bf828 100644 --- a/Map/Map.csproj +++ b/Map/Map.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Map @@ -34,14 +34,12 @@ - - - - - - - - + + + + + + diff --git a/Map/Models/MapLogic.cs b/Map/Models/MapLogic.cs index 88edb1e..e65098b 100644 --- a/Map/Models/MapLogic.cs +++ b/Map/Models/MapLogic.cs @@ -246,24 +246,55 @@ public class MapLogic } } + private static string? GetFacesDirectory(string dFacesContentDirectory, MappingFromItem mappingFromItem) + { + string? result; + string? directoryName = Path.GetDirectoryName(mappingFromItem.RelativePath); + if (directoryName is null) + result = null; + else + result = Path.Combine($"{dFacesContentDirectory}{directoryName}", mappingFromItem.ImageFileHolder.NameWithoutExtension); + return result; + } + + private static string? GetFacePartsDirectory(string d2FacePartsContentDirectory, MappingFromItem mappingFromItem) + { + string? result; + string? directoryName = Path.GetDirectoryName(mappingFromItem.RelativePath); + if (directoryName is null) + result = null; + else + result = Path.Combine($"{d2FacePartsContentDirectory}{directoryName}", mappingFromItem.ImageFileHolder.NameWithoutExtension); + return result; + } + private SaveContainer? GetMatchSaveContainer(string dFacesContentDirectory, string d2FacePartsContentDirectory, string directory, Mapping mapping) { if (_Configuration is null) throw new NullReferenceException(nameof(_Configuration)); SaveContainer? result; string shortcutFile = string.Empty; - string? directoryName = Path.GetDirectoryName(mapping.MappingFromItem.RelativePath); - string facesDirectory = Path.Combine($"{dFacesContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); - FileHolder faceFileHolder = new(Path.Combine(facesDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesFileNameExtension}")); - if (directoryName is null || !faceFileHolder.Exists) + string? facesDirectory = GetFacesDirectory(dFacesContentDirectory, mapping.MappingFromItem); + if (facesDirectory is null) result = null; else { - string facePartsDirectory = Path.Combine($"{d2FacePartsContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); - string checkFile = Path.Combine(directory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}"); - FileHolder hiddenFaceFileHolder = new(Path.Combine(facesDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesHiddenFileNameExtension}")); - FileHolder facePartsFileHolder = new(Path.Combine(facePartsDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacePartsFileNameExtension}")); - result = new(checkFile, directory, faceFileHolder, hiddenFaceFileHolder, facePartsFileHolder, mapping.MappingFromItem.ResizedFileHolder, shortcutFile); + FileHolder faceFileHolder = new(Path.Combine(facesDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesFileNameExtension}")); + if (!faceFileHolder.Exists) + result = null; + else + { + string? facePartsDirectory = GetFacePartsDirectory(d2FacePartsContentDirectory, mapping.MappingFromItem); + if (facePartsDirectory is null) + result = null; + else + { + string checkFile = Path.Combine(directory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}"); + FileHolder hiddenFaceFileHolder = new(Path.Combine(facesDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesHiddenFileNameExtension}")); + FileHolder facePartsFileHolder = new(Path.Combine(facePartsDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacePartsFileNameExtension}")); + result = new(checkFile, directory, faceFileHolder, hiddenFaceFileHolder, facePartsFileHolder, mapping.MappingFromItem.ResizedFileHolder, shortcutFile); + } + } } return result; } @@ -339,12 +370,12 @@ public class MapLogic string checkFile; string directory; string shortcutFile; - string facesDirectory; string? directoryName; string personDirectory; + string? facesDirectory; FileHolder faceFileHolder; - string facePartsDirectory; string personKeyFormatted; + string? facePartsDirectory; SaveContainer? saveContainer; FileHolder facePartsFileHolder; FileHolder hiddenFaceFileHolder; @@ -380,15 +411,17 @@ public class MapLogic personDirectory = Path.Combine(directory, mapping.MappingFromPerson.DisplayDirectoryName, "lnk"); else personDirectory = Path.Combine(directory, mapping.MappingFromPerson.DisplayDirectoryName[..1], "lnk"); - if (isByMapping && personKeyToCount.ContainsKey(personKey)) + if (isByMapping && personKeyToCount.TryGetValue(personKey, out int count)) { - saveContainer = new(Path.Combine(directory, mapping.MappingFromPerson.DisplayDirectoryName, $"{personKeyToCount[personKey]} Face(s)")); + saveContainer = new(Path.Combine(directory, mapping.MappingFromPerson.DisplayDirectoryName, $"{count} Face(s)")); results.Add(saveContainer); } } saveContainer = new(personDirectory); results.Add(saveContainer); - facesDirectory = Path.Combine($"{dFacesContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); + facesDirectory = GetFacesDirectory(dFacesContentDirectory, mapping.MappingFromItem); + if (facesDirectory is null) + continue; faceFileHolder = new(Path.Combine(facesDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesFileNameExtension}")); if (!faceFileHolder.Exists) continue; @@ -399,7 +432,9 @@ public class MapLogic } else { - facePartsDirectory = Path.Combine($"{d2FacePartsContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); + facePartsDirectory = GetFacePartsDirectory(d2FacePartsContentDirectory, mapping.MappingFromItem); + if (facePartsDirectory is null) + continue; checkFile = Path.Combine(directory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}"); shortcutFile = Path.Combine(personDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}.lnk"); hiddenFaceFileHolder = new(Path.Combine(facesDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesHiddenFileNameExtension}")); @@ -633,9 +668,9 @@ public class MapLogic string faceFileName; string shortcutFile; string? directoryName; - string facesDirectory; string mappingSegmentB; string personDirectory; + string? facesDirectory; string personKeyFormatted; string personDisplayFileName; PersonBirthday personBirthday; @@ -653,6 +688,8 @@ public class MapLogic personBirthday = keyValuePair.Value.Birthdays[zero]; foreach (string personDisplayDirectoryAllFile in keyValuePair.Value.DisplayDirectoryAllFiles) { + if (personDisplayDirectoryAllFile.Contains("-2318605")) + continue; if (!personDisplayDirectoryAllFile.EndsWith(_Configuration.FacesFileNameExtension)) continue; (id, normalizedPixelPercentage, _) = IMapping.GetReversedDeterministicHashCodeKey(_Configuration.FacesFileNameExtension, personDisplayDirectoryAllFile); @@ -678,7 +715,9 @@ public class MapLogic if (string.IsNullOrEmpty(directoryName)) throw new NotSupportedException(); shortcutFile = Path.Combine(personDisplayDirectory, $"{personDisplayFileName}.lnk"); - facesDirectory = Path.Combine($"{dFacesContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); + facesDirectory = GetFacesDirectory(dFacesContentDirectory, mapping.MappingFromItem); // Path.Combine($"{dFacesContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); + if (facesDirectory is null) + continue; faceFileName = $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesFileNameExtension}"; checkFile = Path.Combine(directory, fileInfo.Name); if (!_IdThenNormalizedPixelPercentageToPersonContainers.TryGetValue(id.Value, out normalizedPixelPercentageToPeronContainerCollection) || !normalizedPixelPercentageToPeronContainerCollection.ContainsKey(normalizedPixelPercentage.Value)) @@ -762,6 +801,8 @@ public class MapLogic { if (_Configuration is null) throw new NullReferenceException(nameof(_Configuration)); + if (_MapLogicSupport is null) + throw new NullReferenceException(nameof(_MapLogicSupport)); List<(string, PersonContainer)> results = new(); string[] files; const int zero = 0; @@ -788,8 +829,12 @@ public class MapLogic fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); if (windowsShortcut.Path is null) continue; - if (!Directory.Exists(windowsShortcut.Path) && files.Length != checkDirectories.Length) - throw new NotSupportedException(fileNameWithoutExtension); + if (!Directory.Exists(windowsShortcut.Path)) + { + if (files.Length != checkDirectories.Length) + throw new NotSupportedException(fileNameWithoutExtension); + continue; + } (personKeyFormatted, personBirthday) = GetPersonBirthday(windowsShortcut.Path); if (personBirthday is not null) { @@ -819,9 +864,10 @@ public class MapLogic { matches = (from l in personContainers where l.Key == personKey && l.ApproximateYears.HasValue select l).ToArray(); if (!matches.Any()) - throw new NotSupportedException(fileNameWithoutExtension); + continue; if (!Directory.Exists(displayDirectoryName)) _ = Directory.CreateDirectory(displayDirectoryName); + personKeyFormatted = IPersonBirthday.GetFormatted(_Configuration.PersonBirthdayFormat, personKey); results.Add(new(personKeyFormatted, matches[zero])); } } @@ -995,8 +1041,8 @@ public class MapLogic Mapping mapping; string checkFile; string directory; - string facesDirectory; string? directoryName; + string? facesDirectory; FileHolder faceFileHolder; List? normalizedPixelPercentages; string by = nameof(IMapLogic.CopyNotMappedFaces); @@ -1013,7 +1059,9 @@ public class MapLogic if (normalizedPixelPercentages is not null && normalizedPixelPercentages.Contains(mapping.MappingFromLocation.NormalizedPixelPercentage)) continue; directoryName = Path.GetDirectoryName(mapping.MappingFromItem.RelativePath); - facesDirectory = Path.Combine($"{dFacesContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); + facesDirectory = GetFacesDirectory(dFacesContentDirectory, mapping.MappingFromItem); // Path.Combine($"{dFacesContentDirectory}{directoryName}", mapping.MappingFromItem.ImageFileHolder.NameWithoutExtension); + if (facesDirectory is null) + continue; faceFileHolder = new(Path.Combine(facesDirectory, $"{mapping.MappingFromLocation.DeterministicHashCodeKey}{mapping.MappingFromItem.ImageFileHolder.ExtensionLowered}{_Configuration.FacesFileNameExtension}")); if (directoryName is null || !faceFileHolder.Exists) continue; diff --git a/Map/Models/Stateless/MapLogic.cs b/Map/Models/Stateless/MapLogic.cs index 4dd26da..08f5194 100644 --- a/Map/Models/Stateless/MapLogic.cs +++ b/Map/Models/Stateless/MapLogic.cs @@ -208,7 +208,10 @@ internal abstract class MapLogic ticksDirectories = Array.Empty(); else { - _ = IPath.DeleteEmptyDirectories(eDistanceContentDirectory); + if (!Directory.Exists(eDistanceContentDirectory)) + _ = Directory.CreateDirectory(eDistanceContentDirectory); + else + _ = IPath.DeleteEmptyDirectories(eDistanceContentDirectory); ticksDirectories = Directory.GetDirectories(eDistanceContentDirectory, "*", SearchOption.TopDirectoryOnly); } string message = $") {ticksDirectories.Length:000} collect from and clean ticks Director(ies) - A - {totalSeconds} total second(s)"; @@ -556,22 +559,28 @@ internal abstract class MapLogic } } + private static string? GetDisplayDirectoryName(Dictionary personKeyToPersonContainer, long key) + { + string? result = null; + if (personKeyToPersonContainer.TryGetValue(key, out PersonContainer? personContainer)) + { + result = personContainer.DisplayDirectoryName; + if (string.IsNullOrEmpty(result)) + throw new NotSupportedException(); + } + return result; + } + private static void SetPersonKeyToPersonContainer(Configuration configuration, List personContainers, long[] personKeyCollection, Dictionary personKeyToPersonContainer) { - string personDisplayDirectoryName; + string? displayDirectoryName; foreach (PersonContainer personContainer in personContainers) { if (personContainer.Key is null || !personKeyCollection.Contains(personContainer.Key.Value)) continue; - if (personKeyToPersonContainer.ContainsKey(personContainer.Key.Value)) - { - personDisplayDirectoryName = personKeyToPersonContainer[personContainer.Key.Value].DisplayDirectoryName; - if (string.IsNullOrEmpty(personDisplayDirectoryName)) - throw new NotSupportedException(); - if (personDisplayDirectoryName == personContainer.DisplayDirectoryName || (personDisplayDirectoryName[0] == personContainer.DisplayDirectoryName[0] && (personDisplayDirectoryName.Length == 1 || personContainer.DisplayDirectoryName.Length == 1))) - continue; - throw new NotImplementedException(); - } + displayDirectoryName = GetDisplayDirectoryName(personKeyToPersonContainer, personContainer.Key.Value); + if (displayDirectoryName is not null && (displayDirectoryName == personContainer.DisplayDirectoryName || (displayDirectoryName[0] == personContainer.DisplayDirectoryName[0] && (displayDirectoryName.Length == 1 || personContainer.DisplayDirectoryName.Length == 1)))) + continue; personKeyToPersonContainer.Add(personContainer.Key.Value, personContainer); } if (personKeyCollection.Any()) @@ -579,7 +588,7 @@ internal abstract class MapLogic int? approximateYears = null; PersonBirthday? personBirthday; PersonContainer? personContainer; - string displayDirectoryName = configuration.MappingDefaultName; + displayDirectoryName = configuration.MappingDefaultName; foreach (long personKey in personKeyCollection) { if (personKeyToPersonContainer.ContainsKey(personKey)) diff --git a/Metadata/Metadata.csproj b/Metadata/Metadata.csproj index 91c9eaa..f98ce14 100644 --- a/Metadata/Metadata.csproj +++ b/Metadata/Metadata.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Metadata @@ -34,11 +34,9 @@ - - - - - + + + diff --git a/Metadata/Models/B_Metadata.cs b/Metadata/Models/B_Metadata.cs index 538bd89..d521e14 100644 --- a/Metadata/Models/B_Metadata.cs +++ b/Metadata/Models/B_Metadata.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Text.Json; using View_by_Distance.Metadata.Models.Stateless; +using View_by_Distance.Property.Models.Stateless; using View_by_Distance.Shared.Models.Stateless; namespace View_by_Distance.Metadata.Models; @@ -35,6 +36,18 @@ public class B_Metadata return result; } + public void SetAngleBracketCollection(Property.Models.Configuration configuration, string bResultsFullGroupDirectory, string sourceDirectory) + { + AngleBracketCollection.Clear(); + AngleBracketCollection.AddRange(IResult.GetDirectoryInfoCollection(configuration, + sourceDirectory, + bResultsFullGroupDirectory, + contentDescription: string.Empty, + singletonDescription: "Metadata as key value pairs", + collectionDescription: string.Empty, + converted: true)); + } + private Dictionary>> GetMetadataCollection(string subFile) { Dictionary>> results = new(); @@ -78,38 +91,25 @@ public class B_Metadata return results; } - public (int, List>) GetMetadataCollection(Property.Models.Configuration propertyConfiguration, string bResultsFullGroupDirectory, List> subFileTuples, List parseExceptions, Shared.Models.Item item) + public (int, List>) GetMetadataCollection(Property.Models.Configuration configuration, string bResultsFullGroupDirectory, List> subFileTuples, List parseExceptions, Shared.Models.MappingFromItem mappingFromItem) { List> results = new(); - if (item.Property?.Id is null) - throw new NullReferenceException(nameof(item.Property.Id)); - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); string json = string.Empty; string[] changesFrom = Array.Empty(); Dictionary>>? dictionary; List dateTimes = (from l in subFileTuples where changesFrom.Contains(l.Item1) select l.Item2).ToList(); - string usingRelativePath = Path.Combine(AngleBracketCollection[0].Replace("<>", "{}"), string.Concat(item.ImageFileHolder.NameWithoutExtension, ".json")); - string bMetadataSingletonFile = Path.Combine(bResultsFullGroupDirectory, "{}", propertyConfiguration.ResultAllInOne, $"{item.Property.Id.Value}{item.ImageFileHolder.ExtensionLowered}.json"); + string bMetadataSingletonFile = Path.Combine(bResultsFullGroupDirectory, "{}", configuration.ResultAllInOne, $"{mappingFromItem.Id}{mappingFromItem.ImageFileHolder.ExtensionLowered}.json"); FileInfo fileInfo = new(bMetadataSingletonFile); - if (!fileInfo.Exists) + if (!fileInfo.FullName.Contains(configuration.ResultAllInOne) && !fileInfo.Exists) { - if (File.Exists(usingRelativePath)) + if (fileInfo.Directory?.Parent is null) + throw new Exception(); + string parentCheck = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name); + if (File.Exists(parentCheck)) { - File.Move(usingRelativePath, fileInfo.FullName); + File.Move(parentCheck, fileInfo.FullName); fileInfo.Refresh(); } - if (!fileInfo.Exists) - { - if (fileInfo.Directory?.Parent is null) - throw new Exception(); - string parentCheck = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name); - if (File.Exists(parentCheck)) - { - File.Move(parentCheck, fileInfo.FullName); - fileInfo.Refresh(); - } - } } if (_ForceMetadataLastWriteTimeToCreationTime && !fileInfo.Exists && File.Exists(Path.ChangeExtension(fileInfo.FullName, ".delete"))) { @@ -147,7 +147,7 @@ public class B_Metadata } if (dictionary is null || !dictionary.Any()) { - dictionary = GetMetadataCollection(item.ImageFileHolder.FullName); + dictionary = GetMetadataCollection(mappingFromItem.ImageFileHolder.FullName); json = JsonSerializer.Serialize(dictionary, _WriteIndentedJsonSerializerOptions); bool updateDateWhenMatches = dateTimes.Any() && fileInfo.Exists && dateTimes.Max() > fileInfo.LastWriteTime; DateTime? dateTime = !updateDateWhenMatches ? null : dateTimes.Max(); diff --git a/Not-Copy-Copy/Models/Binder/AppSettings.cs b/Not-Copy-Copy/Models/Binder/AppSettings.cs index 07e2b02..6aa9ef0 100644 --- a/Not-Copy-Copy/Models/Binder/AppSettings.cs +++ b/Not-Copy-Copy/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/Not-Copy-Copy/Models/Stateless/Configuration.cs b/Not-Copy-Copy/Models/Stateless/Configuration.cs index 32c092d..676e9f5 100644 --- a/Not-Copy-Copy/Models/Stateless/Configuration.cs +++ b/Not-Copy-Copy/Models/Stateless/Configuration.cs @@ -13,7 +13,7 @@ public abstract class Configuration 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? configuration = configurationSection.Get(); string json = JsonSerializer.Serialize(configuration, new JsonSerializerOptions() { WriteIndented = true }); result = JsonSerializer.Deserialize(json); if (result is null) diff --git a/Not-Copy-Copy/Not-Copy-Copy.csproj b/Not-Copy-Copy/Not-Copy-Copy.csproj index 0876809..fd3aac3 100644 --- a/Not-Copy-Copy/Not-Copy-Copy.csproj +++ b/Not-Copy-Copy/Not-Copy-Copy.csproj @@ -5,7 +5,7 @@ enable Exe win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Not.Copy.Copy @@ -34,22 +34,18 @@ - - - - - - - - - - + + + + + + + + - - - - - + + + diff --git a/Not-Copy-Copy/appsettings.Development.json b/Not-Copy-Copy/appsettings.Development.json index 9f02cb9..63023c3 100644 --- a/Not-Copy-Copy/appsettings.Development.json +++ b/Not-Copy-Copy/appsettings.Development.json @@ -50,7 +50,7 @@ "WorkingDirectoryName": "PharesApps", "Windows": { "Configuration": { - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "FileNameDirectorySeparator": ".Z.", "ForcePropertyLastWriteTimeToCreationTime": false, "MaxImagesInDirectoryForTopLevelFirstPass": 10, @@ -83,8 +83,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/PrepareForOld/Models/Binder/AppSettings.cs b/PrepareForOld/Models/Binder/AppSettings.cs index 8fbc37d..b5f8b4b 100644 --- a/PrepareForOld/Models/Binder/AppSettings.cs +++ b/PrepareForOld/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/PrepareForOld/Models/Stateless/Configuration.cs b/PrepareForOld/Models/Stateless/Configuration.cs index 232ba10..61f3c47 100644 --- a/PrepareForOld/Models/Stateless/Configuration.cs +++ b/PrepareForOld/Models/Stateless/Configuration.cs @@ -13,7 +13,7 @@ public abstract class Configuration 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? configuration = configurationSection.Get(); string json = JsonSerializer.Serialize(configuration, new JsonSerializerOptions() { WriteIndented = true }); result = JsonSerializer.Deserialize(json); if (result is null) diff --git a/PrepareForOld/PrepareForOld.cs b/PrepareForOld/PrepareForOld.cs index ea47183..c311fed 100644 --- a/PrepareForOld/PrepareForOld.cs +++ b/PrepareForOld/PrepareForOld.cs @@ -148,6 +148,7 @@ public class PrepareForOld List dateTimes; string fileNameWithoutExtension; string firstFileSegmentCollection; + DateTime? dateTimeFromName = null; Dictionary keyValuePairs = new(); Models.SaveTabSeparatedValues.IndexInfo[]? indexCollection; List exifCollection = GetExifCollection(infoDirectory, infoDirectoryExtra, checkDistinct); @@ -156,7 +157,7 @@ public class PrepareForOld indexInfoFiles.AddRange(Directory.GetFiles(infoDirectoryExtra, "IndexInfo.json", SearchOption.AllDirectories)); foreach (Models.SaveTabSeparatedValues.ImageExifInfo exifInfo in exifCollection) { - dateTimes = Shared.Models.Stateless.Methods.IProperty.GetDateTimes(exifInfo.CreationTime, exifInfo.LastWriteTime, exifInfo.DateTime, exifInfo.DateTimeDigitized, exifInfo.DateTimeOriginal, exifInfo.GPSDateStamp); + dateTimes = Shared.Models.Stateless.Methods.IProperty.GetDateTimes(exifInfo.CreationTime, exifInfo.LastWriteTime, exifInfo.DateTime, dateTimeFromName, exifInfo.DateTimeDigitized, exifInfo.DateTimeOriginal, exifInfo.GPSDateStamp); if (!checkDistinct && keyValuePairs.ContainsKey(exifInfo.Index)) continue; keyValuePairs.Add(exifInfo.Index, dateTimes.Min().Ticks); diff --git a/PrepareForOld/PrepareForOld.csproj b/PrepareForOld/PrepareForOld.csproj index a94034b..4fba30a 100644 --- a/PrepareForOld/PrepareForOld.csproj +++ b/PrepareForOld/PrepareForOld.csproj @@ -5,7 +5,7 @@ enable Exe win-x64 - net6.0 + net7.0 Phares.View.by.Distance.PrepareForOld @@ -34,18 +34,18 @@ - - - - - + + + + + - - - - - - + + + + + + diff --git a/PrepareForOld/appsettings.Development.json b/PrepareForOld/appsettings.Development.json index 03bb81a..e5a94cb 100644 --- a/PrepareForOld/appsettings.Development.json +++ b/PrepareForOld/appsettings.Development.json @@ -50,7 +50,7 @@ "WorkingDirectoryName": "PharesApps", "Windows": { "Configuration": { - "DateGroup": "2022-10-23", + "DateGroup": "2022-11-12", "FileNameDirectorySeparator": ".Z.", "ForcePropertyLastWriteTimeToCreationTime": false, "KeepFullPath": false, @@ -108,8 +108,6 @@ "ValidMetadataExtensions": [ ".3gp", ".3GP", - ".amr", - ".AMR", ".avi", ".AVI", ".bmp", diff --git a/Property-Compare/Property-Compare.csproj b/Property-Compare/Property-Compare.csproj index 9dbbf7e..ad3ee1d 100644 --- a/Property-Compare/Property-Compare.csproj +++ b/Property-Compare/Property-Compare.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Property.Compare @@ -34,12 +34,10 @@ - - - - - - + + + + diff --git a/Property/Models/A_Property.cs b/Property/Models/A_Property.cs index 343a99e..6af00cb 100644 --- a/Property/Models/A_Property.cs +++ b/Property/Models/A_Property.cs @@ -8,7 +8,6 @@ using System.Text; using System.Text.Json; using View_by_Distance.Property.Models.Stateless; using View_by_Distance.Shared.Models; -using View_by_Distance.Shared.Models.Properties; using View_by_Distance.Shared.Models.Stateless; namespace View_by_Distance.Property.Models; @@ -63,41 +62,9 @@ public class A_Property return result; } - public static List GetMetadataDateTimesByPattern(string dateTimeFormat, string filteredSourceDirectoryFile) - { - List results = new(); - try - { - DateTime checkDateTime; - DateTime kristy = new(1976, 3, 8); - IReadOnlyList directories = MetadataExtractor.ImageMetadataReader.ReadMetadata(filteredSourceDirectoryFile); - foreach (MetadataExtractor.Directory directory in directories) - { - foreach (MetadataExtractor.Tag tag in directory.Tags) - { - if (string.IsNullOrEmpty(tag.Description) || tag.Description.Length != dateTimeFormat.Length) - continue; - if (!DateTime.TryParseExact(tag.Description, dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out checkDateTime)) - continue; - if (checkDateTime < kristy) - continue; - results.Add(checkDateTime); - } - } - } - catch (Exception) { } - return results; - } - - public static List GetMetadataDateTimesByPattern(string dateTimeFormat, IFileHolder filteredSourceDirectoryFileHolder) - { - List results = GetMetadataDateTimesByPattern(dateTimeFormat, filteredSourceDirectoryFileHolder.FullName); - return results; - } - #pragma warning disable CA1416 - private Shared.Models.Property GetImageProperty(IFileHolder fileHolder, Shared.Models.Property? property, bool populateId, bool isIgnoreExtension, bool isValidImageFormatExtension, bool isValidMetadataExtensions, int? id, List indices) + private Shared.Models.Property GetImageProperty(FileHolder fileHolder, Shared.Models.Property? property, bool populateId, bool isIgnoreExtension, bool isValidImageFormatExtension, bool isValidMetadataExtensions, int? id, List indices) { Shared.Models.Property result; if (_Log is null) @@ -119,10 +86,11 @@ public class A_Property DateTime? dateTimeOriginal = null; string orientation = string.Empty; DateTime? dateTimeDigitized = null; + DateTime? dateTimeFromName = Shared.Models.Stateless.Methods.IProperty.GetDateTimeFromName(fileHolder); if (!isValidImageFormatExtension && isValidMetadataExtensions && fileHolder.Exists) { dateTimeFormat = "ddd MMM dd HH:mm:ss yyyy"; - List dateTimes = GetMetadataDateTimesByPattern(dateTimeFormat, fileHolder); + List dateTimes = Shared.Models.Stateless.Methods.IProperty.GetMetadataDateTimesByPattern(dateTimeFormat, fileHolder); if (dateTimes.Any()) dateTimeOriginal = dateTimes.Min(); } @@ -257,9 +225,9 @@ public class A_Property if (fileHolder.LastWriteTime is null && property?.LastWriteTime is null) throw new NullReferenceException(nameof(fileHolder.LastWriteTime)); if (fileHolder.CreationTime is not null && fileHolder.LastWriteTime is not null) - result = new(fileHolder.CreationTime.Value, dateTime, dateTimeDigitized, dateTimeOriginal, fileLength, gpsDateStamp, height, id, indices.ToArray(), fileHolder.LastWriteTime.Value, make, model, orientation, width); + result = new(fileHolder.CreationTime.Value, dateTime, dateTimeDigitized, dateTimeFromName, dateTimeOriginal, fileLength, gpsDateStamp, height, id, indices.ToArray(), fileHolder.LastWriteTime.Value, make, model, orientation, width); else if (property is not null) - result = new(property.CreationTime, dateTime, dateTimeDigitized, dateTimeOriginal, fileLength, gpsDateStamp, height, id, indices.ToArray(), property.LastWriteTime, make, model, orientation, width); + result = new(property.CreationTime, dateTime, dateTimeDigitized, dateTimeFromName, dateTimeOriginal, fileLength, gpsDateStamp, height, id, indices.ToArray(), property.LastWriteTime, make, model, orientation, width); else throw new NullReferenceException(nameof(property)); return result; @@ -270,8 +238,6 @@ public class A_Property private Shared.Models.Property GetPropertyOfPrivate(Item item, List> sourceDirectoryFileTuples, List parseExceptions, bool isIgnoreExtension, bool isValidMetadataExtensions) { Shared.Models.Property? result; - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); string json; int? id = null; List indices = new(); @@ -288,7 +254,7 @@ public class A_Property fileInfo.Refresh(); } List dateTimes = (from l in sourceDirectoryFileTuples where changesFrom.Contains(l.Item1) select l.Item2).ToList(); - if (!fileInfo.Exists) + if (!fileInfo.FullName.Contains(_Configuration.ResultAllInOne) && !fileInfo.Exists) { if (fileInfo.Directory?.Parent is null) throw new Exception(); @@ -322,8 +288,6 @@ public class A_Property json = File.ReadAllText(fileInfo.FullName); try { - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); bool check = true; property = JsonSerializer.Deserialize(json); if (!isIgnoreExtension && item.ValidImageFormatExtension && ((populateId && property?.Id is null) || property?.Width is null || property?.Height is null)) @@ -389,8 +353,6 @@ public class A_Property } if (result is null) { - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); result = GetImageProperty(item.ImageFileHolder, property, populateId, isIgnoreExtension, item.ValidImageFormatExtension, isValidMetadataExtensions, id, indices); json = JsonSerializer.Serialize(result, _WriteIndentedJsonSerializerOptions); if (populateId && Shared.Models.Stateless.Methods.IPath.WriteAllText(fileInfo.FullName, json, updateDateWhenMatches: true, compareBeforeWrite: true)) @@ -436,7 +398,7 @@ public class A_Property DateTime directoryMaximumOfMinimumDateTime = DateTime.MinValue; foreach (Item item in items) { - if (!item.ValidImageFormatExtension || item.Property is null || item.ImageFileHolder is null || !item.ImageFileHolder.Exists) + if (!item.ValidImageFormatExtension || item.Property is null || !item.ImageFileHolder.Exists) continue; minimumDateTime = Shared.Models.Stateless.Methods.IProperty.GetMinimumDateTime(item.Property); if (minimumDateTime > directoryMaximumOfMinimumDateTime) @@ -520,8 +482,6 @@ public class A_Property private void SavePropertyParallelForWork(string sourceDirectory, List> sourceDirectoryFileTuples, List> sourceDirectoryChanges, Item item) { - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); Shared.Models.Property property; List parseExceptions = new(); bool isValidMetadataExtensions = _Configuration.ValidMetadataExtensions.Contains(item.ImageFileHolder.ExtensionLowered); @@ -529,7 +489,7 @@ public class A_Property string filteredSourceDirectoryFileExtensionLowered = Path.Combine(sourceDirectory, $"{item.ImageFileHolder.NameWithoutExtension}{item.ImageFileHolder.ExtensionLowered}"); if (item.ValidImageFormatExtension && item.ImageFileHolder.FullName.Length == filteredSourceDirectoryFileExtensionLowered.Length && item.ImageFileHolder.FullName != filteredSourceDirectoryFileExtensionLowered) File.Move(item.ImageFileHolder.FullName, filteredSourceDirectoryFileExtensionLowered); - if (item.Changed is null || item.Changed.Value || item.Property is null) + if (item.FileSizeChanged is null || item.FileSizeChanged.Value || item.LastWriteTimeChanged is null || item.LastWriteTimeChanged.Value || item.Property is null) { property = GetPropertyOfPrivate(item, sourceDirectoryFileTuples, parseExceptions, isIgnoreExtension, isValidMetadataExtensions); lock (sourceDirectoryChanges) @@ -568,19 +528,28 @@ public class A_Property }); } - private void SetAngleBracketCollection(string sourceDirectory) + public void SetAngleBracketCollection(string aResultsFullGroupDirectory, string sourceDirectory) { AngleBracketCollection.Clear(); AngleBracketCollection.AddRange(IResult.GetDirectoryInfoCollection(_Configuration, sourceDirectory, - nameof(A_Property), - string.Empty, - includeResizeGroup: false, - includeModel: false, - includePredictorModel: false, + aResultsFullGroupDirectory, contentDescription: string.Empty, singletonDescription: "Properties for each image", - collectionDescription: string.Empty)); + collectionDescription: string.Empty, + converted: false)); + } + + public void SetAngleBracketCollection(string sourceDirectory) + { + AngleBracketCollection.Clear(); + string aResultsFullGroupDirectory = IResult.GetResultsFullGroupDirectory(_Configuration, + nameof(A_Property), + string.Empty, + includeResizeGroup: false, + includeModel: false, + includePredictorModel: false); + SetAngleBracketCollection(aResultsFullGroupDirectory, sourceDirectory); } public void SavePropertyParallelWork(long ticks, Shared.Models.Container[] containers) @@ -633,8 +602,6 @@ public class A_Property public Shared.Models.Property GetProperty(Item item, List> sourceDirectoryFileTuples, List parseExceptions) { Shared.Models.Property result; - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); bool angleBracketCollectionAny = AngleBracketCollection.Any(); if (!angleBracketCollectionAny) { diff --git a/Property/Models/Binder/Configuration.cs b/Property/Models/Binder/Configuration.cs index bf9a356..2e87105 100644 --- a/Property/Models/Binder/Configuration.cs +++ b/Property/Models/Binder/Configuration.cs @@ -37,9 +37,11 @@ public class Configuration return result; } - private static Models.Configuration Get(Configuration configuration) + private static Models.Configuration Get(Configuration? configuration) { Models.Configuration result; + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); if (configuration.ForcePropertyLastWriteTimeToCreationTime is null) throw new NullReferenceException(nameof(configuration.ForcePropertyLastWriteTimeToCreationTime)); if (configuration.MaxImagesInDirectoryForTopLevelFirstPass is null) @@ -58,16 +60,11 @@ public class Configuration throw new NullReferenceException(nameof(configuration.ResultSingleton)); if (configuration.WriteBitmapDataBytes is null) throw new NullReferenceException(nameof(configuration.WriteBitmapDataBytes)); - if (configuration.IgnoreExtensions is null) - configuration.IgnoreExtensions = Array.Empty(); - if (configuration.PropertyContentCollectionFiles is null) - configuration.PropertyContentCollectionFiles = Array.Empty(); - if (configuration.ValidImageFormatExtensions is null) - configuration.ValidImageFormatExtensions = Array.Empty(); - if (configuration.ValidMetadataExtensions is null) - configuration.ValidMetadataExtensions = Array.Empty(); - if (configuration.VerifyToSeason is null) - configuration.VerifyToSeason = Array.Empty(); + configuration.IgnoreExtensions ??= Array.Empty(); + configuration.PropertyContentCollectionFiles ??= Array.Empty(); + configuration.ValidImageFormatExtensions ??= Array.Empty(); + configuration.ValidMetadataExtensions ??= Array.Empty(); + configuration.VerifyToSeason ??= Array.Empty(); result = new(configuration.DateGroup, configuration.FileNameDirectorySeparator, configuration.ForcePropertyLastWriteTimeToCreationTime.Value, @@ -92,7 +89,7 @@ public class Configuration public static Models.Configuration Get(IsEnvironment isEnvironment, IConfigurationRoot configurationRoot) { Models.Configuration result; - Configuration configuration; + Configuration? configuration; if (isEnvironment is null) configuration = configurationRoot.Get(); else diff --git a/Property/Models/Stateless/Container.cs b/Property/Models/Stateless/Container.cs index 7b8d1dc..7d3aa3c 100644 --- a/Property/Models/Stateless/Container.cs +++ b/Property/Models/Stateless/Container.cs @@ -150,13 +150,18 @@ public class Container private static Item GetNewItem(Configuration configuration, A_Property propertyLogic, string relativePath, FileHolder sourceDirectoryFileHolder) { Item result; - List parseExceptions = new(); Shared.Models.Property? property = null; - List> subFileTuples = new(); bool isValidImageFormatExtension = configuration.ValidImageFormatExtensions.Contains(sourceDirectoryFileHolder.ExtensionLowered); - Item item = new(sourceDirectoryFileHolder.FullName, relativePath, sourceDirectoryFileHolder, isValidImageFormatExtension, property, null, null); - property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions); - result = new(sourceDirectoryFileHolder.FullName, relativePath, sourceDirectoryFileHolder, isValidImageFormatExtension, property, null, null); + if (configuration.PopulatePropertyId) + result = new(sourceDirectoryFileHolder.FullName, relativePath, sourceDirectoryFileHolder, isValidImageFormatExtension, property, null, null, null); + else + { + List parseExceptions = new(); + List> subFileTuples = new(); + Item item = new(sourceDirectoryFileHolder.FullName, relativePath, sourceDirectoryFileHolder, isValidImageFormatExtension, property, null, null, null); + property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions); + result = new(sourceDirectoryFileHolder.FullName, relativePath, sourceDirectoryFileHolder, isValidImageFormatExtension, property, null, null, null); + } return result; } @@ -171,10 +176,12 @@ public class Container List items; string keyWithJson; string relativePath; + bool fileSizeChanged; FileHolder keyFileHolder; + bool lastWriteTimeChanged; bool isValidImageFormatExtension; - Shared.Models.Container container; List keySourceDirectories; + Shared.Models.Container container; Dictionary keyValuePairs = new(); Dictionary fileHolderKeyValuePairs = new(); length = configuration.RootDirectory.Length; @@ -205,7 +212,7 @@ public class Container continue; keySourceDirectories.Add(string.Concat(keyFileHolder.DirectoryName)); isValidImageFormatExtension = configuration.ValidImageFormatExtensions.Contains(keyFileHolder.ExtensionLowered); - item = new(sourceDirectoryFile, relativePath, keyFileHolder, isValidImageFormatExtension, property, true, null); + item = new(sourceDirectoryFile, relativePath, keyFileHolder, isValidImageFormatExtension, property, true, null, null); items.Add(item); } else @@ -218,11 +225,13 @@ public class Container continue; isValidImageFormatExtension = configuration.ValidImageFormatExtensions.Contains(keyFileHolder.ExtensionLowered); if (property?.Id is null || property?.Width is null || property?.Height is null) - item = new(sourceDirectoryFile, relativePath, keyFileHolder, isValidImageFormatExtension, property, false, null); - else if (configuration.PropertiesChangedForProperty || property.LastWriteTime != keyFileHolder.LastWriteTime || property.FileSize != keyFileHolder.Length) - item = new(sourceDirectoryFile, relativePath, keyFileHolder, isValidImageFormatExtension, property, false, true); + item = new(sourceDirectoryFile, relativePath, keyFileHolder, isValidImageFormatExtension, property, false, null, null); else - item = new(sourceDirectoryFile, relativePath, keyFileHolder, isValidImageFormatExtension, property, false, false); + { + fileSizeChanged = property.FileSize != keyFileHolder.Length; + lastWriteTimeChanged = configuration.PropertiesChangedForProperty || property.LastWriteTime != keyFileHolder.LastWriteTime; + item = new(sourceDirectoryFile, relativePath, keyFileHolder, isValidImageFormatExtension, property, false, fileSizeChanged, lastWriteTimeChanged); + } items.Add(item); } } @@ -239,6 +248,7 @@ public class Container foreach ((int g, string sourceDirectory, FileHolder[] sourceDirectoryFileHolderCollection) in fileHolderGroupCollection) { items = new(); + propertyLogic.SetAngleBracketCollection(sourceDirectory); foreach (FileHolder sourceDirectoryFileHolder in sourceDirectoryFileHolderCollection) { relativePath = Shared.Models.Stateless.Methods.IPath.GetRelativePath(sourceDirectoryFileHolder.FullName, length, forceExtensionToLower: true); diff --git a/Property/Property.csproj b/Property/Property.csproj index 7132761..39601ac 100644 --- a/Property/Property.csproj +++ b/Property/Property.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Property @@ -17,16 +17,13 @@ snupkg - + true - + true - + true @@ -43,14 +40,12 @@ - - - - - - - - + + + + + + diff --git a/Resize/Models/_C_Resize.cs b/Resize/Models/_C_Resize.cs index 6e5d047..a5945af 100644 --- a/Resize/Models/_C_Resize.cs +++ b/Resize/Models/_C_Resize.cs @@ -5,6 +5,8 @@ using System.Runtime.InteropServices; using System.Text; using System.Text.Json; using View_by_Distance.Metadata.Models; +using View_by_Distance.Property.Models.Stateless; +using View_by_Distance.Shared.Models; using View_by_Distance.Shared.Models.Stateless; namespace View_by_Distance.Resize.Models; @@ -64,6 +66,18 @@ public class C_Resize return result; } + public void SetAngleBracketCollection(Property.Models.Configuration configuration, string cResultsFullGroupDirectory, string sourceDirectory) + { + AngleBracketCollection.Clear(); + AngleBracketCollection.AddRange(IResult.GetDirectoryInfoCollection(configuration, + sourceDirectory, + cResultsFullGroupDirectory, + contentDescription: "Resized image", + singletonDescription: "Resize dimensions for each resolution", + collectionDescription: string.Empty, + converted: true)); + } + #pragma warning disable CA1416 public static (ImageCodecInfo imageCodecInfo, EncoderParameters encoderParameters, string filenameExtension) GetGifLowQuality() @@ -161,16 +175,12 @@ public class C_Resize } } - private byte[] SaveResizedSubfile3(Shared.Models.Item item, int[] resize, bool returnAndDoNotWrite, byte[] bytes) + private byte[] SaveResizedSubfile3(MappingFromItem mappingFromItem, int[] resize, bool returnAndDoNotWrite, byte[] bytes) { - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); - if (item.ResizedFileHolder is null) - throw new NullReferenceException(nameof(item.ResizedFileHolder)); byte[] results; Bitmap bitmap; int outputResolutionWidth = resize[_OutputResolutionWidthIndex]; - using Bitmap temp = new(item.ImageFileHolder.FullName, useIcm: false); + using Bitmap temp = new(mappingFromItem.ImageFileHolder.FullName, useIcm: false); int outputResolutionHeight = resize[_OutputResolutionHeightIndex]; PropertyItem[] propertyItems = temp.PropertyItems; int outputResolutionOrientation = resize[_OutputResolutionOrientationIndex]; @@ -211,21 +221,17 @@ public class C_Resize { results = Array.Empty(); CopyPropertyItems(bytes, propertyItems, bitmap); - bitmap.Save(item.ResizedFileHolder.FullName, _ImageCodecInfo, _EncoderParameters); + bitmap.Save(mappingFromItem.ResizedFileHolder.FullName, _ImageCodecInfo, _EncoderParameters); } bitmap.Dispose(); return results; } - private byte[] SaveResizedSubfile5(Shared.Models.Item item, int[] resize, bool returnAndDoNotWrite, byte[] bytes) + private byte[] SaveResizedSubfile5(MappingFromItem mappingFromItem, int[] resize, bool returnAndDoNotWrite, byte[] bytes) { - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); - if (item.ResizedFileHolder is null) - throw new NullReferenceException(nameof(item.ResizedFileHolder)); byte[] results; Bitmap bitmap; - using Bitmap temp = new(item.ImageFileHolder.FullName, useIcm: false); + using Bitmap temp = new(mappingFromItem.ImageFileHolder.FullName, useIcm: false); PropertyItem[] propertyItems = temp.PropertyItems; int tempResolutionWidth = resize[_TempResolutionWidth]; int tempResolutionHeight = resize[_TempResolutionHeight]; @@ -279,7 +285,7 @@ public class C_Resize { results = Array.Empty(); CopyPropertyItems(bytes, propertyItems, bitmap); - bitmap.Save(item.ResizedFileHolder.FullName, _ImageCodecInfo, _EncoderParameters); + bitmap.Save(mappingFromItem.ResizedFileHolder.FullName, _ImageCodecInfo, _EncoderParameters); } } bitmap.Dispose(); @@ -288,28 +294,26 @@ public class C_Resize #pragma warning restore CA1416 - private byte[] SaveResizedSubfile(Shared.Models.Item item, int[] resize, bool returnAndDoNotWrite) + private byte[] SaveResizedSubfile(Shared.Models.Property property, MappingFromItem mappingFromItem, int[] resize, bool returnAndDoNotWrite) { - if (item.Property is null) - throw new NullReferenceException(nameof(item.Property)); byte[] results; // string subFile, Shared.Models.Property property, Shared.Models.FileHolder? fileHolder string dateTimeFormat = Shared.Models.Stateless.Methods.IProperty.DateTimeFormat(); - DateTime dateTime = Shared.Models.Stateless.Methods.IProperty.GetMinimumDateTime(item.Property); + DateTime dateTime = Shared.Models.Stateless.Methods.IProperty.GetMinimumDateTime(property); string dateTimeValue = dateTime.ToString(dateTimeFormat); byte[] bytes = _ASCIIEncoding.GetBytes(dateTimeValue); if (_ASCIIEncoding.GetString(bytes, 0, bytes.Length) != dateTimeValue) throw new Exception(); if (resize.Length == 3) - results = SaveResizedSubfile3(item, resize, returnAndDoNotWrite, bytes); + results = SaveResizedSubfile3(mappingFromItem, resize, returnAndDoNotWrite, bytes); else if (resize.Length == 5) - results = SaveResizedSubfile5(item, resize, returnAndDoNotWrite, bytes); + results = SaveResizedSubfile5(mappingFromItem, resize, returnAndDoNotWrite, bytes); else throw new Exception(); return results; } - public byte[] GetResizedBytes(string outputResolution, string cResultsFullGroupDirectory, List> subFileTuples, Shared.Models.Item item, Dictionary imageResizes) + public byte[] GetResizedBytes(string outputResolution, string cResultsFullGroupDirectory, List> subFileTuples, Shared.Models.Property property, MappingFromItem mappingFromItem, Dictionary imageResizes) { byte[] results; if (!imageResizes.ContainsKey(outputResolution)) @@ -318,23 +322,19 @@ public class C_Resize int outputResolutionWidth = resize[_OutputResolutionWidthIndex]; int outputResolutionHeight = resize[_OutputResolutionHeightIndex]; int outputResolutionOrientation = resize[_OutputResolutionOrientationIndex]; - results = SaveResizedSubfile(item, resize, returnAndDoNotWrite: true); + results = SaveResizedSubfile(property, mappingFromItem, resize, returnAndDoNotWrite: true); subFileTuples.Add(new Tuple(nameof(C_Resize), DateTime.Now)); return results; } - public void SaveResizedSubfile(string outputResolution, string cResultsFullGroupDirectory, List> subFileTuples, Shared.Models.Item item, string original, Dictionary imageResizes) + public void SaveResizedSubfile(Property.Models.Configuration configuration, string outputResolution, string cResultsFullGroupDirectory, List> subFileTuples, Item item, Shared.Models.Property property, MappingFromItem mappingFromItem, string original, Dictionary imageResizes) { - if (item.Property is null) - throw new NullReferenceException(nameof(item.Property)); - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); - if (item.ResizedFileHolder is null) - throw new NullReferenceException(nameof(item.ResizedFileHolder)); + if (mappingFromItem.ResizedFileHolder is null) + throw new NullReferenceException(nameof(mappingFromItem.ResizedFileHolder)); if (!imageResizes.ContainsKey(outputResolution)) throw new Exception(); - FileInfo fileInfo = new(item.ResizedFileHolder.FullName); - if (!fileInfo.Exists) + FileInfo fileInfo = new(mappingFromItem.ResizedFileHolder.FullName); + if (!fileInfo.FullName.Contains(configuration.ResultAllInOne) && !fileInfo.Exists) { if (fileInfo.Directory?.Parent is null) throw new Exception(); @@ -342,7 +342,7 @@ public class C_Resize if (File.Exists(parentCheck)) { File.Move(parentCheck, fileInfo.FullName); - item.SetResizedFileHolder(_FileNameExtension, Shared.Models.Stateless.Methods.IFileHolder.Refresh(item.ResizedFileHolder)); + item.SetResizedFileHolder(_FileNameExtension, Shared.Models.Stateless.Methods.IFileHolder.Refresh(mappingFromItem.ResizedFileHolder)); fileInfo.Refresh(); } } @@ -355,8 +355,8 @@ public class C_Resize { if (!fileInfo.Exists) { - File.Copy(item.ImageFileHolder.FullName, fileInfo.FullName); - item.SetResizedFileHolder(_FileNameExtension, Shared.Models.Stateless.Methods.IFileHolder.Refresh(item.ResizedFileHolder)); + File.Copy(mappingFromItem.ImageFileHolder.FullName, fileInfo.FullName); + item.SetResizedFileHolder(_FileNameExtension, Shared.Models.Stateless.Methods.IFileHolder.Refresh(mappingFromItem.ResizedFileHolder)); subFileTuples.Add(new Tuple(nameof(C_Resize), DateTime.Now)); } } @@ -373,14 +373,14 @@ public class C_Resize check = true; if (check) { - _ = SaveResizedSubfile(item, resize, returnAndDoNotWrite: false); - item.SetResizedFileHolder(_FileNameExtension, Shared.Models.Stateless.Methods.IFileHolder.Refresh(item.ResizedFileHolder)); + _ = SaveResizedSubfile(property, mappingFromItem, resize, returnAndDoNotWrite: false); + item.SetResizedFileHolder(_FileNameExtension, Shared.Models.Stateless.Methods.IFileHolder.Refresh(mappingFromItem.ResizedFileHolder)); subFileTuples.Add(new Tuple(nameof(C_Resize), DateTime.Now)); } } } - private int[] GetCollection(string outputResolution) + private static int[] GetCollection(string outputResolution) { List results = new(); string[] segments = outputResolution.Split('x'); @@ -447,37 +447,30 @@ public class C_Resize return results; } - public Dictionary GetResizeKeyValuePairs(Property.Models.Configuration configuration, string cResultsFullGroupDirectory, List> subFileTuples, List parseExceptions, string original, List> metadataCollection, Shared.Models.Item item) + public FileHolder GetResizedFileHolder(Item item) + { + FileHolder result = new(Path.Combine(AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName))); + return result; + } + + public Dictionary GetResizeKeyValuePairs(Property.Models.Configuration configuration, string cResultsFullGroupDirectory, List> subFileTuples, List parseExceptions, string original, List> metadataCollection, Shared.Models.Property property, MappingFromItem mappingFromItem) { Dictionary results; - if (item.Property?.Id is null) - throw new NullReferenceException(nameof(item.Property.Id)); - if (item.ImageFileHolder is null) - throw new NullReferenceException(nameof(item.ImageFileHolder)); string json; string[] changesFrom = new string[] { nameof(Property.Models.A_Property), nameof(B_Metadata) }; List dateTimes = (from l in subFileTuples where changesFrom.Contains(l.Item1) select l.Item2).ToList(); - string usingRelativePath = Path.Combine(AngleBracketCollection[0].Replace("<>", "{}"), string.Concat(item.ImageFileHolder.NameWithoutExtension, ".json")); - string cResizeSingletonFile = Path.Combine(cResultsFullGroupDirectory, "{}", configuration.ResultAllInOne, $"{item.Property.Id.Value}{item.ImageFileHolder.ExtensionLowered}.json"); + string cResizeSingletonFile = Path.Combine(cResultsFullGroupDirectory, "{}", configuration.ResultAllInOne, $"{mappingFromItem.Id}{mappingFromItem.ImageFileHolder.ExtensionLowered}.json"); FileInfo fileInfo = new(cResizeSingletonFile); - if (!fileInfo.Exists) + if (!fileInfo.FullName.Contains(configuration.ResultAllInOne) && !fileInfo.Exists) { - if (File.Exists(usingRelativePath)) + if (fileInfo.Directory?.Parent is null) + throw new Exception(); + string parentCheck = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name); + if (File.Exists(parentCheck)) { - File.Move(usingRelativePath, fileInfo.FullName); + File.Move(parentCheck, fileInfo.FullName); fileInfo.Refresh(); } - if (!fileInfo.Exists) - { - if (fileInfo.Directory?.Parent is null) - throw new Exception(); - string parentCheck = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name); - if (File.Exists(parentCheck)) - { - File.Move(parentCheck, fileInfo.FullName); - fileInfo.Refresh(); - } - } } if (_ForceResizeLastWriteTimeToCreationTime && !fileInfo.Exists && File.Exists(Path.ChangeExtension(fileInfo.FullName, ".delete"))) { @@ -509,7 +502,7 @@ public class C_Resize results = keyValuePairs; if ((from l in results where l.Value[0] == l.Value[1] select true).Any()) { - results = GetImageResizes(item.Property, metadataCollection, original); + results = GetImageResizes(property, metadataCollection, original); if (!(from l in results where l.Value[0] == l.Value[1] select true).Any()) throw new Exception("Was square!"); } @@ -523,7 +516,7 @@ public class C_Resize } if (results is null || !results.Any()) { - results = GetImageResizes(item.Property, metadataCollection, original); + results = GetImageResizes(property, metadataCollection, original); json = JsonSerializer.Serialize(results, _WriteIndentedJsonSerializerOptions); bool updateDateWhenMatches = dateTimes.Any() && fileInfo.Exists && dateTimes.Max() > fileInfo.LastWriteTime; DateTime? dateTime = !updateDateWhenMatches ? null : dateTimes.Max(); @@ -539,8 +532,6 @@ public class C_Resize } } } - Shared.Models.FileHolder fileHolder = new(Path.Combine(AngleBracketCollection[0].Replace("<>", "()"), Path.GetFileName(item.ImageFileHolder.FullName))); - item.SetResizedFileHolder(_FileNameExtension, fileHolder); return results; } diff --git a/Resize/Resize.csproj b/Resize/Resize.csproj index fb947ff..d26cc67 100644 --- a/Resize/Resize.csproj +++ b/Resize/Resize.csproj @@ -5,7 +5,7 @@ enable library win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Resize @@ -34,12 +34,10 @@ - - - - - - + + + + diff --git a/Shared/Models/Face.cs b/Shared/Models/Face.cs index 7e2db58..039180d 100644 --- a/Shared/Models/Face.cs +++ b/Shared/Models/Face.cs @@ -13,7 +13,6 @@ public class Face : Properties.IFace protected readonly OutputResolution? _OutputResolution; protected Location? _Location; protected Mapping? _Mapping; - protected readonly string _RelativePath; public DateTime DateTime => _DateTime; public FaceDistance? FaceDistance => _FaceDistance; public FaceEncoding? FaceEncoding => _FaceEncoding; @@ -21,10 +20,9 @@ public class Face : Properties.IFace public Location? Location => _Location; public Mapping? Mapping => _Mapping; public OutputResolution? OutputResolution => _OutputResolution; - public string RelativePath => _RelativePath; [JsonConstructor] - public Face(DateTime dateTime, FaceDistance? faceDistance, FaceEncoding? faceEncoding, Dictionary? faceParts, Location? location, Mapping? mapping, OutputResolution? outputResolution, string relativePath) + public Face(DateTime dateTime, FaceDistance? faceDistance, FaceEncoding? faceEncoding, Dictionary? faceParts, Location? location, Mapping? mapping, OutputResolution? outputResolution) { _DateTime = dateTime; _FaceDistance = faceDistance; @@ -33,27 +31,26 @@ public class Face : Properties.IFace _Location = location; _Mapping = mapping; _OutputResolution = outputResolution; - _RelativePath = relativePath; } public Face(int locationDigits, int locationFactor, int facesCount, Face face) : - this(face.DateTime, null, face.FaceEncoding, face.FaceParts, face.Location, null, face.OutputResolution, face.RelativePath) + this(face.DateTime, null, face.FaceEncoding, face.FaceParts, face.Location, null, face.OutputResolution) { if (face.Location?.Confidence is not null && face.OutputResolution is not null) _Location = new(face.Location.Confidence, face.OutputResolution.Height, face.Location, locationDigits, locationFactor, face.OutputResolution.Width, facesCount); } - public Face(Property property, int outputResolutionWidth, int outputResolutionHeight, int outputResolutionOrientation, string relativePath, Location? location) : - this(DateTime.MinValue, null, null, null, location, null, null, relativePath) + public Face(Property property, int outputResolutionWidth, int outputResolutionHeight, int outputResolutionOrientation, Location? location) : + this(DateTime.MinValue, null, null, null, location, null, null) { DateTime?[] dateTimes; _OutputResolution = new(outputResolutionHeight, outputResolutionOrientation, outputResolutionWidth); - dateTimes = new DateTime?[] { property.CreationTime, property.LastWriteTime, property.DateTime, property.DateTimeDigitized, property.DateTimeOriginal, property.GPSDateStamp }; + dateTimes = new DateTime?[] { property.CreationTime, property.LastWriteTime, property.DateTime, property.DateTimeDigitized, property.DateTimeFromName, property.DateTimeOriginal, property.GPSDateStamp }; _DateTime = (from l in dateTimes where l.HasValue select l.Value).Min(); } public Face(Face face, int height, Location location, int locationDigits, int locationFactor, int width, int zCount) : - this(face.DateTime, face.FaceDistance, face.FaceEncoding, face.FaceParts, new(height, location, locationDigits, locationFactor, width, zCount), face.Mapping, face.OutputResolution, face.RelativePath) + this(face.DateTime, face.FaceDistance, face.FaceEncoding, face.FaceParts, new(height, location, locationDigits, locationFactor, width, zCount), face.Mapping, face.OutputResolution) { } public override string ToString() diff --git a/Shared/Models/FaceFileSystem.cs b/Shared/Models/FaceFileSystem.cs index a20728e..e36287f 100644 --- a/Shared/Models/FaceFileSystem.cs +++ b/Shared/Models/FaceFileSystem.cs @@ -144,9 +144,9 @@ public class FaceFileSystem : FileSystem, Properties.IFaceFileSystem faceHeight = face.Location.Bottom - face.Location.Top; confidence = face.Location.Confidence.ToString("00.000"); } - string? directoryName = Path.GetDirectoryName(face.RelativePath); - string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(face.RelativePath); - string sourceFullFileName = string.Concat(cResizeContent, face.RelativePath); + string? directoryName = Path.GetDirectoryName("face.RelativePath"); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension("face.RelativePath"); + string sourceFullFileName = string.Concat(cResizeContent, "face.RelativePath"); if (directoryName is null) throw new Exception(); string faceFullFileName = Path.Combine($"{dFacesContentDirectory}{directoryName}", fileNameWithoutExtension, $"{locationIndex} - {fileNameWithoutExtension}.png"); diff --git a/Shared/Models/Item.cs b/Shared/Models/Item.cs index 49525f0..0ac4886 100644 --- a/Shared/Models/Item.cs +++ b/Shared/Models/Item.cs @@ -7,9 +7,10 @@ public class Item : Properties.IItem { protected readonly bool? _Abandoned; - protected readonly bool? _Changed; protected List _Faces; - protected readonly FileHolder? _ImageFileHolder; + protected readonly bool? _FileSizeChanged; + protected readonly FileHolder _ImageFileHolder; + protected bool? _LastWriteTimeChanged; protected bool? _Moved; protected readonly bool? _NoJson; protected Property? _Property; @@ -18,9 +19,10 @@ public class Item : Properties.IItem protected readonly string _SourceDirectoryFile; protected bool _ValidImageFormatExtension; public bool? Abandoned => _Abandoned; - public bool? Changed => _Changed; public List Faces => _Faces; - public FileHolder? ImageFileHolder => _ImageFileHolder; + public bool? FileSizeChanged => _FileSizeChanged; + public FileHolder ImageFileHolder => _ImageFileHolder; + public bool? LastWriteTimeChanged => _LastWriteTimeChanged; public bool? Moved => _Moved; public bool? NoJson => _NoJson; public Property? Property => _Property; @@ -30,32 +32,25 @@ public class Item : Properties.IItem public bool ValidImageFormatExtension => _ValidImageFormatExtension; [JsonConstructor] - public Item(bool? abandoned, bool? changed, List faces, FileHolder? imageFileHolder, bool? moved, bool? noJson, Property? property, string relativePath, FileHolder? resizedFileHolder, string sourceDirectoryFile, bool validImageFormatExtension) + public Item(bool? abandoned, List faces, bool? fileSizeChanged, FileHolder imageFileHolder, bool? lastWriteTimeChanged, bool? moved, bool? noJson, Property? property, string relativePath, FileHolder? resizedFileHolder, string sourceDirectoryFile, bool validImageFormatExtension) { - _Abandoned = abandoned; - _Changed = changed; _Faces = faces; - _ImageFileHolder = imageFileHolder; _Moved = moved; _NoJson = noJson; _Property = property; + _Abandoned = abandoned; _RelativePath = relativePath; + _FileSizeChanged = fileSizeChanged; + _ImageFileHolder = imageFileHolder; _ResizedFileHolder = resizedFileHolder; _SourceDirectoryFile = sourceDirectoryFile; + _LastWriteTimeChanged = lastWriteTimeChanged; _ValidImageFormatExtension = validImageFormatExtension; } - public Item(string sourceDirectoryFile, string relativePath, FileHolder imageFileInfo, bool isValidImageFormatExtension, Property? property, bool? abandoned, bool? changed) + public Item(string sourceDirectoryFile, string relativePath, FileHolder imageFileInfo, bool validImageFormatExtension, Property? property, bool? abandoned, bool? fileSizeChanged, bool? lastWriteTimeChanged) : + this(abandoned, new(), fileSizeChanged, imageFileInfo, lastWriteTimeChanged, null, abandoned is null, property, relativePath, null, sourceDirectoryFile, validImageFormatExtension) { - _Faces = new(); - _Changed = changed; - _Property = property; - _Abandoned = abandoned; - _NoJson = abandoned is null; - _RelativePath = relativePath; - _ImageFileHolder = imageFileInfo; - _SourceDirectoryFile = sourceDirectoryFile; - _ValidImageFormatExtension = isValidImageFormatExtension; if (relativePath.EndsWith(".json")) throw new ArgumentException("Can not be a *.json file!"); if (imageFileInfo is not null && imageFileInfo.ExtensionLowered is ".json") @@ -63,7 +58,7 @@ public class Item : Properties.IItem } public Item(string sourceDirectoryFile, string relativePath, bool isValidImageFormatExtension) : - this(sourceDirectoryFile, relativePath, new(sourceDirectoryFile), isValidImageFormatExtension, null, null, null) + this(sourceDirectoryFile, relativePath, new(sourceDirectoryFile), isValidImageFormatExtension, null, null, null, null) { } public override string ToString() @@ -84,7 +79,7 @@ public class Item : Properties.IItem _ResizedFileHolder = fileHolder; } - public bool Any() => (_Abandoned.HasValue && _Abandoned.Value) || (_Changed.HasValue && _Changed.Value) || (_Moved.HasValue && _Moved.Value) || (_NoJson.HasValue && _NoJson.Value); + public bool Any() => (_Abandoned.HasValue && _Abandoned.Value) || (_FileSizeChanged.HasValue && _FileSizeChanged.Value) || (_LastWriteTimeChanged.HasValue && _LastWriteTimeChanged.Value) || (_Moved.HasValue && _Moved.Value) || (_NoJson.HasValue && _NoJson.Value); public void Update(Property property) => _Property = property; diff --git a/Shared/Models/Mapping.cs b/Shared/Models/Mapping.cs index c2226bf..c906660 100644 --- a/Shared/Models/Mapping.cs +++ b/Shared/Models/Mapping.cs @@ -30,6 +30,21 @@ public class MappingFromItem : Properties.IMappingFromItem return result; } + internal static MappingFromItem GetMappingFromItem(Item item, FileHolder? resizedFileHolder) + { + MappingFromItem result; + bool? isWrongYear; + DateTime minimumDateTime; + if (item.Property?.Id is null) + throw new NotSupportedException(); + if (resizedFileHolder is null) + throw new NotSupportedException(); + minimumDateTime = Stateless.Methods.IProperty.GetMinimumDateTime(item.Property); + (isWrongYear, _) = item.Property.IsWrongYear(item.ImageFileHolder, minimumDateTime); + result = new(item.Property.Id.Value, item.ImageFileHolder, isWrongYear, minimumDateTime, item.RelativePath, resizedFileHolder); + return result; + } + } public class MappingFromLocation : Properties.IMappingFromLocation diff --git a/Shared/Models/Properties/IFace.cs b/Shared/Models/Properties/IFace.cs index 8a37881..e99c1b1 100644 --- a/Shared/Models/Properties/IFace.cs +++ b/Shared/Models/Properties/IFace.cs @@ -9,6 +9,5 @@ public interface IFace public Dictionary? FaceParts { get; } public Mapping? Mapping { get; } public OutputResolution? OutputResolution { get; } - public string RelativePath { get; } } \ No newline at end of file diff --git a/Shared/Models/Properties/IItem.cs b/Shared/Models/Properties/IItem.cs index 4f48e82..3eee95b 100644 --- a/Shared/Models/Properties/IItem.cs +++ b/Shared/Models/Properties/IItem.cs @@ -4,9 +4,9 @@ public interface IItem { public bool? Abandoned { get; } - public bool? Changed { get; } + public bool? FileSizeChanged { get; } public List Faces { get; } - public FileHolder? ImageFileHolder { get; } + public FileHolder ImageFileHolder { get; } public bool? Moved { get; } public bool? NoJson { get; } public Property? Property { get; } diff --git a/Shared/Models/Properties/IProperty.cs b/Shared/Models/Properties/IProperty.cs index 25bf3c1..5049e11 100644 --- a/Shared/Models/Properties/IProperty.cs +++ b/Shared/Models/Properties/IProperty.cs @@ -6,6 +6,7 @@ public interface IProperty public DateTime CreationTime { get; } public DateTime? DateTime { get; } public DateTime? DateTimeDigitized { get; } + public DateTime? DateTimeFromName { get; } public DateTime? DateTimeOriginal { get; } public long FileSize { get; } public DateTime? GPSDateStamp { get; } diff --git a/Shared/Models/Property.cs b/Shared/Models/Property.cs index 62802c4..90b7fe6 100644 --- a/Shared/Models/Property.cs +++ b/Shared/Models/Property.cs @@ -9,6 +9,7 @@ public class Property : Properties.IProperty protected DateTime _CreationTime; protected DateTime? _DateTime; protected DateTime? _DateTimeDigitized; + protected DateTime? _DateTimeFromName; protected DateTime? _DateTimeOriginal; protected long _FileSize; protected DateTime? _GPSDateStamp; @@ -23,6 +24,7 @@ public class Property : Properties.IProperty public DateTime CreationTime => _CreationTime; public DateTime? DateTime => _DateTime; public DateTime? DateTimeDigitized => _DateTimeDigitized; + public DateTime? DateTimeFromName => _DateTimeFromName; public DateTime? DateTimeOriginal => _DateTimeOriginal; public long FileSize => _FileSize; public DateTime? GPSDateStamp => _GPSDateStamp; @@ -36,8 +38,9 @@ public class Property : Properties.IProperty public int? Width => _Width; [JsonConstructor] - public Property(DateTime creationTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeOriginal, long fileSize, DateTime? gpsDateStamp, int? height, int? id, int[] indices, DateTime lastWriteTime, string make, string model, string orientation, int? width) + public Property(DateTime creationTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeFromName, DateTime? dateTimeOriginal, long fileSize, DateTime? gpsDateStamp, int? height, int? id, int[] indices, DateTime lastWriteTime, string make, string model, string orientation, int? width) { + _DateTimeFromName = dateTimeFromName; _CreationTime = creationTime; _DateTime = dateTime; _DateTimeDigitized = dateTimeDigitized; @@ -60,7 +63,7 @@ public class Property : Properties.IProperty return result; } // ... - public List GetDateTimes() => Stateless.Methods.Property.GetDateTimes(_CreationTime, _LastWriteTime, _DateTime, _DateTimeDigitized, _DateTimeOriginal, _GPSDateStamp); + public List GetDateTimes() => Stateless.Methods.Property.GetDateTimes(_CreationTime, _LastWriteTime, _DateTime, _DateTimeDigitized, _DateTimeFromName, _DateTimeOriginal, _GPSDateStamp); public (bool?, string[]) IsWrongYear(FileHolder fileHolder, DateTime? minimumDateTime) { diff --git a/Shared/Models/Stateless/Methods/Face.cs b/Shared/Models/Stateless/Methods/Face.cs index 6958b7d..5d0b1db 100644 --- a/Shared/Models/Stateless/Methods/Face.cs +++ b/Shared/Models/Stateless/Methods/Face.cs @@ -45,7 +45,7 @@ internal abstract class Face foreach (JsonElement jsonElement in jsonElements) { tuple = JsonSerializer.Deserialize>(jsonElement.ToString()); - if (tuple is null || tuple.Item1 is null || string.IsNullOrEmpty(tuple.Item1.RelativePath)) + if (tuple is null || tuple.Item1 is null || string.IsNullOrEmpty("tuple.Item1.RelativePath")) continue; results.Add(tuple.Item1); if (maximum.HasValue && results.Count >= maximum) diff --git a/Shared/Models/Stateless/Methods/FaceFileSystem.cs b/Shared/Models/Stateless/Methods/FaceFileSystem.cs index 886d511..f8c16e1 100644 --- a/Shared/Models/Stateless/Methods/FaceFileSystem.cs +++ b/Shared/Models/Stateless/Methods/FaceFileSystem.cs @@ -59,10 +59,10 @@ internal abstract class FaceFileSystem if (face[i] is null) continue; locationIndex = 0; - directoryName = Path.GetDirectoryName(face[i].RelativePath); + directoryName = Path.GetDirectoryName("face[i].RelativePath"); if (directoryName is null) continue; - fileNameWithoutExtension = Path.GetFileNameWithoutExtension(face[i].RelativePath); + fileNameWithoutExtension = Path.GetFileNameWithoutExtension("face[i].RelativePath"); jsonFileName = string.Concat(locationIndex.Value, " - ", fileNameWithoutExtension, extension); eDistanceCollectionFileFullName = Path.Combine($"{tuple.E_DistanceCollectionDirectory}{directoryName}", fileNameWithoutExtension, jsonFileName); if (i == 0 && extension is ".json" && eDistanceCollectionFileFullName != selectedFileFullName) diff --git a/Shared/Models/Stateless/Methods/IMappingFromItem.cs b/Shared/Models/Stateless/Methods/IMappingFromItem.cs new file mode 100644 index 0000000..91932bc --- /dev/null +++ b/Shared/Models/Stateless/Methods/IMappingFromItem.cs @@ -0,0 +1,16 @@ +namespace View_by_Distance.Shared.Models.Stateless.Methods; + +public interface IMappingFromItem +{ // ... + + MappingFromItem TestStatic_GetMappingFromItem(Models.Item item, Models.FileHolder? resizedFileHolder) + => GetMappingFromItem(item, resizedFileHolder); + static MappingFromItem GetMappingFromItem(Models.Item item, Models.FileHolder? resizedFileHolder) + => MappingFromItem.GetMappingFromItem(item, resizedFileHolder); + + MappingFromItem TestStatic_GetMappingFromItem(Models.Item item) + => GetMappingFromItem(item); + static MappingFromItem GetMappingFromItem(Models.Item item) + => GetMappingFromItem(item, item.ResizedFileHolder); + +} \ No newline at end of file diff --git a/Shared/Models/Stateless/Methods/IPersonURL.cs b/Shared/Models/Stateless/Methods/IPersonURL.cs index ebd5355..6e83f50 100644 --- a/Shared/Models/Stateless/Methods/IPersonURL.cs +++ b/Shared/Models/Stateless/Methods/IPersonURL.cs @@ -3,9 +3,10 @@ namespace View_by_Distance.Shared.Models.Stateless.Methods; public interface IPersonURL { - string TestStatic_GetDefaultValue() => PersonURL.GetDefaultValue(); // <{1}>PluralValue - - static string GetDefaultValue() => PersonURL.GetDefaultValue(); // <{1}>PluralValue + string TestStatic_GetDefaultValue() => + GetDefaultValue(); // <{1}>PluralValue + static string GetDefaultValue() => + PersonURL.GetDefaultValue(); // <{1}>PluralValue // ... diff --git a/Shared/Models/Stateless/Methods/IProperty.cs b/Shared/Models/Stateless/Methods/IProperty.cs index fb0a499..3177ad7 100644 --- a/Shared/Models/Stateless/Methods/IProperty.cs +++ b/Shared/Models/Stateless/Methods/IProperty.cs @@ -6,56 +6,84 @@ public interface IProperty string TestStatic_DateTimeFormat(); static string DateTimeFormat() => "yyyy:MM:dd HH:mm:ss"; - int TestStatic_GetDeterministicHashCode(byte[] value); + int TestStatic_GetDeterministicHashCode(byte[] value) => + GetDeterministicHashCode(value); static int GetDeterministicHashCode(byte[] value) => Property.GetDeterministicHashCode(value); - int TestStatic_GetDeterministicHashCode(string value); + List TestStatic_GetMetadataDateTimesByPattern(string dateTimeFormat, Models.FileHolder fileHolder) => + GetMetadataDateTimesByPattern(dateTimeFormat, fileHolder); + static List GetMetadataDateTimesByPattern(string dateTimeFormat, Models.FileHolder fileHolder) => + Property.GetMetadataDateTimesByPattern(dateTimeFormat, fileHolder.FullName); + + int TestStatic_GetDeterministicHashCode(string value) => + GetDeterministicHashCode(value); static int GetDeterministicHashCode(string value) => Property.GetDeterministicHashCode(value); - DateTime TestStatic_GetDateTime(Models.Property? property); + DateTime TestStatic_GetDateTime(Models.Property? property) => + GetDateTime(property); static DateTime GetDateTime(Models.Property? property) => Property.GetDateTime(property); - DateTime TestStatic_GetMinimumDateTime(Models.Property? property); + DateTime TestStatic_GetMinimumDateTime(Models.Property? property) => + GetMinimumDateTime(property); static DateTime GetMinimumDateTime(Models.Property? property) => Property.GetMinimumDateTime(property); - (int Season, string seasonName) TestStatic_GetSeason(int dayOfYear); + (int Season, string seasonName) TestStatic_GetSeason(int dayOfYear) => + GetSeason(dayOfYear); static (int Season, string seasonName) GetSeason(int dayOfYear) => Property.GetSeason(dayOfYear); - string TestStatic_GetDiffRootDirectory(string diffPropertyDirectory); + string TestStatic_GetDiffRootDirectory(string diffPropertyDirectory) => + GetDiffRootDirectory(diffPropertyDirectory); static string GetDiffRootDirectory(string diffPropertyDirectory) => Property.GetDiffRootDirectory(diffPropertyDirectory); - bool TestStatic_Any(Models.Container[] propertyHolderCollections); + bool TestStatic_Any(Models.Container[] propertyHolderCollections) => + Any(propertyHolderCollections); static bool Any(Models.Container[] propertyHolderCollections) => Property.Any(propertyHolderCollections); - (bool?, string[]) TestStatic_IsWrongYear(string[] segments, string year); + (bool?, string[]) TestStatic_IsWrongYear(string[] segments, string year) => + IsWrongYear(segments, year); static (bool?, string[]) IsWrongYear(string[] segments, string year) => Property.IsWrongYear(segments, year); - List TestStatic_GetDateTimes(Models.Property property); - static List GetDateTimes(Models.Property property) => - Property.GetDateTimes(property.CreationTime, property.LastWriteTime, property.DateTime, property.DateTimeDigitized, property.DateTimeOriginal, property.GPSDateStamp); + (DateTime?, int?, string?) TestStatic_Get(Models.FileHolder fileHolder) => + Get(fileHolder); + static (DateTime?, int?, string?) Get(Models.FileHolder fileHolder) => + Property.Get(fileHolder); - double TestStatic_GetStandardDeviation(IEnumerable values, double average); + DateTime? TestStatic_GetDateTimeFromName(Models.FileHolder fileHolder) => + GetDateTimeFromName(fileHolder); + static DateTime? GetDateTimeFromName(Models.FileHolder fileHolder) => + Property.GetDateTimeFromName(fileHolder); + + List TestStatic_GetDateTimes(Models.Property property) => + GetDateTimes(property); + static List GetDateTimes(Models.Property property) => + Property.GetDateTimes(property.CreationTime, property.LastWriteTime, property.DateTime, property.DateTimeDigitized, property.DateTimeFromName, property.DateTimeOriginal, property.GPSDateStamp); + + double TestStatic_GetStandardDeviation(IEnumerable values, double average) => + GetStandardDeviation(values, average); static double GetStandardDeviation(IEnumerable values, double average) => Property.GetStandardDeviation(values, average); - TimeSpan TestStatic_GetThreeStandardDeviationHigh(int minimum, Models.Container container); + TimeSpan TestStatic_GetThreeStandardDeviationHigh(int minimum, Models.Container container) => + GetThreeStandardDeviationHigh(minimum, container); static TimeSpan GetThreeStandardDeviationHigh(int minimum, Models.Container container) => Property.GetThreeStandardDeviationHigh(minimum, container); - (int, List, List) TestStatic_Get(Models.Container container, TimeSpan threeStandardDeviationHigh, int i); + (int, List, List) TestStatic_Get(Models.Container container, TimeSpan threeStandardDeviationHigh, int i) => + Get(container, threeStandardDeviationHigh, i); static (int, List, List) Get(Models.Container container, TimeSpan threeStandardDeviationHigh, int i) => Property.Get(container, threeStandardDeviationHigh, i); - List TestStatic_GetDateTimes(DateTime creationTime, DateTime lastWriteTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeOriginal, DateTime? gpsDateStamp); - static List GetDateTimes(DateTime creationTime, DateTime lastWriteTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeOriginal, DateTime? gpsDateStamp) => - Property.GetDateTimes(creationTime, lastWriteTime, dateTime, dateTimeDigitized, dateTimeOriginal, gpsDateStamp); + List TestStatic_GetDateTimes(DateTime creationTime, DateTime lastWriteTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeFromName, DateTime? dateTimeOriginal, DateTime? gpsDateStamp) => + GetDateTimes(creationTime, lastWriteTime, dateTime, dateTimeDigitized, dateTimeFromName, dateTimeOriginal, gpsDateStamp); + static List GetDateTimes(DateTime creationTime, DateTime lastWriteTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeFromName, DateTime? dateTimeOriginal, DateTime? gpsDateStamp) => + Property.GetDateTimes(creationTime, lastWriteTime, dateTime, dateTimeDigitized, dateTimeFromName, dateTimeOriginal, gpsDateStamp); } \ No newline at end of file diff --git a/Shared/Models/Stateless/Methods/Index.cs b/Shared/Models/Stateless/Methods/Index.cs index 94befc5..9ce1f90 100644 --- a/Shared/Models/Stateless/Methods/Index.cs +++ b/Shared/Models/Stateless/Methods/Index.cs @@ -5,8 +5,7 @@ internal abstract class Index private static string GetJsonContains(string result, string jsonFileFullName, FileInfo fileInfo, string fileSegmentCollection) { - if (fileInfo is null) - fileInfo = new FileInfo(jsonFileFullName); + fileInfo ??= new FileInfo(jsonFileFullName); result = result.Replace(fileSegmentCollection, nameof(Properties.IIndex.RelativePaths)).Replace("\\\\", "/"); File.WriteAllText(fileInfo.FullName, result); File.SetLastWriteTime(fileInfo.FullName, fileInfo.LastWriteTime); @@ -15,8 +14,7 @@ internal abstract class Index private static string GetJsonSpecial(string result, string jsonFileFullName, FileInfo fileInfo) { - if (fileInfo is null) - fileInfo = new FileInfo(jsonFileFullName); + fileInfo ??= new FileInfo(jsonFileFullName); result = result.Replace("/u0", "\\u0"); File.WriteAllText(fileInfo.FullName, result); File.SetLastWriteTime(fileInfo.FullName, fileInfo.LastWriteTime); diff --git a/Shared/Models/Stateless/Methods/Item.cs b/Shared/Models/Stateless/Methods/Item.cs index da3096b..50b416e 100644 --- a/Shared/Models/Stateless/Methods/Item.cs +++ b/Shared/Models/Stateless/Methods/Item.cs @@ -10,15 +10,11 @@ internal abstract class Item List collection = new(); foreach (Models.Item item in itemsA) { - if (item.ImageFileHolder is null) - continue; results.Add(item); collection.Add(item.ImageFileHolder.FullName); } foreach (Models.Item item in itemsB) { - if (item.ImageFileHolder is null) - continue; if (collection.Contains(item.ImageFileHolder.FullName)) continue; result++; diff --git a/Shared/Models/Stateless/Methods/Property.cs b/Shared/Models/Stateless/Methods/Property.cs index 217692e..a0a73a4 100644 --- a/Shared/Models/Stateless/Methods/Property.cs +++ b/Shared/Models/Stateless/Methods/Property.cs @@ -1,3 +1,10 @@ +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; + namespace View_by_Distance.Shared.Models.Stateless.Methods; internal abstract class Property @@ -85,7 +92,46 @@ internal abstract class Property return new(result, results); } - internal static List GetDateTimes(DateTime creationTime, DateTime lastWriteTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeOriginal, DateTime? gpsDateStamp) + internal static DateTime? GetDateTimeFromName(Models.FileHolder fileHolder) + { + DateTime? result = null; + int length; + string format; + string fullFormat; + StringBuilder value = new(); + string[][] dateFormats = new string[][] + { + new string[] { string.Empty, "yyyyMMdd_HHmmss", string.Empty }, + new string[] { string.Empty, "yyyy-MM-dd HH.mm.ss", string.Empty }, + new string[] { string.Empty, "yyyyMMdd_HHmmss", "_LLS" }, + new string[] { string.Empty, "yyyyMMdd_HHmmss", "_HDR" }, + new string[] { "IMG_", "yyyyMMdd_HHmmss", string.Empty }, + new string[] { "IMG#####-", "yyyyMMdd-HHmm", string.Empty }, + new string[] { "CameraZOOM-", "yyyyMMddHHmmss", string.Empty }, + new string[] { "VideoCapture_", "yyyyMMdd-HHmmss ", string.Empty } + }; + foreach (string[] dateFormat in dateFormats) + { + _ = value.Clear(); + fullFormat = string.Join(string.Empty, dateFormat); + if (fileHolder.NameWithoutExtension.Length != fullFormat.Length) + continue; + format = dateFormat[1]; + length = dateFormat[0].Length + dateFormat[1].Length; + for (int i = dateFormat[0].Length; i < length; i++) + _ = value.Append(fileHolder.NameWithoutExtension[i]); + if (value.Length != format.Length) + continue; + if (DateTime.TryParseExact(value.ToString(), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime checkDateTime)) + { + result = checkDateTime; + break; + } + } + return result; + } + + internal static List GetDateTimes(DateTime creationTime, DateTime lastWriteTime, DateTime? dateTime, DateTime? dateTimeDigitized, DateTime? dateTimeFromName, DateTime? dateTimeOriginal, DateTime? gpsDateStamp) { List results = new() { @@ -96,6 +142,8 @@ internal abstract class Property results.Add(dateTime.Value); if (dateTimeDigitized.HasValue) results.Add(dateTimeDigitized.Value); + if (dateTimeFromName.HasValue) + results.Add(dateTimeFromName.Value); if (dateTimeOriginal.HasValue) results.Add(dateTimeOriginal.Value); if (gpsDateStamp.HasValue) @@ -119,6 +167,8 @@ internal abstract class Property dateTimes.Add(property.DateTime.Value); if (property.DateTimeDigitized.HasValue) dateTimes.Add(property.DateTimeDigitized.Value); + if (property.DateTimeFromName.HasValue) + dateTimes.Add(property.DateTimeFromName.Value); if (property.DateTimeOriginal.HasValue) dateTimes.Add(property.DateTimeOriginal.Value); if (property.GPSDateStamp.HasValue) @@ -269,4 +319,119 @@ internal abstract class Property return result; } + internal static List GetMetadataDateTimesByPattern(string dateTimeFormat, string sourceDirectoryFile) + { + List results = new(); + try + { + DateTime checkDateTime; + DateTime kristy = new(1976, 3, 8); + IReadOnlyList directories = MetadataExtractor.ImageMetadataReader.ReadMetadata(sourceDirectoryFile); + foreach (MetadataExtractor.Directory directory in directories) + { + foreach (MetadataExtractor.Tag tag in directory.Tags) + { + if (string.IsNullOrEmpty(tag.Description) || tag.Description.Length != dateTimeFormat.Length) + continue; + if (!DateTime.TryParseExact(tag.Description, dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out checkDateTime)) + continue; + if (checkDateTime < kristy) + continue; + results.Add(checkDateTime); + } + } + } + catch (Exception) { } + return results; + } + +#pragma warning disable CA1416 + + internal static (DateTime?, int?, string?) Get(Models.FileHolder fileHolder) + { + byte[] bytes; + string value; + int? id = null; + DateTime checkDateTime; + string? message = null; + DateTime? dateTime = null; + PropertyItem? propertyItem; + DateTime? gpsDateStamp = null; + DateTime? dateTimeOriginal = null; + DateTime? dateTimeDigitized = null; + ASCIIEncoding asciiEncoding = new(); + string dateTimeFormat = IProperty.DateTimeFormat(); + try + { + using Image image = Image.FromFile(fileHolder.FullName); + using Bitmap bitmap = new(image); + Rectangle rectangle = new(0, 0, image.Width, image.Height); + BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, bitmap.PixelFormat); + IntPtr intPtr = bitmapData.Scan0; + int length = bitmapData.Stride * bitmap.Height; + bytes = new byte[length]; + Marshal.Copy(intPtr, bytes, 0, length); + bitmap.UnlockBits(bitmapData); + id = IProperty.GetDeterministicHashCode(bytes); + if (image.PropertyIdList.Contains((int)IExif.Tags.DateTime)) + { + propertyItem = image.GetPropertyItem((int)IExif.Tags.DateTime); + if (propertyItem?.Value is not null) + { + value = asciiEncoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1); + if (value.Length > dateTimeFormat.Length) + value = value[..dateTimeFormat.Length]; + if (value.Length == dateTimeFormat.Length && DateTime.TryParseExact(value, dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out checkDateTime)) + dateTime = checkDateTime; + } + } + if (image.PropertyIdList.Contains((int)IExif.Tags.DateTimeDigitized)) + { + propertyItem = image.GetPropertyItem((int)IExif.Tags.DateTimeDigitized); + if (propertyItem?.Value is not null) + { + value = asciiEncoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1); + if (value.Length > dateTimeFormat.Length) + value = value[..dateTimeFormat.Length]; + if (value.Length == dateTimeFormat.Length && DateTime.TryParseExact(value, dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out checkDateTime)) + dateTimeDigitized = checkDateTime; + } + } + if (image.PropertyIdList.Contains((int)IExif.Tags.DateTimeOriginal)) + { + propertyItem = image.GetPropertyItem((int)IExif.Tags.DateTimeOriginal); + if (propertyItem?.Value is not null) + { + value = asciiEncoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1); + if (value.Length > dateTimeFormat.Length) + value = value[..dateTimeFormat.Length]; + if (value.Length == dateTimeFormat.Length && DateTime.TryParseExact(value, dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out checkDateTime)) + dateTimeOriginal = checkDateTime; + } + } + if (image.PropertyIdList.Contains((int)IExif.Tags.GPSDateStamp)) + { + propertyItem = image.GetPropertyItem((int)IExif.Tags.GPSDateStamp); + if (propertyItem?.Value is not null) + { + value = asciiEncoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1); + if (value.Length > dateTimeFormat.Length) + value = value[..dateTimeFormat.Length]; + if (value.Length == dateTimeFormat.Length && DateTime.TryParseExact(value, dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out checkDateTime)) + gpsDateStamp = checkDateTime; + } + } + bitmap.Dispose(); + image.Dispose(); + } + catch (Exception) + { + message = string.Concat(new StackFrame().GetMethod()?.Name, " <", fileHolder.FullName, ">"); + } + DateTime?[] dateTimes = new DateTime?[] { fileHolder.LastWriteTime, fileHolder.CreationTime, dateTime, dateTimeDigitized, dateTimeOriginal, gpsDateStamp }; + return new(dateTimes.Min(), id, message); + } + +#pragma warning restore CA1416 + } \ No newline at end of file diff --git a/Shared/Phares/Shared/RijndaelEncryption.cs b/Shared/Phares/Shared/RijndaelEncryption.cs index bcfc898..1293927 100644 --- a/Shared/Phares/Shared/RijndaelEncryption.cs +++ b/Shared/Phares/Shared/RijndaelEncryption.cs @@ -1,4 +1,5 @@ #pragma warning disable SYSLIB0022 +#pragma warning disable SYSLIB0041 using System.Security.Cryptography; using System.Text; diff --git a/Shared/View-by-Distance.Shared.csproj b/Shared/View-by-Distance.Shared.csproj index 4043237..50047bb 100644 --- a/Shared/View-by-Distance.Shared.csproj +++ b/Shared/View-by-Distance.Shared.csproj @@ -4,7 +4,7 @@ 10.0 enable win-x64 - net6.0 + net7.0 Phares.View.by.Distance.Shared @@ -33,8 +33,8 @@ - - - + + + \ No newline at end of file diff --git a/Tests/Models/Binder/AppSettings.cs b/Tests/Models/Binder/AppSettings.cs index 2167e26..55a8982 100644 --- a/Tests/Models/Binder/AppSettings.cs +++ b/Tests/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/Tests/Models/Binder/Configuration.cs b/Tests/Models/Binder/Configuration.cs index c9627e5..52c3a14 100644 --- a/Tests/Models/Binder/Configuration.cs +++ b/Tests/Models/Binder/Configuration.cs @@ -60,9 +60,11 @@ public class Configuration return result; } - private static Models.Configuration Get(Configuration configuration) + private static Models.Configuration Get(Configuration? configuration) { Models.Configuration result; + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); if (configuration.CheckDFaceAndUpWriteDates is null) throw new NullReferenceException(nameof(configuration.CheckDFaceAndUpWriteDates)); if (configuration.CheckJsonForDistanceResults is null) @@ -81,10 +83,8 @@ public class Configuration throw new NullReferenceException(nameof(configuration.IgnoreExtensions)); if (configuration.IgnoreRelativePaths is null) throw new NullReferenceException(nameof(configuration.IgnoreRelativePaths)); - if (configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions = Array.Empty(); - if (configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = Array.Empty(); + configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions ??= Array.Empty(); + configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions ??= Array.Empty(); if (configuration.LoadOrCreateThenSaveIndex is null) throw new NullReferenceException(nameof(configuration.LoadOrCreateThenSaveIndex)); if (configuration.MixedYearRelativePaths is null) @@ -115,16 +115,13 @@ public class Configuration throw new NullReferenceException(nameof(configuration.PropertiesChangedForResize)); if (configuration.Reverse is null) throw new NullReferenceException(nameof(configuration.Reverse)); - if (configuration.SaveFaceLandmarkForOutputResolutions is null) - configuration.SaveFaceLandmarkForOutputResolutions = Array.Empty(); + configuration.SaveFaceLandmarkForOutputResolutions ??= Array.Empty(); if (configuration.SaveFullYearOfRandomFiles is null) throw new NullReferenceException(nameof(configuration.SaveFullYearOfRandomFiles)); - if (configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions is null) - configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions = Array.Empty(); + configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions ??= Array.Empty(); if (configuration.SaveResizedSubfiles is null) throw new NullReferenceException(nameof(configuration.SaveResizedSubfiles)); - if (configuration.SaveShortcutsForOutputResolutions is null) - configuration.SaveShortcutsForOutputResolutions = Array.Empty(); + configuration.SaveShortcutsForOutputResolutions ??= Array.Empty(); if (configuration.SkipSearch is null) throw new NullReferenceException(nameof(configuration.SkipSearch)); if (configuration.TestDistanceResults is null) @@ -178,7 +175,7 @@ public class Configuration public static Models.Configuration Get(IsEnvironment isEnvironment, IConfigurationRoot configurationRoot, Property.Models.Configuration propertyConfiguration) { Models.Configuration result; - Configuration configuration; + Configuration? configuration; if (isEnvironment is null) configuration = configurationRoot.Get(); else diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 565c681..5211145 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -5,7 +5,7 @@ 10.0 enable win-x64 - net6.0 + net7.0 trx @@ -27,18 +27,18 @@ Linux - - - - - - - - - - + + + + + + + + + + - + diff --git a/Tests/UnitTestIsEnvironment.cs b/Tests/UnitTestIsEnvironment.cs index 086b28b..da8f3e2 100644 --- a/Tests/UnitTestIsEnvironment.cs +++ b/Tests/UnitTestIsEnvironment.cs @@ -59,7 +59,7 @@ public class UnitTestIsEnvironment List jsonFiles = new(); foreach (IConfigurationProvider configurationProvider in _ConfigurationRoot.Providers) { - if (configurationProvider is not JsonConfigurationProvider jsonConfigurationProvider) + if (configurationProvider is not JsonConfigurationProvider jsonConfigurationProvider || jsonConfigurationProvider.Source.Path is null) continue; jsonFiles.Add(jsonConfigurationProvider.Source.Path); } diff --git a/Tests/UnitTestResize.cs b/Tests/UnitTestResize.cs index 958c513..81fb848 100644 --- a/Tests/UnitTestResize.cs +++ b/Tests/UnitTestResize.cs @@ -98,6 +98,7 @@ public class UnitTestResize string sourceDirectoryName = "Halloween 2006"; Item item; bool reverse = false; + FileHolder resizedFileHolder; string original = "Original"; string aResultsFullGroupDirectory; string bResultsFullGroupDirectory; @@ -125,45 +126,29 @@ public class UnitTestResize (ImageCodecInfo imageCodecInfo, EncoderParameters encoderParameters, string filenameExtension) = C_Resize.GetTuple(_Configuration.OutputExtension, _Configuration.OutputQuality); C_Resize resize = new(_Configuration.ForceResizeLastWriteTimeToCreationTime, _Configuration.OverrideForResizeImages, _Configuration.PropertiesChangedForResize, _Configuration.ValidResolutions, imageCodecInfo, encoderParameters, filenameExtension); _ = resize.ToString(); - propertyLogic.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _PropertyConfiguration, - sourceDirectory, - aResultsFullGroupDirectory, - contentDescription: string.Empty, - singletonDescription: "Properties for each image", - collectionDescription: string.Empty, - converted: false)); - metadata.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _PropertyConfiguration, - sourceDirectory, - bResultsFullGroupDirectory, - contentDescription: string.Empty, - singletonDescription: "Metadata as key value pairs", - collectionDescription: string.Empty, - converted: true)); - resize.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _PropertyConfiguration, - sourceDirectory, - cResultsFullGroupDirectory, - contentDescription: "Resized image", - singletonDescription: "Resize dimensions for each resolution", - collectionDescription: string.Empty, - converted: true)); string sourceDirectoryFile = ".json"; FileHolder fileHolder = new(Path.Combine(sourceDirectory, sourceFileName)); string relativePath = IPath.GetRelativePath(fileHolder.FullName, length); sourceDirectory = Path.Combine(aPropertySingletonDirectory, sourceDirectoryName); - item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false); + propertyLogic.SetAngleBracketCollection(aResultsFullGroupDirectory, sourceDirectory); + resize.SetAngleBracketCollection(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, sourceDirectory); + metadata.SetAngleBracketCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, sourceDirectory); + item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false, false); Assert.IsNotNull(item.ImageFileHolder); if (item.Property is null) { property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions); item.Update(property); } - (int _, metadataCollection) = metadata.GetMetadataCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, subFileTuples, parseExceptions, item); - imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item); - Assert.IsNotNull(item.ResizedFileHolder); - resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, imageResizeKeyValuePairs); + if (property is null || item.Property is null) + throw new NullReferenceException(nameof(property)); + resizedFileHolder = resize.GetResizedFileHolder(item); + item.SetResizedFileHolder(resize.FileNameExtension, resizedFileHolder); + MappingFromItem mappingFromItem = IMappingFromItem.GetMappingFromItem(item); + (int _, metadataCollection) = metadata.GetMetadataCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, subFileTuples, parseExceptions, mappingFromItem); + imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item.Property, mappingFromItem); + Assert.IsNotNull(mappingFromItem.ResizedFileHolder); + resize.SaveResizedSubfile(_Configuration.PropertyConfiguration, outputResolution, cResultsFullGroupDirectory, subFileTuples, item, item.Property, mappingFromItem, original, imageResizeKeyValuePairs); } } \ No newline at end of file diff --git a/TestsWithFaceRecognitionDotNet/Models/Binder/AppSettings.cs b/TestsWithFaceRecognitionDotNet/Models/Binder/AppSettings.cs index 2167e26..55a8982 100644 --- a/TestsWithFaceRecognitionDotNet/Models/Binder/AppSettings.cs +++ b/TestsWithFaceRecognitionDotNet/Models/Binder/AppSettings.cs @@ -20,10 +20,10 @@ public class AppSettings return result; } - private static Models.AppSettings Get(AppSettings appSettings) + private static Models.AppSettings Get(AppSettings? appSettings) { Models.AppSettings result; - if (appSettings.MaxDegreeOfParallelism is null) + if (appSettings?.MaxDegreeOfParallelism is null) throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism)); result = new( appSettings.Company, @@ -36,7 +36,7 @@ public class AppSettings public static Models.AppSettings Get(IConfigurationRoot configurationRoot) { Models.AppSettings result; - AppSettings appSettings = configurationRoot.Get(); + AppSettings? appSettings = configurationRoot.Get(); result = Get(appSettings); return result; } diff --git a/TestsWithFaceRecognitionDotNet/Models/Binder/Configuration.cs b/TestsWithFaceRecognitionDotNet/Models/Binder/Configuration.cs index ee8a8b6..2c03aab 100644 --- a/TestsWithFaceRecognitionDotNet/Models/Binder/Configuration.cs +++ b/TestsWithFaceRecognitionDotNet/Models/Binder/Configuration.cs @@ -82,9 +82,11 @@ public class Configuration return result; } - private static Models.Configuration Get(Configuration configuration) + private static Models.Configuration Get(Configuration? configuration) { Models.Configuration result; + if (configuration is null) + throw new NullReferenceException(nameof(configuration)); if (configuration.CheckDFaceAndUpWriteDates is null) throw new NullReferenceException(nameof(configuration.CheckDFaceAndUpWriteDates)); if (configuration.CheckJsonForDistanceResults is null) @@ -115,10 +117,8 @@ public class Configuration throw new NullReferenceException(nameof(configuration.IgnoreExtensions)); if (configuration.IgnoreRelativePaths is null) throw new NullReferenceException(nameof(configuration.IgnoreRelativePaths)); - if (configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions = Array.Empty(); - if (configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions is null) - configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions = Array.Empty(); + configuration.LoadOrCreateThenSaveDistanceResultsForOutputResolutions ??= Array.Empty(); + configuration.LoadOrCreateThenSaveImageFacesResultsForOutputResolutions ??= Array.Empty(); if (configuration.LoadOrCreateThenSaveIndex is null) throw new NullReferenceException(nameof(configuration.LoadOrCreateThenSaveIndex)); if (configuration.LocationDigits is null) @@ -175,16 +175,13 @@ public class Configuration throw new NullReferenceException(nameof(configuration.RetryImagesWithoutAFace)); if (configuration.Reverse is null) throw new NullReferenceException(nameof(configuration.Reverse)); - if (configuration.SaveFaceLandmarkForOutputResolutions is null) - configuration.SaveFaceLandmarkForOutputResolutions = Array.Empty(); + configuration.SaveFaceLandmarkForOutputResolutions ??= Array.Empty(); if (configuration.SaveFullYearOfRandomFiles is null) throw new NullReferenceException(nameof(configuration.SaveFullYearOfRandomFiles)); - if (configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions is null) - configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions = Array.Empty(); + configuration.SaveResizedImagesByPersonKeyFormattedForOutputResolutions ??= Array.Empty(); if (configuration.SaveResizedSubfiles is null) throw new NullReferenceException(nameof(configuration.SaveResizedSubfiles)); - if (configuration.SaveShortcutsForOutputResolutions is null) - configuration.SaveShortcutsForOutputResolutions = Array.Empty(); + configuration.SaveShortcutsForOutputResolutions ??= Array.Empty(); if (configuration.SkipSearch is null) throw new NullReferenceException(nameof(configuration.SkipSearch)); if (configuration.SortingMaximumPerFaceShouldBeHigh is null) @@ -267,7 +264,7 @@ public class Configuration public static Models.Configuration Get(IsEnvironment isEnvironment, IConfigurationRoot configurationRoot, Property.Models.Configuration propertyConfiguration) { Models.Configuration result; - Configuration configuration; + Configuration? configuration; if (isEnvironment is null) configuration = configurationRoot.Get(); else diff --git a/TestsWithFaceRecognitionDotNet/TestsWithFaceRecognitionDotNet.csproj b/TestsWithFaceRecognitionDotNet/TestsWithFaceRecognitionDotNet.csproj index f89b138..bda122a 100644 --- a/TestsWithFaceRecognitionDotNet/TestsWithFaceRecognitionDotNet.csproj +++ b/TestsWithFaceRecognitionDotNet/TestsWithFaceRecognitionDotNet.csproj @@ -5,7 +5,7 @@ 10.0 enable win-x64 - net6.0 + net7.0 trx @@ -27,17 +27,17 @@ Linux - - - - - - - - - + + + + + + + + + - + diff --git a/TestsWithFaceRecognitionDotNet/UnitTestFace.cs b/TestsWithFaceRecognitionDotNet/UnitTestFace.cs index 0130d7d..d6689e6 100644 --- a/TestsWithFaceRecognitionDotNet/UnitTestFace.cs +++ b/TestsWithFaceRecognitionDotNet/UnitTestFace.cs @@ -172,6 +172,7 @@ public class UnitTestFace Item item; bool reverse = false; string original = "Original"; + FileHolder resizedFileHolder; string aResultsFullGroupDirectory; string bResultsFullGroupDirectory; string cResultsFullGroupDirectory; @@ -198,46 +199,30 @@ public class UnitTestFace (ImageCodecInfo imageCodecInfo, EncoderParameters encoderParameters, string filenameExtension) = C_Resize.GetTuple(_Configuration.OutputExtension, _Configuration.OutputQuality); C_Resize resize = new(_Configuration.ForceResizeLastWriteTimeToCreationTime, _Configuration.OverrideForResizeImages, _Configuration.PropertiesChangedForResize, _Configuration.ValidResolutions, imageCodecInfo, encoderParameters, filenameExtension); _ = resize.ToString(); - propertyLogic.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _PropertyConfiguration, - sourceDirectory, - aResultsFullGroupDirectory, - contentDescription: string.Empty, - singletonDescription: "Properties for each image", - collectionDescription: string.Empty, - converted: false)); - metadata.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _PropertyConfiguration, - sourceDirectory, - bResultsFullGroupDirectory, - contentDescription: string.Empty, - singletonDescription: "Metadata as key value pairs", - collectionDescription: string.Empty, - converted: true)); - resize.AngleBracketCollection.AddRange(Property.Models.Stateless.IResult.GetDirectoryInfoCollection( - _PropertyConfiguration, - sourceDirectory, - cResultsFullGroupDirectory, - contentDescription: "Resized image", - singletonDescription: "Resize dimensions for each resolution", - collectionDescription: string.Empty, - converted: true)); string sourceDirectoryFile = ".json"; FileHolder fileHolder = new(Path.Combine(sourceDirectory, sourceFileName)); string relativePath = IPath.GetRelativePath(fileHolder.FullName, length); sourceDirectory = Path.Combine(aPropertySingletonDirectory, sourceDirectoryName); - item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false); + propertyLogic.SetAngleBracketCollection(aResultsFullGroupDirectory, sourceDirectory); + resize.SetAngleBracketCollection(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, sourceDirectory); + metadata.SetAngleBracketCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, sourceDirectory); + item = new(sourceDirectoryFile, relativePath, fileHolder, isValidImageFormatExtension, property, false, false, false); Assert.IsNotNull(item.ImageFileHolder); if (item.Property is null) { property = propertyLogic.GetProperty(item, subFileTuples, parseExceptions); item.Update(property); } - (int _, metadataCollection) = metadata.GetMetadataCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, subFileTuples, parseExceptions, item); - imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item); - Assert.IsNotNull(item.ResizedFileHolder); - resize.SaveResizedSubfile(outputResolution, cResultsFullGroupDirectory, subFileTuples, item, original, imageResizeKeyValuePairs); - Image image = FaceRecognition.LoadImageFile(item.ResizedFileHolder.FullName); + if (property is null || item.Property is null) + throw new NullReferenceException(nameof(property)); + resizedFileHolder = resize.GetResizedFileHolder(item); + item.SetResizedFileHolder(resize.FileNameExtension, resizedFileHolder); + MappingFromItem mappingFromItem = IMappingFromItem.GetMappingFromItem(item); + (int _, metadataCollection) = metadata.GetMetadataCollection(_Configuration.PropertyConfiguration, bResultsFullGroupDirectory, subFileTuples, parseExceptions, mappingFromItem); + imageResizeKeyValuePairs = resize.GetResizeKeyValuePairs(_Configuration.PropertyConfiguration, cResultsFullGroupDirectory, subFileTuples, parseExceptions, original, metadataCollection, item.Property, mappingFromItem); + Assert.IsNotNull(mappingFromItem.ResizedFileHolder); + resize.SaveResizedSubfile(_Configuration.PropertyConfiguration, outputResolution, cResultsFullGroupDirectory, subFileTuples, item, item.Property, mappingFromItem, original, imageResizeKeyValuePairs); + Image image = FaceRecognition.LoadImageFile(mappingFromItem.ResizedFileHolder.FullName); Assert.IsNotNull(image); (Model model, PredictorModel predictorModel, ModelParameter modelParameter) = GetModel(_Configuration); FaceRecognition faceRecognition = new(_Configuration.NumberOfTimesToUpsample, _Configuration.NumberOfJitters, predictorModel, model, modelParameter); diff --git a/View-by-Distance-MKLink-Console.sln b/View-by-Distance-MKLink-Console.sln index 4491bbd..a66c5b4 100644 --- a/View-by-Distance-MKLink-Console.sln +++ b/View-by-Distance-MKLink-Console.sln @@ -37,8 +37,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Face", "Face\Face.csproj", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FaceParts", "FaceParts\FaceParts.csproj", "{919525B1-60BA-40C6-BA66-6F7F4C526E01}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Drag-Drop", "Drag-Drop\Drag-Drop.csproj", "{796F5B13-1E23-433F-8CBF-BF548AC4AF3F}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -116,9 +114,5 @@ Global {919525B1-60BA-40C6-BA66-6F7F4C526E01}.Debug|Any CPU.Build.0 = Debug|Any CPU {919525B1-60BA-40C6-BA66-6F7F4C526E01}.Release|Any CPU.ActiveCfg = Release|Any CPU {919525B1-60BA-40C6-BA66-6F7F4C526E01}.Release|Any CPU.Build.0 = Release|Any CPU - {796F5B13-1E23-433F-8CBF-BF548AC4AF3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {796F5B13-1E23-433F-8CBF-BF548AC4AF3F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {796F5B13-1E23-433F-8CBF-BF548AC4AF3F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {796F5B13-1E23-433F-8CBF-BF548AC4AF3F}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal