public Task Start(string[] rawData, FSharpFunc <int[], Observation> classifier)
        {
            var tasks = new List <Task <Observation> >();

            foreach (var imageString in rawData)
            {
                int   actual = imageString.Split(',').Select(x => Convert.ToInt32(x)).First();
                int[] ints   = imageString.Split(',').Select(x => Convert.ToInt32(x)).Skip(1).ToArray();

                var task = Task.Run <Observation>(() =>
                {
                    return(Recognizers.predict <Observation>(ints, classifier));
                }
                                                  );
                tasks.Add(task);
                task.ContinueWith(t =>
                {
                    CreateUIElements(t.Result.Label, actual.ToString(), imageString, DigitsBox);
                },
                                  TaskScheduler.FromCurrentSynchronizationContext()
                                  );
            }
            Task.WhenAny(tasks).ContinueWith(t => startTime = DateTime.Now);
            return(Task.CompletedTask);
        }
Example #2
0
        static void Main(string[] args)
        {
            Console.Clear();
            Console.WriteLine("Loading training data...");

            var log = new List <Prediction>();

            string fileName    = AppDomain.CurrentDomain.BaseDirectory + "train.csv";
            int    offset      = 9000;
            int    recordCount = 100;

            string[] rawTrain      = Loader.trainingReader(fileName, offset, recordCount);
            string[] rawValidation = Loader.validationReader(fileName, offset, recordCount);

            var classifier = Recognizers.manhattanClassifier(rawTrain);

            Console.Clear();
            var startTime = DateTime.Now;

            foreach (var imageString in rawValidation)
            {
                int   actual = imageString.Split(',').Select(x => Convert.ToInt32(x)).First();
                int[] ints   = imageString.Split(',').Select(x => Convert.ToInt32(x)).Skip(1).ToArray();

                // Call the CPU-intensive function
                var result = Recognizers.predict(ints, classifier);

                var prediction = new  Prediction {
                    prediction = result.Label, actual = actual.ToString(),
                    image      = ints, closestMatch = result.Pixels
                };

                // Display the result
                Console.SetCursorPosition(0, 0);
                WriteOutput(prediction);

                if (prediction.prediction != prediction.actual.ToString())
                {
                    log = LogError(log, prediction);
                }
            }

            var endTime = DateTime.Now;

            Console.Clear();
            Console.WriteLine("Press ENTER to view errors");
            Console.ReadLine();

            foreach (var pred in log)
            {
                WriteOutput(pred);
                Console.WriteLine("-------------------------------------");
            }
            Console.WriteLine($"Total Errors: {log.Count}");
            Console.WriteLine($"Start Time: {startTime}");
            Console.WriteLine($"End Time: {endTime}");
            Console.WriteLine($"Elapsed: {endTime - startTime:ss}");
            Console.WriteLine("\n\nEND END END END END END END END END");
            Console.ReadLine();
        }
        private async void GoButton_Click(object sender, RoutedEventArgs e)
        {
            LeftPanel.Children.Clear();
            RightPanel.Children.Clear();

            string fileName = AppDomain.CurrentDomain.BaseDirectory + "train.csv";

            int offset      = int.Parse(Offset.Text);
            int recordCount = int.Parse(RecordCount.Text);

            string[] rawTrain = await Task.Run(() => Loader.trainingReader(fileName, offset, recordCount));

            string[] rawValidation = await Task.Run(() => Loader.validationReader(fileName, offset, recordCount));

            var manhattanClassifier = Recognizers.manhattanClassifier(rawTrain);

            var manhattanRecognizer = new NonParallelRecognizerControl(
                "Single-Threaded Manhattan Classifier");

            LeftPanel.Children.Add(manhattanRecognizer);

            var parallelManhattanRecognizer = new ParallelRecognizerControl(
                "Parallel Manhattan Classifier");

            RightPanel.Children.Add(parallelManhattanRecognizer);

            MessageBox.Show("Ready to start non-parallel");
            await manhattanRecognizer.Start(rawValidation, manhattanClassifier);

            MessageBox.Show("Ready to start parallel");
            await parallelManhattanRecognizer.Start(rawValidation, manhattanClassifier);
        }
Example #4
0
 private RecognizerContext recognizectx;                  // REM 识别器上下文
 // Private myInkCollector As InkCollector
 // REM 初始化墨迹识别器
 public void InitRecognizer()
 {
     myRecognizers        = new Recognizers();
     strokes              = ink.CreateStrokes();
     recognizectx         = myRecognizers.GetDefaultRecognizer().CreateRecognizerContext();
     recognizectx.Strokes = strokes;
 }
