Слияние кода C # в Android Xamarin - PullRequest
0 голосов
/ 01 июня 2018

Я получил код обнаружения плохой грамматики отсюда - Определение плохой грамматики

Я новичок в C # и Xamarin.Я хочу объединить этот код с приложением преобразования речи в текст.

Я пытался сделать это, но не получил желаемых результатов.

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.OS;
using Android.Speech;
using Android.Util;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;

namespace SpeechToText
{
    [Activity(Label = "SpeechToText", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity, IRecognitionListener
    {
        public const string Tag = "VoiceRec";

        SpeechRecognizer Recognizer { get; set; }
        Intent SpeechIntent { get; set; }
        TextView Label { get; set; }
        TextView Label1 { get; set; }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Recognizer = SpeechRecognizer.CreateSpeechRecognizer(this);
            Recognizer.SetRecognitionListener(this);

            SpeechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
            SpeechIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
            SpeechIntent.PutExtra(RecognizerIntent.ExtraCallingPackage, PackageName);

            var button = FindViewById<Button>(Resource.Id.btn);
            button.Click += ButtonClick;

            var Grammarbutton = FindViewById<Button>(Resource.Id.btn1);
            Grammarbutton.Click += new EventHandler(ButtonClick2);

            Label = FindViewById<TextView>(Resource.Id.tv);
            Label1 = FindViewById<TextView>(Resource.Id.tv1);
        }

        private void ButtonClick(object sender, EventArgs e)
        {
            Recognizer.StartListening(SpeechIntent);
        }

        public void OnResults(Bundle results)
        {
            var matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
            if (matches != null && matches.Count > 0)
            {
                Label.Text = matches[0];
            }

        }

        private void ButtonClick2(object sender, EventArgs e)
        {

            var api = new GingerItApi();
            for (; ; )
            {
                Console.Write("Text to check: ");
                var text = Label.Text;
                if (string.IsNullOrEmpty(text)) break;

                try
                {
                    var result = api.Check(text);
                    if (result?.Corrections?.Count != 0)
                    {

                        for (int i = 0; i < result.Corrections.Count; i++)
                        {
                            var item = result.Corrections[i];
                            var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
                            var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
                            Label1.Text = $"  {i + 1}: {mistakes} >> {suggestions}";
                        }

                    }
                    else
                    {
                        Console.WriteLine("Looks okay.\n");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"**Error: {ex.Message}\n");
                }

            }
        }

        public void OnReadyForSpeech(Bundle @params)
        {
            Log.Debug(Tag, "OnReadyForSpeech");
        }

        public void OnBeginningOfSpeech()
        {
            Log.Debug(Tag, "OnBeginningOfSpeech");
        }

        public void OnEndOfSpeech()
        {
            Log.Debug(Tag, "OnEndOfSpeech");
        }

        public void OnError([GeneratedEnum] SpeechRecognizerError error)
        {
            Log.Debug("OnError", error.ToString());
        }

        public void OnBufferReceived(byte[] buffer) { }

        public void OnEvent(int eventType, Bundle @params) { }

        public void OnPartialResults(Bundle partialResults) { }

        public void OnRmsChanged(float rmsdB) { }
    }
}

class GingerItApi
        {
            public CheckResult Check(string text)
            {
                var request = WebRequest.Create($"https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=jQuery172015406464511272344_1490987331365&apiKey=GingerWebSite&lang=US&clientVersion=2.0&text={text}&_=1490987518060") as HttpWebRequest;
                WebResponse response = null;
                try
                {
                    response = request.GetResponse();

                    if (response != null)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            string data = reader.ReadToEnd();
                            var first = data.IndexOf('{');
                            var last = data.LastIndexOf('}');
                            var json = data.Substring(first, last - first + 1);
                            return JsonConvert.DeserializeObject<CheckResult>(json);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return null;
            }
        }

        public class LrnFrgOrigIndx
        {
            [JsonProperty("From")]
            public int From { get; set; }

            [JsonProperty("To")]
            public int To { get; set; }
        }

        public class Mistake
        {
            [JsonProperty("Definition")]
            public string Definition { get; set; }

            [JsonProperty("CanAddToDict")]
            public bool CanAddToDict { get; set; }

            [JsonProperty("From")]
            public int From { get; set; }

            [JsonProperty("To")]
            public int To { get; set; }
        }

        public class Suggestion
        {
            [JsonProperty("Definition")]
            public string Definition { get; set; }

            [JsonProperty("LrnCatId")]
            public int LrnCatId { get; set; }

            [JsonProperty("Text")]
            public string Text { get; set; }
        }

        public class Correction
        {
            [JsonProperty("Confidence")]
            public int Confidence { get; set; }

            [JsonProperty("From")]
            public int From { get; set; }

            [JsonProperty("LrnFrg")]
            public string LrnFrg { get; set; }

            [JsonProperty("LrnFrgOrigIndxs")]
            public IList<LrnFrgOrigIndx> LrnFrgOrigIndxs { get; set; }

            [JsonProperty("Mistakes")]
            public IList<Mistake> Mistakes { get; set; }

            [JsonProperty("ShouldReplace")]
            public bool ShouldReplace { get; set; }

            [JsonProperty("Suggestions")]
            public IList<Suggestion> Suggestions { get; set; }

            [JsonProperty("To")]
            public int To { get; set; }

            [JsonProperty("TopLrnCatId")]
            public int TopLrnCatId { get; set; }

            [JsonProperty("Type")]
            public int Type { get; set; }

            [JsonProperty("UXFrgFrom")]
            public int UXFrgFrom { get; set; }

            [JsonProperty("UXFrgTo")]
            public int UXFrgTo { get; set; }
        }

        public class Sentence
        {
            [JsonProperty("FromIndex")]
            public int FromIndex { get; set; }

            [JsonProperty("IsEnglish")]
            public bool IsEnglish { get; set; }

            [JsonProperty("ToIndex")]
            public int ToIndex { get; set; }
        }

        public class CheckResult
        {
            [JsonProperty("Corrections")]
            public IList<Correction> Corrections { get; set; }

            [JsonProperty("Sentences")]
            public IList<Sentence> Sentences { get; set; }
        }

Я хочу получить распознанныйречи, отправьте его в корректор грамматики и отобразите вывод.

Пожалуйста, помогите мне решить эту проблему или, по крайней мере, помогите мне продолжить исследование проблемы.

Спасибо.

1 Ответ

0 голосов
/ 04 июня 2018

Вы поместили бесконечный цикл в ваш код.Пожалуйста, удалите его.

Например:

    private void ButtonClick2(object sender, EventArgs e)
    {
        var api = new GingerItApi();
        Console.Write("Text to check: ");
        var text = Label.Text;
        if (!string.IsNullOrEmpty(text))
        {
            try
            {
                var result = api.Check(text);
                if (result?.Corrections?.Count != 0)
                {
                    for (int i = 0; i < result.Corrections.Count; i++)
                    {
                        var item = result.Corrections[i];
                        var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
                        var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
                        Label1.Text = $"  {i + 1}: {mistakes} >> {suggestions}";
                    }
                }
                else
                {
                    Label1.Text = "Looks okay.\n";
                    Console.WriteLine("Looks okay.\n");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"**Error: {ex.Message}\n");
            }
        }
    }

И результат:enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...