public static void Run()
        {
            var configuration = new Configuration
            {
                AppSid = Common.MyAppSid,
                AppKey = Common.MyAppKey
            };

            var apiInstance = new ClassificationApi(configuration);

            try
            {
                var request = new ClassifyRequest(new BaseRequest()
                {
                    Document = new FileInfo()
                    {
                        Name   = "one-page.docx",
                        Folder = ""
                    },
                },
                                                  bestClassesCount: "3");

                // Get classification results
                ClassificationResponse response = apiInstance.Classify(request);
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling ClassificationApi: " + e.Message);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Calls classification service.
        /// </summary>
        /// <param name="modelInstanceUId">The model instance id.</param>
        /// <param name="data">Input data fields for classification model.</param>
        /// <returns>
        /// List of <see cref="ClassificationResult" />.
        /// </returns>
        public ClassificationOutput Classify(Guid modelInstanceUId, Dictionary <string, object> data)
        {
            ClassificationResponse response = Predict <ClassificationRequest, ClassificationResponse>(modelInstanceUId,
                                                                                                      new List <Dictionary <string, object> > {
                data
            }, ClassifyMethodName, ClassifyTimeoutSec, false);

            return(response.Outputs.FirstOrDefault());
        }
        public static ClassificationCompleteEventGridPayload Create(IEventStreamIdentity targetEntity,
                                                                    string classificationType,
                                                                    int asOfSequenceNumber,
                                                                    DateTime?asOfDate,
                                                                    ClassificationResponse response,
                                                                    Dictionary <string, object> parameters,
                                                                    string notificationId = @"",
                                                                    string commentary     = @"")
        {
            if (null == targetEntity)
            {
                throw new ArgumentNullException(nameof(targetEntity));
            }

            if (string.IsNullOrWhiteSpace(classificationType))
            {
                throw new ArgumentNullException(nameof(classificationType));
            }

            // Default the notification id if not are provided
            if (string.IsNullOrEmpty(notificationId))
            {
                notificationId = Guid.NewGuid().ToString("N");
            }

            ClassificationCompleteEventGridPayload ret = new ClassificationCompleteEventGridPayload()
            {
                DomainName             = targetEntity.DomainName,
                EntityTypeName         = targetEntity.EntityTypeName,
                InstanceKey            = targetEntity.InstanceKey,
                NotificationId         = notificationId,
                Commentary             = commentary,
                ClassificationTypeName = classificationType,
                SequenceNumber         = asOfSequenceNumber
            };

            if (asOfDate.HasValue)
            {
                ret.AsOfDate = asOfDate;
            }

            if (null != response)
            {
                ret.Result          = response.Result;
                ret.WasEverExcluded = response.WasEverExcluded;
                ret.WasEverIncluded = response.WasEverIncluded;
            }

            if (null != parameters)
            {
                // add them to the response
                ret.Parameters = parameters;
            }

            return(ret);
        }
 public Task ClassificationCompleted(IEventStreamIdentity targetEntity,
                                     string classificationType,
                                     Dictionary <string, object> parameters,
                                     int asOfSequenceNumber,
                                     DateTime?asOfDate,
                                     ClassificationResponse response,
                                     string commentary = "")
 {
     // do nothing
     return(Task.CompletedTask);
 }
        /// <summary>
        /// A classification has been requested in processing a query.
        /// This function will run it and attach the result back to the query
        /// event stream when complete.
        /// </summary>
        public static async Task RunClassificationForQuery(
            ClassifierRequestedEventGridEventData classifierRequestData)
        {
            if (classifierRequestData != null)
            {
                // handle the classifier request
                ClassificationResponse response   = null;
                Classification         classifier = new Classification(
                    new ClassificationAttribute(
                        classifierRequestData.ClassifierRequest.DomainName,
                        classifierRequestData.ClassifierRequest.EntityTypeName,
                        classifierRequestData.ClassifierRequest.InstanceKey,
                        classifierRequestData.ClassifierRequest.ClassifierTypeName
                        ));

                if (classifier != null)
                {
                    if (_classificationMap == null)
                    {
                        _classificationMap = ClassificationMaps.CreateDefaultClassificationMaps();
                    }
                    // get the classifier class - must implement TClassification : IClassification, new()
                    IClassification classificationToRun = _classificationMap.CreateClassificationClass(classifier.ClassifierTypeName);
                    if (classificationToRun != null)
                    {
                        response = await classifier.Classify(classificationToRun, null);
                    }
                }

                if (response != null)
                {
                    // and post the result back to the query that asked for it
                    Query qrySource = new Query(classifierRequestData.DomainName,
                                                classifierRequestData.EntityTypeName,
                                                classifierRequestData.InstanceKey);


                    if (qrySource != null)
                    {
                        await qrySource.PostClassifierResponse(classifierRequestData.ClassifierRequest.DomainName,
                                                               classifierRequestData.ClassifierRequest.EntityTypeName,
                                                               classifierRequestData.ClassifierRequest.InstanceKey,
                                                               classifierRequestData.ClassifierRequest.ClassifierTypeName,
                                                               response.AsOfDate,
                                                               classifierRequestData.ClassifierRequest.CorrelationIdentifier,
                                                               response.AsOfSequence,
                                                               response.Result
                                                               );
                    }
                }
            }
        }
Beispiel #6
0
        public static async Task OnQueryClassificationHandler([EventGridTrigger] EventGridEvent eventGridEvent)
        {
            if (eventGridEvent != null)
            {
                // Get the data from the event that describes what classification is requested
                ClassifierRequestedEventGridEventData classifierRequestData = eventGridEvent.Data as ClassifierRequestedEventGridEventData;
                if (classifierRequestData != null)
                {
                    // handle the classifier request
                    ClassificationResponse response   = null;
                    Classification         classifier = new Classification(
                        new ClassificationAttribute(
                            classifierRequestData.ClassifierRequest.DomainName,
                            classifierRequestData.ClassifierRequest.EntityTypeName,
                            classifierRequestData.ClassifierRequest.InstanceKey,
                            classifierRequestData.ClassifierRequest.ClassifierTypeName
                            ));

                    if (classifier != null)
                    {
                        // get the classifier class - must implement TClassification : IClassification, new()
                        IClassification classificationToRun = Classification.GetClassifierByName(classifier.ClassifierTypeName);
                        if (classificationToRun != null)
                        {
                            response = await classifier.Classify(classificationToRun, null);
                        }
                    }

                    if (response != null)
                    {
                        // and post the result back to the query that asked for it
                        Query qrySource = new Query(classifierRequestData.DomainName,
                                                    classifierRequestData.EntityTypeName,
                                                    classifierRequestData.InstanceKey);


                        if (qrySource != null)
                        {
                            await qrySource.PostClassifierResponse(classifierRequestData.ClassifierRequest.DomainName,
                                                                   classifierRequestData.ClassifierRequest.EntityTypeName,
                                                                   classifierRequestData.ClassifierRequest.InstanceKey,
                                                                   classifierRequestData.ClassifierRequest.ClassifierTypeName,
                                                                   response.AsOfDate,
                                                                   classifierRequestData.ClassifierRequest.CorrelationIdentifier,
                                                                   response.AsOfSequence,
                                                                   response.Result
                                                                   );
                        }
                    }
                }
            }
        }
        public async Task<IActionResult> Post(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest();
            }

            var fileName = $"{Guid.NewGuid()}_{ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"')}";
            var fullPath = Path.Combine(_scoringSvc.ImagesFolder, fileName);

            try
            {

                MemoryStream imageMemoryStream = new MemoryStream();
                await file.CopyToAsync(imageMemoryStream);

                //Convert to Bitmap
                Bitmap bitmapImage = (Bitmap)Image.FromStream(imageMemoryStream);

                //Set the specific image data into the ImageInputData type used in the DataView
                ImageInputData imageInputData = new ImageInputData { Image = bitmapImage };

                _logger.LogInformation($"Start processing image file { fullPath }");

                var scoring = _scoringSvc.Score(imageInputData);

                _logger.LogInformation($"Image processed");

                return Ok(ClassificationResponse.CreateFrom(scoring));
            }
            finally
            {
                try
                {
                    _logger.LogInformation($"Deleting Image {fullPath}");
                    System.IO.File.Delete(fullPath);
                }
                catch (Exception)
                {
                    _logger.LogInformation("Error deleting image: " + fileName);
                }
            }
        }
Beispiel #8
0
        public async Task<IActionResult> Post(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest();
            }

            var fileName = $"{Guid.NewGuid()}_{ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"')}";
            var fullPath = Path.Combine(_scoringSvc.ImagesFolder, fileName);

            try
            {
                using (var fs = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(fs);
                }

                _logger.LogInformation($"Start processing image file { fullPath }");

                var scoring = _scoringSvc.Score(fileName);

                _logger.LogInformation($"Image processed");

                return Ok(ClassificationResponse.CreateFrom(scoring));
            }
            finally
            {
                try
                {
                    _logger.LogInformation($"Deleting Image {fullPath}");
                    System.IO.File.Delete(fullPath);
                }
                catch (Exception)
                {
                    _logger.LogInformation("Error deleting image: " + fileName);
                }
            }
        }