Example #5
0
        private void ink_()
        {
            Recognizers recos       = new Recognizers();
            Recognizer  chineseReco = recos.GetDefaultRecognizer();

            rct = chineseReco.CreateRecognizerContext();
        }
        private async void GoButton_Click(object sender, RoutedEventArgs e)
        {
            LeftPanel.Children.Clear();
            RightPanel.Children.Clear();

            string fileName = AppDomain.CurrentDomain.BaseDirectory + "train.csv";

            int offset      = int.Parse(Offset.Text);
            int recordCount = int.Parse(RecordCount.Text);

            string[] rawTrain = await Task.Run(() => Loader.trainingReader(fileName, offset, recordCount));

            string[] rawValidation = await Task.Run(() => Loader.validationReader(fileName, offset, recordCount));

            var manhattanClassifier = Recognizers.manhattanClassifier(rawTrain);
            var euclideanClassifier = Recognizers.euclideanClassifier(rawTrain);

            var manhattanRecognizer = new ParallelRecognizerControl(
                "Manhattan Classifier", manhattanClassifier, rawValidation);

            LeftPanel.Children.Add(manhattanRecognizer);

            var euclideanRecognizer = new ParallelRecognizerControl(
                "Euclidean Classifier", euclideanClassifier, rawValidation);

            RightPanel.Children.Add(euclideanRecognizer);

            await manhattanRecognizer.Start();

            await euclideanRecognizer.Start();
        }
Example #7
0
        public CharacterRecognizer(InkCanvas canvas)
        {
            this.canvas = canvas;
            Recognizers systemRecognizers = new Recognizers();

            recognizer = systemRecognizers.GetDefaultRecognizer();
        }
        /// <summary>
        /// Event Handler from Form Load Event
        /// Setup the ink overlay for collection
        /// </summary>
        /// <param name="sender">The control that raised the event.</param>
        /// <param name="e">The event arguments.</param>
        private void InkDividerForm_Load(object sender, System.EventArgs e)
        {
            // Create the ink overlay and associate it with the form
            myInkOverlay = new Microsoft.Ink.InkOverlay(DrawArea.Handle);

            // Hook event handler for the Stroke event to myInkOverlay_Stroke.
            // This is necessary since the application needs to pass the strokes
            // to the ink divider.
            myInkOverlay.Stroke += new InkCollectorStrokeEventHandler(myInkOverlay_Stroke);

            // Hook the event handler for StrokeDeleting event to myInkOverlay_StrokeDeleting.
            // This is necessary as the application needs to remove the strokes from
            // ink divider object as well.
            myInkOverlay.StrokesDeleting += new InkOverlayStrokesDeletingEventHandler(myInkOverlay_StrokeDeleting);

            // Hook the event handler for StrokeDeleted event to myInkOverlay_StrokeDeleted.
            // This is necessary to update the layout analysis result when automatic layout analysis
            // option is selected.
            myInkOverlay.StrokesDeleted += new InkOverlayStrokesDeletedEventHandler(myInkOverlay_StrokeDeleted);

            // Create the ink divider object
            myInkDivider = new Divider();

            // Add a default recognizer context to the divider object
            // without adding the recognizer context, the divider would
            // not use a recognizer to do its word segmentation and would
            // have less accurate results.
            // Adding the recognizer context will slow down the call to
            // myInkDivider.Divide though.
            // It is possible that there is no recognizer installed on the
            // machine for this language. In that case the divider will
            // not use a recognizer to improve its accuracy.
            // Get the default recognizer if any
            try
            {
                Recognizers recognizers = new Recognizers();
                myInkDivider.RecognizerContext = recognizers.GetDefaultRecognizer().CreateRecognizerContext();
            }
            catch (InvalidOperationException)
            {
                //We are in the case where no default recognizers can be found
            }

            // The LineHeight property helps the InkDivider distinguish between
            // drawing and handwriting. The value should be the expected height
            // of the user's handwriting in ink space units (0.01mm).
            // Here we set the LineHeight to 840, which is about 1/3 of an inch.
            myInkDivider.LineHeight = 840;

            // Assign ink overlay's strokes collection to the ink divider
            // This strokes collection will be updated in the event handler
            myInkDivider.Strokes = myInkOverlay.Ink.Strokes;

            // Enable ink collection
            myInkOverlay.Enabled = true;

            // Set check for ink menu item
            miInk.Checked = true;
        }
        /// <summary>
        /// Iterate through each row of the form data and
        /// display the recognition results
        /// </summary>
        private void Recognize()
        {
            // Check to ensure that the user has at least one recognizer installed
            Recognizers inkRecognizers = new Recognizers();

            if (0 == inkRecognizers.Count)
            {
                MessageBox.Show(this, "There are no handwriting recognizers installed.  You need to have at least one in order to perform the recognition.");
            }
            else
            {
                StringBuilder buffer = new StringBuilder();

                // Iterate through the rows in the "FieldInfo" table
                foreach (DataRow row in formData.Tables["FieldInfo"].Rows)
                {
                    // get the metadata for the field
                    // Note that the DataSet contains a row for each field
                    // in the form.  It is assumed that the rows are in the
                    // same order as the fields in the form.  The DataSet
                    // has the following columns:
                    // Name:  the field's name
                    // Left, Top, Right, Bottom:  the coordinates of the field (in pixels)
                    string fieldname = (string)row["Name"];
                    Point  pt1       = new Point((int)row["Left"], (int)row["Top"]);
                    Point  pt2       = new Point((int)row["Right"], (int)row["Bottom"]);

                    using (Graphics g = CreateGraphics())
                    {
                        // Convert to ink space units
                        inkPicture1.Renderer.PixelToInkSpace(g, ref pt1);
                        inkPicture1.Renderer.PixelToInkSpace(g, ref pt2);
                    }

                    // the rectangle for the region
                    Rectangle rc = new Rectangle(pt1.X, pt1.Y, pt2.X - pt1.X, pt2.Y - pt1.Y);

                    // find the strokes that intersect and lie inside of the rectangle
                    Strokes strokes = inkPicture1.Ink.HitTest(rc, 70);

                    // recognize the handwriting
                    if (strokes.Count > 0)
                    {
                        buffer.Append(fieldname + " = " + strokes.ToString() + Environment.NewLine);
                    }
                }

                // Display the results
                if (buffer.Length > 0)
                {
                    MessageBox.Show(this, buffer.ToString());
                }
                else
                {
                    MessageBox.Show(this, "There aren't any recognition results.");
                }
            }
        }
        public async Task ScheduleGuildEvent(
            CommandContext context,
            [Description("The channel to announce the event in")]
            DiscordChannel announcementChannel,
            [Description("The role to announce the event to")]
            DiscordRole role,
            [Description("The date to schedule the event for")]
            [RemainingText]
            string datetimeString
            )
        {
            using IBotAccessProvider provider = this.accessBuilder.Build();

            if (!context.User.TryGetDateTimeZone(provider, this.timeZoneProvider, out DateTimeZone schedulerTimeZone))
            {
                await context.RespondAsync(StringConstants.NoTimeZoneErrorMessage);

                return;
            }

            DiscordMember botMember = await context.Guild.GetMemberAsync(context.Client.CurrentUser.Id);

            if (!announcementChannel.PermissionsFor(botMember).HasPermission(Permissions.SendMessages | Permissions.MentionEveryone))
            {
                await context.RespondAsync($"{context.Member.Mention}, I don't have permission to send messages and mention `@everyone` in that channel.");

                return;
            }

            LocalDateTime datetime = Recognizers.RecognizeDateTime(datetimeString, DateTimeV2Type.DateTime)
                                     .First().Values.Select(value => (LocalDateTime)value.Value).OrderBy(key => key).First();
            DiscordMessage msg = await context.RespondAsync($":wave: Hi, {context.User.Mention}! You want to schedule an event for {datetime:g} in your timezone?");

            InteractivityExtension interactivity = context.Client.GetInteractivity();
            Reaction reaction = await interactivity.AddAndWaitForYesNoReaction(msg, context.User);

            if (reaction != Reaction.Yes)
            {
                return;
            }

            DiscordEmbedBuilder scheduleEmbedBase = new DiscordEmbedBuilder()
                                                    .WithTitle("Select an event by typing: <event number>")
                                                    .WithColor(context.Member.Color);

            GuildEvent selectedEvent = await SelectPredefinedEvent(context, provider, msg, interactivity, scheduleEmbedBase);

            Instant      eventDateTime = datetime.InZoneStrictly(schedulerTimeZone).ToInstant();
            DiscordEmbed embed         = new DiscordEmbedBuilder()
                                         .WithAuthor(context.Member.DisplayName, iconUrl: context.Member.AvatarUrl)
                                         .WithDescription(selectedEvent.EventDesc)
                                         .WithTitle(selectedEvent.EventName)
                                         .Build();
            await msg.ModifyAsync($"You have scheduled the following event for {datetime:g} in your time zone to be output in the {announcementChannel.Mention} channel.", embed : embed);

            this.ScheduleEventsForRole(context, announcementChannel, provider, selectedEvent, eventDateTime, role);
        }
