public static HttpClient GetHttpClientForVideo(TraceWriter log) { Tuple <HttpClient, PolicyWrap <HttpResponseMessage> > tuple = HttpClientList.GetOrAdd("video", new Tuple <HttpClient, PolicyWrap <HttpResponseMessage> >( new HttpClient(), FaceHelper.DefineAndRetrieveResiliencyStrategy(log))); return(tuple.Item1); }
public static async Task <bool> RunDetect(Guid requestID, string apis, string name, string source, Stream incomingPicture, string sourceContainerName, string resultContainerName, IAsyncCollector <object> outputItem, TraceWriter log, string videoName = null) { string apikey = string.Empty; try { string[] apiArr = apis.Split(','); int randomApi = FaceHelper.Instance.Next(0, apiArr.Length); apikey = apiArr[randomApi]; log.Info($"RunDetect request id: {requestID} apiKey: {apikey} ticks: {DateTime.Now.Ticks}"); Tuple <HttpClient, PolicyWrap <HttpResponseMessage> > tuple = FaceHelper.HttpClientList.GetOrAdd(apikey, new Tuple <HttpClient, PolicyWrap <HttpResponseMessage> >( new HttpClient(), FaceHelper.DefineAndRetrieveResiliencyStrategy(log))); HttpClient client = tuple.Item1; PolicyWrap <HttpResponseMessage> policy = tuple.Item2; IDatabase cache = FaceHelper.Connection.GetDatabase(int.Parse(FaceHelper.Connection.GetDatabase(1).StringGet(apikey))); //the large group id it's based on the mac address we get - each MAC address can work with different face api group string largegroupid = ConfigurationManager.AppSettings[source]; if (videoName == null) { log.Info($"Detecting {name} requestId: {requestID} apiKey: {apikey} ticks: {DateTime.Now.Ticks}"); } else { log.Info($"Detecting thumbnail {name} from {videoName} requestId: {requestID} apiKey: {apikey} ticks: {DateTime.Now.Ticks}"); } byte[] pictureImage; // Convert the incoming image stream to a byte array. using (var br = new BinaryReader(incomingPicture)) { pictureImage = br.ReadBytes((int)incomingPicture.Length); } var detectionResult = await new FaceDetect(log, client).DetectFaces(pictureImage, apikey, requestID, policy); if ((detectionResult != null) && (detectionResult.Length > 0)) { //prepare identify request int maxCandidate = int.Parse(ConfigurationManager.AppSettings["maxNumOfCandidatesReturned"]); double threshold = double.Parse(ConfigurationManager.AppSettings["confidenceThreshold"]); var identifyResquest = new FaceIdentifyRequest() { ConfidenceThreshold = threshold, MaxNumOfCandidatesReturned = maxCandidate, LargePersonGroupId = largegroupid, FaceIds = detectionResult.Select(s => s.FaceId).ToArray() }; var identifyResult = await new FaceIdentify(log, client).IdentifyFaces(identifyResquest, apikey, requestID, policy); if ((identifyResult == null) || (identifyResult.Length == 0)) { log.Info($"No identification result requestId: {requestID}, apiKey:{apikey} ticks: {DateTime.Now.Ticks}"); } var personResult = new PersonDetails(log, client); //merging results and find person name for (int i = 0; i < detectionResult.Length; i++) { if (videoName == null) { detectionResult[i].FaceBlobName = string.Concat(detectionResult[i].FaceId, "_", name); } else { detectionResult[i].FaceBlobName = videoName + "/" + name; } if ((identifyResult != null) && (identifyResult.Length > 0)) { detectionResult[i].Candidates = identifyResult[i].Candidates; for (int j = 0; j < detectionResult[i].Candidates.Length; j++) { string personid = detectionResult[i].Candidates[j].PersonId.ToString(); string personName = cache.StringGet(largegroupid + "-" + personid); if (string.IsNullOrEmpty(personName) == true) { log.Info($"Missing cache requestId: {requestID} apiKey: {apikey} personId: {personid} ticks: {DateTime.Now.Ticks}"); var tPerson = await personResult.GetPersonName(personid, apikey, largegroupid, requestID, policy); personName = tPerson.Name; cache.StringSet(largegroupid + "-" + personid, personName, null, When.Always); } detectionResult[i].Candidates[j].PersonName = new InternalPersonDetails() { PersonId = detectionResult[i].Candidates[j].PersonId, Name = personName }; } } } } else { log.Info($"No dectection result requestId: {requestID}, apiKey:{apikey} ticks: {DateTime.Now.Ticks}"); //in case of video, we want to create a link to the face detected by AMS (Azure Media Services) although face api didn't recognize it if (videoName != null) { detectionResult = new FaceDetectResult[1] { new FaceDetectResult() { FaceBlobName = videoName + "/" + name } } } ; } string blobname = videoName ?? name; var actionResult = new FaceIdentifyResult() { BlobName = blobname, ContainerName = sourceContainerName, ResultContainerName = resultContainerName, BlobLength = incomingPicture.Length, CreatedDateTime = DateTime.UtcNow, RequestId = requestID, ApiKey = apikey, LargeGroupId = largegroupid, Source = source, DetectResultList = detectionResult }; string strResult = JsonConvert.SerializeObject(actionResult); await outputItem.AddAsync(strResult); } catch (Exception ex) { log.Error($"Exception Message: {ex.Message}, requestId: {requestID}, apiKey:{apikey} ticks: {DateTime.Now.Ticks}", ex); return(false); } return(true); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { Guid requestID = Guid.NewGuid(); try { log.Info($"LoadPersonGroup was triggered request id {requestID}"); string largepersongroupid = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "groupid", true) == 0) .Value; if (largepersongroupid == null) { // Get request body dynamic data = await req.Content.ReadAsAsync <object>(); largepersongroupid = data?.groupid; } if (largepersongroupid != null) { string apis = ConfigurationManager.AppSettings["apis"]; string[] apiArr = apis.Split(','); if (apiArr.Length > 0) { _loadPersonClient = _loadPersonClient ?? new HttpClient(); PolicyWrap <HttpResponseMessage> resilientPolicy = FaceHelper.DefineAndRetrieveResiliencyStrategy(log); int i; //setting the map of api to database in database 1 IDatabase cache = Connection.GetDatabase(1); for (i = 1; i <= apiArr.Length; i++) { cache.StringSet(apiArr[i - 1], i + 1); } var personResult = new ListPersonGroup(log, _loadPersonClient); for (i = 1; i <= apiArr.Length; i++) { bool isComplete = false; string lastPerson = string.Empty; Task <InternalPersonDetails[]> task; List <InternalPersonDetails> personList = new List <InternalPersonDetails>(); cache = Connection.GetDatabase(i + 1); while (!isComplete) { task = personResult.GetListPersonGroup(lastPerson, apiArr[i - 1], largepersongroupid, requestID, resilientPolicy); task.Wait(); if (task.Result.Length < 1000) { isComplete = true; } if (task.Result.Length > 0) { lastPerson = task.Result[task.Result.Length - 1].PersonId.ToString(); personList.AddRange(task.Result.ToList()); } int loop = task.Result.Length / 100; var tmplist = task.Result.ToList(); int k = 0, len = 0; for (k = 0; k < loop; k++) { var tmpinnerlist = tmplist.GetRange(k * 100, 100); len += tmpinnerlist.Count; cache.StringSet(tmpinnerlist.Select(s => new KeyValuePair <RedisKey, RedisValue>(largepersongroupid + "-" + s.PersonId, s.Name)).ToArray(), When.Always); } if (tmplist.Count - len > 0) { var tmpinnerlist = tmplist.GetRange(k * 100, tmplist.Count - len); cache.StringSet(tmpinnerlist.Select(s => new KeyValuePair <RedisKey, RedisValue>(largepersongroupid + "-" + s.PersonId, s.Name)).ToArray(), When.Always); } } } return(req.CreateResponse(HttpStatusCode.OK, "Redis loaded successfully")); } else { string msg = "List of Api setting is empty"; log.Error($"Error-LoadPersonGroup: {msg} requestId: {requestID} ticks: {DateTime.Now.Ticks}"); return(req.CreateResponse(HttpStatusCode.BadRequest, "List of Api setting is empty")); } } else { string msg = "Please pass a large person group id on the query string or in the request body"; log.Error($"Error-LoadPersonGroup: {msg} requestId: {requestID} ticks: {DateTime.Now.Ticks}"); return(req.CreateResponse(HttpStatusCode.BadRequest, msg)); } } catch (Exception e) { log.Error($"Exception-LoadPersonGroup: {e.Message} requestId: {requestID} ticks: {DateTime.Now.Ticks}", e); return(req.CreateResponse(HttpStatusCode.BadRequest, e.Message)); } }