-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathDogDetector.cs
55 lines (50 loc) · 2.29 KB
/
DogDetector.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.Extensions.Logging;
namespace DogDemo.Function
{
public static class DogDetector
{
private static readonly List<VisualFeatureTypes> Features = new List<VisualFeatureTypes>
{
VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,
VisualFeatureTypes.Tags
};
// We must provide SAS token in order to have the API read the image located at the provided URL since our container is private
private static SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(10),
Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List
};
[FunctionName("DogDetector")]
public static async Task Run([BlobTrigger("images/{name}", Connection = "AzureWebJobsStorage")]CloudBlockBlob myBlob, string name, ILogger log)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
log.LogInformation($"Looking image {myBlob.Uri.ToString()}");
var visionAPI = new ComputerVisionClient(new ApiKeyServiceClientCredentials(config["ComputerVision:ApiKey"])) { Endpoint = config["ComputerVision:Endpoint"] };
var path = $"{myBlob.Uri.ToString()}{myBlob.GetSharedAccessSignature(sasConstraints)}";
var results = await visionAPI.AnalyzeImageAsync(path, Features);
if(IsDog(results))
{
log.LogInformation($"It's a Dog");
return;
}
log.LogInformation($"Not a Dog");
await myBlob.DeleteIfExistsAsync();
}
private static bool IsDog(ImageAnalysis image)
{
return image.Categories.Any(x => x.Name == "animal_dog") || image.Tags.Any(x => x.Name == "dog");
}
}
}