Example #11
0
 private void HandwritingPad_Load(object sender, EventArgs e)
 {
     ic = new InkCollector(PicInkPad.Handle);
     ic.Enabled = true;
     Recognizers recos = new Recognizers();
     Recognizer chineseReco = recos.GetDefaultRecognizer();
     rct = chineseReco.CreateRecognizerContext();
     rct.Strokes = ic.Ink.Strokes;
 }
Example #12
0
        private void HandwritingPad_Load(object sender, EventArgs e)
        {
            ic         = new InkCollector(PicInkPad.Handle);
            ic.Enabled = true;
            Recognizers recos       = new Recognizers();
            Recognizer  chineseReco = recos.GetDefaultRecognizer();

            rct         = chineseReco.CreateRecognizerContext();
            rct.Strokes = ic.Ink.Strokes;
        }
Example #13
0
        private void ink_Here()
        {
            Recognizers recos       = new Recognizers();
            Recognizer  chineseReco = recos.GetDefaultRecognizer();

            rct = chineseReco.CreateRecognizerContext();
            rct.RecognitionFlags = Microsoft.Ink.RecognitionModes.WordMode;

            this.rct.RecognitionWithAlternates += new RecognizerContextRecognitionWithAlternatesEventHandler(rct_RecognitionWithAlternates);
        }