Beispiel #9
0
        public async Task ClassificationCompleted(IEventStreamIdentity targetEntity,
                                                  string classificationType,
                                                  Dictionary <string, object> parameters,
                                                  int asOfSequenceNumber,
                                                  DateTime?asOfDate,
                                                  ClassificationResponse response,
                                                  string commentary = "")
        {
            string messageToSend = MakeMessageString(targetEntity,
                                                     NOTIFICATION_CLASSIFICATION,
                                                     classificationType,
                                                     asOfSequenceNumber,
                                                     asOfDate);

            string queueName = MakeQueueName(targetEntity);

            string connectionStringName = _eventStreamSettings.GetConnectionStringName(targetEntity);

            if (!string.IsNullOrWhiteSpace(queueName))
            {
                await SendQueueMessage(connectionStringName, queueName, messageToSend);
            }
        }
        public static async Task <Tuple <string, bool> > AccrueInterestForSpecificAccount
            ([ActivityTrigger] IDurableActivityContext accrueInterestContext)
        {
            const decimal DEBIT_INTEREST_RATE  = 0.001M;
            const decimal CREDIT_INTEREST_RATE = 0.0005M;

            string accountNumber = accrueInterestContext.GetInput <string>();

            #region Tracing telemetry
            Activity.Current.AddTag("Account Number", accountNumber);
            #endregion

            if (!string.IsNullOrEmpty(accountNumber))
            {
                EventStream bankAccountEvents = new EventStream(new EventStreamAttribute("Bank", "Account", accountNumber));
                if (await bankAccountEvents.Exists())
                {
                    // Has the accrual been done today for this account?
                    Classification         clsAccruedToday = new Classification(new ClassificationAttribute("Bank", "Account", accountNumber, nameof(InterestAccruedToday)));
                    ClassificationResponse isAccrued       = await clsAccruedToday.Classify <InterestAccruedToday>();

                    if (isAccrued.Result != ClassificationResponse.ClassificationResults.Include)
                    {
                        // Get the account balance
                        Projection prjBankAccountBalance = new Projection(new ProjectionAttribute("Bank", "Account", accountNumber, nameof(Balance)));

                        // Get the current account balance, as at midnight
                        Balance projectedBalance = await prjBankAccountBalance.Process <Balance>(DateTime.Today);

                        if (null != projectedBalance)
                        {
                            Account.Events.InterestAccrued evAccrued = new Account.Events.InterestAccrued()
                            {
                                Commentary           = $"Daily scheduled interest accrual",
                                AccrualEffectiveDate = DateTime.Today  // set the accrual to midnight today
                            };
                            // calculate the accrual amount
                            if (projectedBalance.CurrentBalance >= 0)
                            {
                                // Using the credit rate
                                evAccrued.AmountAccrued        = CREDIT_INTEREST_RATE * projectedBalance.CurrentBalance;
                                evAccrued.InterestRateInEffect = CREDIT_INTEREST_RATE;
                            }
                            else
                            {
                                // Use the debit rate
                                evAccrued.AmountAccrued        = DEBIT_INTEREST_RATE * projectedBalance.CurrentBalance;
                                evAccrued.InterestRateInEffect = DEBIT_INTEREST_RATE;
                            }

                            try
                            {
                                await bankAccountEvents.AppendEvent(evAccrued, isAccrued.AsOfSequence);
                            }
                            catch (EventSourcingOnAzureFunctions.Common.EventSourcing.Exceptions.EventStreamWriteException)
                            {
                                // We can't be sure this hasn't already run...
                                return(new Tuple <string, bool>(accountNumber, false));
                            }
                        }
                    }
                }
            }
            return(new Tuple <string, bool>(accountNumber, true));
        }
 public Task WriteSnapshot(ISnapshot snapshot, ClassificationResponse state)
 {
     throw new System.NotImplementedException();
 }
        public static async Task <HttpResponseMessage> AccrueInterestRun(
            [HttpTrigger(AuthorizationLevel.Function, "POST", Route = @"AccrueInterest/{accountnumber}")] HttpRequestMessage req,
            string accountnumber,
            [EventStream("Bank", "Account", "{accountnumber}")]  EventStream bankAccountEvents,
            [Projection("Bank", "Account", "{accountnumber}", nameof(Balance))] Projection prjBankAccountBalance,
            [Classification("Bank", "Account", "{accountnumber}", nameof(InterestAccruedToday))] Classification clsAccruedToday)
        {
            // Set the start time for how long it took to process the message
            DateTime startTime = DateTime.UtcNow;

            if (!await bankAccountEvents.Exists())
            {
                // You cannot accrue interest if the account does not exist
                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 true,
                                                                                                                 $"Account {accountnumber} does not exist",
                                                                                                                 0)));
            }

            ClassificationResponse isAccrued = await clsAccruedToday.Classify <InterestAccruedToday>();

            if (isAccrued.Result == ClassificationResponse.ClassificationResults.Include)
            {
                // The accrual for today has been performed for this account
                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 true,
                                                                                                                 $"Interest accrual already done on account {accountnumber} today",
                                                                                                                 isAccrued.AsOfSequence),
                                                                       FunctionResponse.MEDIA_TYPE
                                                                       ));
            }


            // get the request body...
            InterestAccrualData data = await req.Content.ReadAsAsync <InterestAccrualData>();

            // Get the current account balance, as at midnight
            Balance projectedBalance = await prjBankAccountBalance.Process <Balance>(DateTime.Today);

            if (null != projectedBalance)
            {
                Account.Events.InterestAccrued evAccrued = new Account.Events.InterestAccrued()
                {
                    Commentary           = data.Commentary,
                    AccrualEffectiveDate = DateTime.Today  // set the accrual to midnight today
                };

                if (projectedBalance.CurrentBalance >= 0)
                {
                    // Using the credit rate
                    evAccrued.AmountAccrued = data.CreditInterestRate * projectedBalance.CurrentBalance;
                }
                else
                {
                    // Use the debit rate
                    evAccrued.AmountAccrued = data.DebitInterestRate * projectedBalance.CurrentBalance;
                }

                try
                {
                    await bankAccountEvents.AppendEvent(evAccrued, isAccrued.AsOfSequence);
                }
                catch (EventSourcingOnAzureFunctions.Common.EventSourcing.Exceptions.EventStreamWriteException exWrite)
                {
                    return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                           ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                     true,
                                                                                                                     $"Failed to write interest accrual event {exWrite.Message}",
                                                                                                                     projectedBalance.CurrentSequenceNumber),
                                                                           FunctionResponse.MEDIA_TYPE));
                }

                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.OK,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 false,
                                                                                                                 $"Interest accrued for account {accountnumber} is {evAccrued.AmountAccrued}",
                                                                                                                 projectedBalance.CurrentSequenceNumber),
                                                                       FunctionResponse.MEDIA_TYPE));
            }
            else
            {
                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 true,
                                                                                                                 $"Unable to get current balance for account {accountnumber} for interest accrual",
                                                                                                                 0),
                                                                       FunctionResponse.MEDIA_TYPE
                                                                       ));
            }
        }