-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFaceGroupConfigurationService.cs
88 lines (75 loc) · 2.92 KB
/
FaceGroupConfigurationService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using Microsoft.Azure.CognitiveServices.Vision.Face;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace TagMyPhotos
{
public class FaceGroupConfigurationService
{
private IFaceClient faceClient;
public FaceGroupConfigurationService(IFaceClient faceClient)
{
this.faceClient = faceClient;
}
public async Task ConfigureGroups(string groupPath, string groupId)
{
await CreateGroupIfRequired(groupId);
await AddFacesToGroup(groupPath, groupId);
await TrainGroups(groupId);
}
private async Task CreateGroupIfRequired(string groupId)
{
Console.WriteLine("Creating Groups.");
try
{
await faceClient.PersonGroup.GetAsync(groupId);
}
catch (APIErrorException apiEx)
{
if (apiEx.Body.Error.Code == "PersonGroupNotFound")
{
await faceClient.PersonGroup.CreateAsync(groupId, groupId);
}
}
Console.WriteLine("Done Creating Groups.");
}
private async Task AddFacesToGroup(string groupPath, string groupId)
{
Console.WriteLine("Adding faces to group.");
IEnumerable<string> folders = Directory.EnumerateDirectories(groupPath);
foreach (var folderPath in folders)
{
await Task.Delay(250);
var personName = Path.GetFileName(folderPath).ToLower();
Person person = await faceClient.PersonGroupPerson.CreateAsync(groupId, personName);
var filePaths = Directory.GetFiles(folderPath);
foreach (var filePath in filePaths)
{
using (var imageStream = File.OpenRead(filePath))
{
await faceClient.PersonGroupPerson.AddFaceFromStreamAsync(groupId, person.PersonId, imageStream);
}
}
}
Console.WriteLine("Done adding faces to group.");
}
public async Task TrainGroups(string groupId)
{
Console.WriteLine("Training Groups.");
await faceClient.PersonGroup.TrainAsync(groupId);
while (true)
{
await Task.Delay(1000);
TrainingStatus traiiningStatus = await faceClient.PersonGroup.GetTrainingStatusAsync(groupId);
if (traiiningStatus.Status == TrainingStatusType.Succeeded)
break;
else if (traiiningStatus.Status == TrainingStatusType.Failed)
throw new Exception("Group Training Failed.");
Console.Write(".");
}
Console.WriteLine("Done Training Groups.");
}
}
}