Example #14
0
        /// <summary>
        /// Event Handler from Form Load Event
        /// Setup the ink collector for collection
        /// </summary>
        /// <param name="sender">The control that raised the event.</param>
        /// <param name="e">The event arguments.</param>
        private void InkRecognition_Load(object sender, System.EventArgs e)
        {
            // Create the recognizers collection
            myRecognizers = new Recognizers();

            // Create a new ink collector that uses the group box handle
            myInkCollector = new InkCollector(gbInkArea.Handle);

            // Turn the ink collector on
            myInkCollector.Enabled = true;
        }
Example #15
0
        static bool LcBracketed(Input inp, ref Position pos, ref Rules rules, out LcTerm x)
        {
            var i = pos;

            if (inp.Char('(', ref i) &&
                Parse(inp, ref i, ref rules, out x) &&
                inp.Optional(inp.WhiteSpaces(ref i)) &&
                inp.Char(')', ref i))
            {
                return(pos.Seek(i, ref rules));
            }
            return(Recognizers.Fail(out x));
        }
Example #16
0
        private void CreateRecognizer(InkOverlay overlay)
        {
            Recognizers recognizers = new Recognizers();
            Recognizer english = recognizers.GetDefaultRecognizer();
            context = english.CreateRecognizerContext();

            WordList wordList = new WordList();
            for (int i = 0; i < 100; ++i)
                wordList.Add(i.ToString());

            context.WordList = wordList;
            context.Factoid = Factoid.WordList;
            context.RecognitionFlags = RecognitionModes.Coerce;
        }
Example #17
0
        static bool LcApply(Input inp, ref Position pos, ref Rules rules, out LcTerm x)
        {
            var i = pos;

            if (!rules.IsLoop(1) &&
                Parse(inp, ref i, ref rules, out var lambda) &&
                inp.WhiteSpaces(ref i) &&
                Parse(inp, ref i, ref rules, out var arg))
            {
                x = new LcApply {
                    Lambda = lambda, Arg = arg
                };
                return(pos.Seek(i, ref rules));
            }
            return(Recognizers.Fail(out x));
        }
Example #18
0
        static bool LcLambda(Input inp, ref Position pos, ref Rules rules, out LcTerm x)
        {
            var i = pos;

            if (inp.Letters(ref i, out var v) &&
                inp.Optional(inp.WhiteSpaces(ref i)) &&
                inp.Literal("->", ref i) &&
                Parse(inp, ref i, ref rules, out var body))
            {
                x = new LcLambda {
                    Var = v.ToString(), Body = body
                };
                return(pos.Seek(i, ref rules));
            }
            return(Recognizers.Fail(out x));
        }
Example #19
0
        protected override Mat OnUpdate()
        {
            Mat mat = cap.RetrieveMat();

            if (DrawGrid)
            {
                DrawGridFrame(mat);
            }

            ReportCollection reps = Recognizers.Recognize(mat);

            DrawPoints(mat, reps);
            reps.Dispose();

            return(mat);
        }
Example #20
0
        public String Recognizer(String strokesStr, int count)
        {
            List <List <int[]> > strokes = new List <List <int[]> >();
            var array = Regex.Split(strokesStr, ",eb,");

            foreach (var item in array)
            {
                var stroke = new List <int[]>();
                var array2 = item.Split(',');
                for (var i = 0; i < array2.Length; i = i + 2)
                {
                    int[] point = new int[2];
                    point[0] = int.Parse(array2[i]);
                    point[1] = int.Parse(array2[i + 1]);
                    stroke.Add(point);
                }
                strokes.Add(stroke);
            }

            RecognizerContext recognizerContext = new Recognizers().GetDefaultRecognizer().CreateRecognizerContext();
            Ink ink = new Ink();

            recognizerContext.Strokes = ink.CreateStrokes();
            foreach (List <int[]> stroke in strokes)
            {
                Point[] points = new Point[stroke.Count];
                for (int i = 0; i < stroke.Count; i++)
                {
                    points[i] = new Point(stroke[i][0], stroke[i][1]);
                }
                recognizerContext.Strokes.Add(ink.CreateStroke(points));
            }
            RecognitionStatus recognitionStatus = RecognitionStatus.NoError;
            RecognitionResult recognitionResult = recognizerContext.Recognize(out recognitionStatus);
            var text = "";

            if (recognitionStatus == RecognitionStatus.NoError)
            {
                RecognitionAlternates alts = recognitionResult.GetAlternatesFromSelection();
                for (int i = 0; i < alts.Count && i < count; i++)
                {
                    RecognitionAlternate alt = alts[i];
                    text += alt.ToString() + " ";
                }
            }
            return(text.Trim());
        }
Example #21
0
    private async void GoButton_Click(object sender, RoutedEventArgs e)
    {
        LeftPanel.Children.Clear();
        RightPanel.Children.Clear();

        string fileName = AppDomain.CurrentDomain.BaseDirectory + "train.csv";

        int    offset           = int.Parse(Offset.Text);
        int    recordCount      = int.Parse(RecordCount.Text);
        double displayMultipler = double.Parse(OutputSize.Text);

        string[] rawTrain = await Task.Run(() => Loader.trainingReader(fileName, offset, recordCount));

        string[] rawValidation = await Task.Run(() => Loader.validationReader(fileName, offset, recordCount));

        var manhattanClassifier = Recognizers.manhattanClassifier(rawTrain);
        var euclideanClassifier = Recognizers.euclideanClassifier(rawTrain);

        // START: Use this section to compare parallel / non-parallel
        //var panel1Recognizer = new ParallelChannelRecognizerControl(
        //    "Manhattan Classifier", displayMultipler);
        //LeftPanel.Children.Add(panel1Recognizer);

        //MessageBox.Show("Ready to start panel #1");
        //await panel1Recognizer.Start(rawValidation, manhattanClassifier);

        var panel2Recognizer = new NonParallelRecognizerControl(
            "Manhattan Classifier", displayMultipler);

        RightPanel.Children.Add(panel2Recognizer);

        MessageBox.Show("Ready to start panel #2");
        await panel2Recognizer.Start(rawValidation, manhattanClassifier);

        // END: Use this section to compare parallel / non-parallel

        // START: Use this section to compare Manhattan / Euclidean distance algos
        //var panel2Recognizer = new ParallelChannelRecognizerControl(
        //    "Euclidean Classifier", displayMultipler);
        //RightPanel.Children.Add(panel2Recognizer);

        //MessageBox.Show("Ready to start panel #2");
        //await panel2Recognizer.Start(rawValidation, euclideanClassifier);
        // END: Use this section to compare Manhattan / Euclidean distance algos
    }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        private async Task CheckForDate(DiscordClient c, MessageCreateEventArgs e)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            if (e.Author.IsBot)
            {
                return;
            }

            _ = Task.Run(async() =>
            {
                IEnumerable <DateTimeV2ModelResult> parserList = Recognizers.RecognizeDateTime(e.Message.Content, DateTimeV2Type.Time, DateTimeV2Type.DateTime);

                if (parserList.Any())
                {
                    await e.Message.CreateReactionAsync(this.ClockEmoji);
                }
            });
        }
        public async Task Start(string[] rawData, FSharpFunc <int[], Observation> classifier)
        {
            await Task.Run(() =>
            {
                startTime = DateTime.Now;
                foreach (var imageString in rawData)
                {
                    int actual = imageString.Split(',').Select(x => Convert.ToInt32(x)).First();
                    int[] ints = imageString.Split(',').Select(x => Convert.ToInt32(x)).Skip(1).ToArray();

                    var result     = Recognizers.predict <Observation>(ints, classifier);
                    var resultData = new RecognizerResult()
                    {
                        prediction  = result.Label,
                        actual      = actual.ToString(),
                        imageString = imageString
                    };
                    progress.Report(resultData);
                }
            });
        }
Example #24
0
        private void button1_Click(object sender, EventArgs e)
        {
            Recognizers recs = new Recognizers();
            Recognizer reco = recs.GetDefaultRecognizer();
            RecognizerContext context = reco.CreateRecognizerContext();
            context.Strokes = inkOverlay.Ink.Strokes;

            RecognitionStatus status = RecognitionStatus.NoError;
            RecognitionResult res = context.Recognize(out status);

            if (status == RecognitionStatus.NoError)
            {
                MessageBox.Show(res.TopAlternate.ToString());

            }

            //Cleaning the strokes
            inkOverlay.Ink.DeleteStrokes(inkOverlay.Ink.Strokes);
            inkOverlay.Ink.Strokes.Clear();

            Invalidate();
        }
Example #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">Bot configuration.</param>
        /// <param name="isProduction">Production environment.</param>
        public BotServices(BotConfiguration botConfiguration, bool isProduction)
        {
            var endpointName = isProduction ? ProductionName : DevelopmentName;

            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Endpoint
                    when service is EndpointService endpoint && endpoint.Name == endpointName:
                    AppCredentials = (endpoint.AppId, endpoint.AppPassword);
                    break;

                case ServiceTypes.CosmosDB
                    when service is CosmosDbService cosmosDb && cosmosDb.Name == BotStateName:
                    IStorage storage = new CosmosDbStorage(
                        new CosmosDbStorageOptions
                    {
                        DatabaseId       = cosmosDb.Database,
                        CollectionId     = cosmosDb.Collection,
                        CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                        AuthKey          = cosmosDb.Key,
                    });
                    break;

                case ServiceTypes.Luis
                    when service is LuisService luis:
                    var app        = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    var recognizer = new TelemetryLuisRecognizer(app);
                    Recognizers.Add(luis.Name, recognizer);
                    break;

                case ServiceTypes.AppInsights
                    when service is AppInsightsService appInsights:
                    Telemetry = new BotTelemetry(appInsights.InstrumentationKey, logOriginalMessage: true, logUserName: false);
                    break;
                }
            }
        }
Example #26
0
        public static Recognizer GetDefaultRecognizer()
        {
            Recognizer recognizer = null;

            try
            {
                Recognizers recognizers = new Recognizers();
                if (recognizers.Count > 1)
                {
                    // First try the current locale's recognizer
                    try { recognizer = recognizers.GetDefaultRecognizer(); }
                    catch {}

                    // Fallback to the en-US (1033) recognizer
                    if (recognizer == null)
                    {
                        try { recognizer = recognizers.GetDefaultRecognizer(1033); }
                        catch {}
                    }
                }
            }
            catch {}
            return(recognizer);
        }
        /// <summary>
        /// Event Handler from Form Load Event
        /// Setup the ink overlay for collection
        /// </summary>
        /// <param name="sender">The control that raised the event.</param>
        /// <param name="e">The event arguments.</param>
        private void InkDividerForm_Load(object sender, System.EventArgs e)
        {
            // Create the ink overlay and associate it with the form
            myInkOverlay = new Microsoft.Ink.InkOverlay(DrawArea.Handle);

            // Hook event handler for the Stroke event to myInkOverlay_Stroke.
            // This is necessary since the application needs to pass the strokes
            // to the ink divider.
            myInkOverlay.Stroke += new InkCollectorStrokeEventHandler(myInkOverlay_Stroke);

            // Hook the event handler for StrokeDeleting event to myInkOverlay_StrokeDeleting.
            // This is necessary as the application needs to remove the strokes from
            // ink divider object as well.
            myInkOverlay.StrokesDeleting += new InkOverlayStrokesDeletingEventHandler(myInkOverlay_StrokeDeleting);

            // Hook the event handler for StrokeDeleted event to myInkOverlay_StrokeDeleted.
            // This is necessary to update the layout analysis result when automatic layout analysis
            // option is selected.
            myInkOverlay.StrokesDeleted += new InkOverlayStrokesDeletedEventHandler(myInkOverlay_StrokeDeleted);

            // Create the ink divider object
            myInkDivider = new Divider();

            // Add a default recognizer context to the divider object
            // without adding the recognizer context, the divider would
            // not use a recognizer to do its word segmentation and would
            // have less accurate results.
            // Adding the recognizer context will slow down the call to
            // myInkDivider.Divide though.
            // It is possible that there is no recognizer installed on the
            // machine for this language. In that case the divider will
            // not use a recognizer to improve its accuracy.
            // Get the default recognizer if any
            try
            {
                Recognizers recognizers = new Recognizers();
                myInkDivider.RecognizerContext = recognizers.GetDefaultRecognizer().CreateRecognizerContext();
            }
            catch (InvalidOperationException)
            {
                //We are in the case where no default recognizers can be found
            }

            // The LineHeight property helps the InkDivider distinguish between
            // drawing and handwriting. The value should be the expected height
            // of the user's handwriting in ink space units (0.01mm).
            // Here we set the LineHeight to 840, which is about 1/3 of an inch.
            myInkDivider.LineHeight = 840;

            // Assign ink overlay's strokes collection to the ink divider
            // This strokes collection will be updated in the event handler
            myInkDivider.Strokes = myInkOverlay.Ink.Strokes;

            // Enable ink collection
            myInkOverlay.Enabled = true;

            // Set check for ink menu item
            miInk.Checked = true;
        }
Example #28
0
        /// <summary>
        /// Iterate through each row of the form data and 
        /// display the recognition results
        /// </summary>
        private void Recognize()
        {
            // Check to ensure that the user has at least one recognizer installed
            Recognizers inkRecognizers = new Recognizers();
            if (0 == inkRecognizers.Count)
            {
                MessageBox.Show(this, "There are no handwriting recognizers installed.  You need to have at least one in order to perform the recognition.");
            }
            else
            {
                StringBuilder buffer = new StringBuilder();

                // Iterate through the rows in the "FieldInfo" table
                foreach(DataRow row in formData.Tables["FieldInfo"].Rows)
                {
                    // get the metadata for the field
                    // Note that the DataSet contains a row for each field
                    // in the form.  It is assumed that the rows are in the
                    // same order as the fields in the form.  The DataSet
                    // has the following columns:
                    // Name:  the field's name
                    // Left, Top, Right, Bottom:  the coordinates of the field (in pixels)
                    string fieldname = (string) row["Name"];
                    Point pt1 = new Point((int) row["Left"], (int) row["Top"]);
                    Point pt2 = new Point((int) row["Right"], (int) row["Bottom"]);

                    using (Graphics g = CreateGraphics())
                    {

                        // Convert to ink space units
                        inkPicture1.Renderer.PixelToInkSpace(g, ref pt1);
                        inkPicture1.Renderer.PixelToInkSpace(g, ref pt2);

                    }

                    // the rectangle for the region
                    Rectangle rc = new Rectangle(pt1.X, pt1.Y, pt2.X-pt1.X, pt2.Y-pt1.Y);

                    // find the strokes that intersect and lie inside of the rectangle
                    Strokes strokes = inkPicture1.Ink.HitTest(rc,70);

                    // recognize the handwriting
                    if (strokes.Count > 0)
                    {
                        buffer.Append(fieldname + " = " + strokes.ToString() + Environment.NewLine);
                    }
                }

                // Display the results
                if (buffer.Length > 0)
                {
                    MessageBox.Show(this, buffer.ToString());
                }
                else
                {
                    MessageBox.Show(this, "There aren't any recognition results.");
                }
            }
        }
Example #29
0
        static async Task Main(string[] args)
        {
            bool mini = false;

            if (args.Length > 0)
            {
                mini = args.Contains("-m");
            }

            Console.Clear();
            Console.WriteLine("Loading training data...");

            var log = new List <Prediction>();

            string fileName    = AppDomain.CurrentDomain.BaseDirectory + "train.csv";
            int    offset      = 9000;
            int    recordCount = 100;

            string[] rawTrain      = Loader.trainingReader(fileName, offset, recordCount);
            string[] rawValidation = Loader.validationReader(fileName, offset, recordCount);

            var classifier = Recognizers.manhattanClassifier(rawTrain);

            Console.Clear();
            var startTime = DateTime.Now;

            List <Task> digitTasks = new List <Task>();

            foreach (var imageString in rawValidation)
            {
                Task <Prediction> task = Task.Run(() =>
                {
                    int actual = imageString.Split(',').Select(x => Convert.ToInt32(x)).First();
                    int[] ints = imageString.Split(',').Select(x => Convert.ToInt32(x)).Skip(1).ToArray();

                    // Call the CPU-intensive function
                    var result = Recognizers.predict(ints, classifier);

                    var prediction = new Prediction
                    {
                        prediction   = result.Label,
                        actual       = actual.ToString(),
                        image        = ints,
                        closestMatch = result.Pixels
                    };
                    return(prediction);
                });
                digitTasks.Add(task);


                Task continuation = task.ContinueWith(t =>
                {
                    Prediction prediction = t.Result;

                    lock (fileName)
                    {
                        // Display the result
                        Console.SetCursorPosition(0, 0);
                        WriteOutput(prediction, mini);
                    }

                    if (prediction.prediction != prediction.actual.ToString())
                    {
                        log = LogError(log, prediction);
                    }
                });
                digitTasks.Add(continuation);
            }

            await Task.WhenAll(digitTasks);

            var endTime = DateTime.Now;

            Console.Clear();
            if (!mini)
            {
                Console.WriteLine("Press ENTER to view errors");
                Console.ReadLine();

                foreach (var pred in log)
                {
                    WriteOutput(pred, mini);
                    Console.WriteLine("-------------------------------------");
                }
            }
            Console.WriteLine($"Total Errors: {log.Count}");
            Console.WriteLine($"Start Time: {startTime}");
            Console.WriteLine($"End Time: {endTime}");
            Console.WriteLine($"Elapsed: {endTime - startTime:ss}");
            Console.WriteLine("\n\nEND END END END END END END END END");
            Console.ReadLine();
        }
        /// <summary>
        /// Event Handler from Form Load Event
        /// Setup the ink collector for collection
        /// </summary>
        /// <param name="sender">The control that raised the event.</param>
        /// <param name="e">The event arguments.</param>
        private void InkRecognition_Load(object sender, System.EventArgs e)
        {
            // Create the recognizers collection
            myRecognizers = new Recognizers();

            // Create a new ink collector that uses the group box handle
            myInkCollector = new InkCollector(gbInkArea.Handle);

            // Turn the ink collector on
            myInkCollector.Enabled = true;
        }
Example #31
0
        private void ink_()
        {
            Recognizers recos = new Recognizers();
            Recognizer chineseReco  = recos.GetDefaultRecognizer();

            rct = chineseReco.CreateRecognizerContext();
        }
Example #32
0
 static RecognizersHelper()
 {
     recognizers         = new Recognizers();
     suitableRecognizers = GetSuitableRecognizersInternal().ToArray();
 }
Example #33
0
        static async Task Main(string[] args)
        {
            var startTime = DateTime.Now;
            var log       = new List <Prediction>();

            string fileName    = AppDomain.CurrentDomain.BaseDirectory + "train.csv";
            int    offset      = 6000;
            int    recordCount = 200;

            string[] rawTrain      = Loader.trainingReader(fileName, offset, recordCount);
            string[] rawValidation = Loader.validationReader(fileName, offset, recordCount);

            var classifier = Recognizers.manhattanClassifier(rawTrain);

            var tasks = new List <Task>();

            foreach (var imageString in rawValidation)
            {
                var task = Task <Prediction> .Run(() =>
                {
                    int actual = imageString.Split(',').Select(x => Convert.ToInt32(x)).First();
                    int[] ints = imageString.Split(',').Select(x => Convert.ToInt32(x)).Skip(1).ToArray();
                    var result = Recognizers.predict(ints, classifier);

                    return(new Prediction {
                        prediction = result.Label, actual = actual.ToString(),
                        image = ints, closestMatch = result.Pixels
                    });
                });

                tasks.Add(task.ContinueWith(t =>
                {
                    lock (fileName)
                    {
                        var prediction = t.Result;
                        Console.Clear();
                        WriteOutput(prediction);

                        if (prediction.prediction != prediction.actual.ToString())
                        {
                            log = LogError(log, prediction);
                        }
                    }
                }));
            }

            await Task.WhenAll(tasks);

            var endTime = DateTime.Now;

            Console.Clear();
            Console.WriteLine("Press ENTER to view errors");
            Console.ReadLine();

            foreach (var pred in log)
            {
                WriteOutput(pred);
                Console.WriteLine("-------------------------------------");
            }
            Console.WriteLine($"Total Errors: {log.Count}");
            Console.WriteLine($"Start Time: {startTime}");
            Console.WriteLine($"End Time: {endTime}");
            Console.WriteLine("\n\nEND END END END END END END END END");
            Console.ReadLine();
        }
        private async Task SendAdjustedDate(DiscordClient c, MessageReactionAddEventArgs e)
        {
            if (e.User.IsBot)
            {
                return;
            }

            if (e.Channel.IsPrivate)
            {
                return;
            }

            DiscordChannel channel = await c.GetChannelAsync(e.Channel.Id);

            _ = Task.Run(async() =>
            {
                if (e.Emoji.Equals(this.ClockEmoji))
                {
                    try
                    {
                        DiscordMember reactor = (DiscordMember)e.User;
                        DiscordMessage msg    = await channel.GetMessageAsync(e.Message.Id);

                        DbResult <UserTimeZone> opTimeZoneResult = await this.Mediator.Send(new UserTimeZones.GetUsersTimeZone(msg.Author));
                        if (!opTimeZoneResult.TryGetValue(out UserTimeZone? opTimeZoneEntity))
                        {
                            await reactor.SendMessageAsync("The original poster has not set up a time zone yet.");
                            return;
                        }

                        string opTimeZoneId = opTimeZoneEntity.TimeZoneId;

                        DateTimeZone?opTimeZone = this.TimeZoneProvider.GetZoneOrNull(opTimeZoneId);

                        DbResult <UserTimeZone> reactorTimeZoneResult = await this.Mediator.Send(new UserTimeZones.GetUsersTimeZone(msg.Author));
                        if (!reactorTimeZoneResult.TryGetValue(out UserTimeZone? reactorTimeZoneEntity))
                        {
                            await reactor.SendMessageAsync("You have not set up a time zone yet. Use `time init` to set up your time zone.");
                            return;
                        }

                        string reactorTimeZoneId = reactorTimeZoneEntity.TimeZoneId;

                        DateTimeZone?reactorTimeZone = this.TimeZoneProvider.GetZoneOrNull(reactorTimeZoneId);

                        if (opTimeZone == null || reactorTimeZone == null)
                        {
                            await reactor.SendMessageAsync("There was a problem, please reach out to your bot developer.");
                            return;
                        }

                        ZonedDateTime zonedMessageDateTime = ZonedDateTime.FromDateTimeOffset(msg.CreationTimestamp);
                        DateTime opRefTime = zonedMessageDateTime.WithZone(opTimeZone).ToDateTimeOffset().DateTime;

                        IEnumerable <DateTimeV2ModelResult> parserList = Recognizers.RecognizeDateTime(e.Message.Content, opRefTime, DateTimeV2Type.Time, DateTimeV2Type.DateTime);

                        if (!parserList.Any())
                        {
                            await reactor.SendMessageAsync("This message does not have a recognizable time in it.");
                            return;
                        }

                        DiscordEmbedBuilder reactorTimeEmbed = new DiscordEmbedBuilder().WithTitle("You requested a timezone conversion");



                        IEnumerable <(string, DateTimeV2Value)> results = parserList.SelectMany(x => x.Values.Select(y => (x.Text, y)));
                        foreach ((string parsedText, DateTimeV2Value result) in results)
                        {
                            string outputString;
                            if (result.Type is DateTimeV2Type.Time)
                            {
                                LocalTime localParsedTime          = (LocalTime)result.Value;
                                LocalDateTime localParsedDateTime  = localParsedTime.On(zonedMessageDateTime.LocalDateTime.Date);
                                ZonedDateTime zonedOpDateTime      = localParsedDateTime.InZoneStrictly(opTimeZone);
                                ZonedDateTime zonedReactorDateTime = zonedOpDateTime.WithZone(reactorTimeZone);
                                outputString = zonedReactorDateTime.LocalDateTime.TimeOfDay.ToString("t", null);
                            }
                            else
                            {
                                LocalDateTime localParsedDateTime  = (LocalDateTime)result.Value;
                                ZonedDateTime zonedOpDateTime      = localParsedDateTime.InZoneStrictly(opTimeZone);
                                ZonedDateTime zonedReactorDateTime = zonedOpDateTime.WithZone(reactorTimeZone);
                                outputString = zonedReactorDateTime.LocalDateTime.ToString("g", null);
                            }

                            reactorTimeEmbed
                            .AddField("Poster's Time", $"\"{parsedText}\"")
                            .AddField("Your time", $"{outputString}");
                        }
                        await reactor.SendMessageAsync(embed: reactorTimeEmbed);
                    }
                    catch (Exception exception)
                    {
                        this.Logger.Log(LogLevel.Error, exception, "Error in sending reactor the DM");
                    }
                }
            });
        }