示例#1
0
        public static ServiceResponse GetOcrResult(OcrService ocrService, string filePath, FenceConfiguration[] fences = null)
        {
            var utcNow          = SystemClock.Instance.GetCurrentInstant().InUtc();
            var channelTimeZone = DateTimeZoneProviders.Tzdb["Europe/Zurich"];

            return(ocrService.AddRaidAsync(typeof(i18n), utcNow, channelTimeZone, filePath, 4, fences, true).Result);
        }
示例#2
0
 public OcrResult(string Text, Rect BoundingBox, OcrService OcrService)
 {
     this.Text        = Text;
     this.BoundingBox = BoundingBox;
     Words            = Text.Split(' ');
     this.OcrService  = OcrService;
 }
示例#3
0
    //...
    private void GetOcrFromService()
    {
        //...
        TextProcessing value = OcrService.Get();

        OcrTextVM = value;
    }
示例#4
0
        private async void OnStartedAsync()
        {
            Logger.LogInformation("メインロジック開始");
            Logger.LogTrace("設定ファイルの内容を出力");
            Console.WriteLine(Configuration.GetValue <string>("aaaa:bbbb"));
            Console.WriteLine(Configuration.GetValue <string>("cccc"));
            Logger.LogTrace("環境変数の内容を出力");
            Console.WriteLine(Configuration.GetValue <string>("TEST"));

            // 実際の処理はここに書きます
            Logger.LogTrace("ログレベルのテスト");
            Logger.Log(LogLevel.Trace, "Trace");
            Logger.Log(LogLevel.Debug, "Debug");
            Logger.Log(LogLevel.Information, "Information");
            Logger.Log(LogLevel.Warning, "Warning");
            Logger.Log(LogLevel.Error, "Error");
            Logger.Log(LogLevel.Critical, "Critical");
            Logger.Log(LogLevel.None, "None");

            Logger.LogInformation("メインロジックからサービスの呼び出しを行います。");
            MyService.MyServiceMethod();

            Logger.LogInformation("OCRを行います。");
            var ocrResult = OcrService.Recognize("./Samples/sample.png");

            Logger.LogInformation($"OCR結果:{ocrResult.Text}");

            Logger.LogInformation("PDF -> OCRを行います。");
            var pdfResult = await PdfService.RecognizeAsync(".\\Samples\\sample.pdf", 0);

            Logger.LogInformation($"PDF -> OCR結果:{pdfResult}");

            AppLifetime.StopApplication(); // 自動でアプリケーションを終了させる
        }
示例#5
0
 /// <summary>
 /// Helper method to initiate the call to the Hawaii OCR service.
 /// </summary>
 /// <param name="hawaiiAppId">Specifies the Hawaii Application Id.</param>
 /// <param name="imageBuffer">
 /// Specifies a buffer containing an image that has to be processed.
 /// The image must be in JPEG format.
 /// </param>
 /// <param name="onComplete">Specifies an on complete callback method.</param>
 public static void RecognizeImageAsync(
     string hawaiiAppId,
     byte[] imageBuffer,
     ServiceAgent <OcrServiceResult> .OnCompleteDelegate onComplete)
 {
     OcrService.RecognizeImageAsync(
         hawaiiAppId,
         imageBuffer,
         onComplete,
         null);
 }
        private void StartOcrConversion(byte[] photoStream)
        {
            byte[] photoBuffer = photoStream;

            OcrService.RecognizeImageAsync(
                SettingsApi.HawaiiGuid,
                photoBuffer,
                (output) =>
            {
                this.Dispatcher.BeginInvoke(() => OnOcrCompleted(output));
            });
        }
示例#7
0
        static void Main(string[] args)
        {
            var imgFile = @"C:\Users\ch489gt\Pictures\Snag-Auto\TestSnag.png";

            var predictService = new PredictionService();
            var predictRes     = predictService.Predict(imgFile);

            var ocrService = new OcrService();
            var ocrRes     = ocrService.DoOcr(imgFile);

            var analyzer = new VisionAnalyzer();
            var result   = analyzer.GetResult(imgFile, predictRes.Data);
        }
示例#8
0
文件: Program.cs 项目: yrrebpsar/ocr
        static void Main(string[] args)
        {
            bool show_help = false;
            bool watch     = false;
            bool force     = false;
            bool commit    = false;
            var  options   = new OptionSet()
            {
                { "o|output=", "specify output Directory", v => output = v },
                { "c|commit", "commit ocr-version", v => commit = true },
                { "w|watch", "watch directory", v => watch = true },
                { "f|force", "force generation of ocr file", v => force = true },
                { "h|help", "orccore file1 [file2 ...file-n]", v => show_help = v != null }
            };
            var pathes = options.Parse(args);

            if (show_help)
            {
                options.WriteOptionDescriptions(Console.Out);
                System.Environment.Exit(0);
            }

            if (watch)
            {
                Watcher watcher = new Watcher(pathes[0], output);
                watcher.Start();
                Console.ReadLine();
                watcher.Stop();
            }
            else
            {
                foreach (var p in pathes)
                {
                    var        globber = new Glob();
                    var        files   = globber.ExpandNames(p);
                    OcrService scanner = new OcrService(output);
                    foreach (var f in files)
                    {
                        if (commit)
                        {
                            scanner.Commit(f);
                        }
                        else
                        {
                            scanner.Scan(f, force);
                        }
                    }
                }
            }
        }
示例#9
0
        public void Configuration(IAppBuilder app)
        {
            //TODO: Only for Demo
            //SETUP PROFILE DATA
            MemoryCasheService memoryCasheService = new MemoryCasheService();

            memoryCasheService.Add("Profile", new Profile(21, 180, 32, 0, PhysicalActivity.Average), DateTimeOffset.MaxValue);
            //SETUP EITEMS DATA
            var eitems = OcrService.GetAllEitems();

            memoryCasheService.Add("ALL_EITEMS", eitems, DateTimeOffset.MaxValue);

            ConfigureAuth(app);
        }
示例#10
0
        private static void Main(string[] args)
        {
            var screenCap = new ScreenCaptureService();
            var ocr       = new OcrService();

            while (true)
            {
                var bitmap = screenCap.CaptureScreenshot();
                var text   = ocr.ProcessImage(new MemoryStream(bitmap));

                Console.WriteLine(text);
                Thread.Sleep(5000);
            }
        }
示例#11
0
        private void StartOcrConversion(byte[] photoStream)
        {
            _progressIndicator.IsVisible = true;
            _progressIndicator.Text      = "Trwa konwersja OCR...";

            byte[] photoBuffer = photoStream;

            OcrService.RecognizeImageAsync(
                SettingsApi.HawaiiGuid,
                photoBuffer,
                (output) =>
            {
                this.Dispatcher.BeginInvoke(() => OnOcrCompleted(output));
            });
        }
示例#12
0
        public static void Run()
        {
            if (running)
            {
                return;
            }
            running = true;
            OcrService.Initialise();
            OcrService.BatchComplete += OcrService_BatchComplete;

            //MessageBus.Subscribe<RecogniseBatchCourtesyAmountRequest>(QueueSubscriptionId, Queue_MessageReceived);
            StartConsumer();
            //var msgThread = new Thread(MessageThread);
            //msgThread.Start();
        }
示例#13
0
        private void StartOcrConversion()
        {
            OcrService.RecognizeImageAsync(
                HawaiiClient.HawaiiApplicationId,
                OcrClientUtils.GetPhotoBits(this.ocrData.PhotoStream),
                (output) =>
            {
                // This section defines the body of what is known as an anonymous method.
                // This anonymous method is the callback method
                // called on the completion of the OCR process.
                // Using Dispatcher.BeginInvoke ensures that
                // OnOcrCompleted is invoked on the Main UI thread.
                this.Dispatcher.BeginInvoke(() => OnOcrCompleted(output));
            });

            this.ocrConversionStateManager.OcrConversionState = OcrConversionState.Converting;
            this.Dispatcher.BeginInvoke(() => { this.mainPivot.SelectedIndex = 1; });
        }
        // api/ocr
        public async Task <IHttpActionResult> Post()
        {
            List <Eitem> returnedEitems = new List <Eitem>();

            var file = HttpContext.Current.Request.Files.Count > 0 ?
                       HttpContext.Current.Request.Files[0] : null;

            if (file.ContentLength > 0)
            {
                //Upload Photo
                OcrService   ocrService       = new OcrService();
                BinaryReader binaryReader     = new BinaryReader(file.InputStream);
                byte[]       imageAsByteArray = binaryReader.ReadBytes(file.ContentLength);
                var          json             = await ocrService.GetOrcServerResponce(imageAsByteArray);

                //Deserialize Json
                var ocrDto = JsonConvert.DeserializeObject <OcrDto>(json);
                if (ocrDto.ErrorMessage != null || String.IsNullOrEmpty(Enumerable.FirstOrDefault(ocrDto.ParsedResults).ParsedText))
                {
                    return(BadRequest(ocrDto.ErrorMessage.ToString()));
                }
                //parse E
                string parsedText = Regex.Replace(ocrDto.ParsedResults[0].ParsedText, @"\s+", "");
                var    eElements  = Enumerable.Cast <Match>(Regex.Matches(parsedText, "(([Е{IsCyrillic}]{1}[0-9]{3,4})|([E{IsCyrillic}-]{2}[0-9]{3,4}))")).Select(m => m.Value.Unidecode()).ToList();

                //Get current E from MemoryCache
                MemoryCasheService memoryCache = new MemoryCasheService();
                var items = memoryCache.GetValue("ALL_EITEMS") as List <Eitem>;
                if (items != null)
                {
                    returnedEitems = items.Where(item => eElements.Contains(item.Ecode)).ToList();
                }
                return(Ok(returnedEitems));
            }
            else
            {
                return(BadRequest());
            }
        }
示例#15
0
    static void __executeCommand(string requestId, COMMANDS cmd, string input, Dictionary <string, object> data)
    {
        if (data == null)
        {
            data = new Dictionary <string, object>();
        }
        switch (cmd)
        {
        case COMMANDS.PDF_SPLIT_ALL_JPG:
            PdfService.SplitAllJpeg(requestId, cmd, input, data);
            break;

        case COMMANDS.OCR_BOX_PAGE:
        case COMMANDS.OCR_TEXT_PAGE:
        case COMMANDS.OCR_TEXT_ALL_PAGE:
            OcrService.convertImage2Text_OneOrAllPage(requestId, cmd, input, data);
            break;

        case COMMANDS.CURL_FTP_UPLOAD_FILE:
            FTPUpload.Execute(requestId, cmd, input, data);
            break;
        }
    }
        protected ServiceResponse <OcrService.RaidOcrResult> GetOcrResult(OcrService ocrService, string fileName)
        {
            var filePath = Path.Combine(BasePath, FolderName, fileName);

            return(OcrTestsHelper.GetOcrResult(ocrService, filePath));
        }
示例#17
0
        public String DoOCR([FromForm] OcrModel request)
        {
            var result = new OcrService().GetLicenseNumber(request.Image, request.DestinationLanguage);

            return(String.IsNullOrWhiteSpace(result) ? "Ocr is finished. Return empty" : result);
        }
示例#18
0
        public void Tests(string input, string expectedResult)
        {
            IOcrService service = new OcrService();

            Assert.Equal(expectedResult, service.ValidateOcr(input));
        }
示例#19
0
        public static void Consumer_ReceiveMessage(IBasicGetResult message)
        {
            // Process Message from queue
            if (message == null)
            {
                return;                 // queue is empty
            }
            var batch = CustomJsonSerializer.BytesToMessage <RecogniseBatchCourtesyAmountRequest>(message.Body);

            //var batch = message;

            if (message.Body.Count() == 0)
            {
                Log.Error(
                    "ProcessingService: Queue_MessageRecieved(message) - message.Body contains no data for message id {0}",
                    message.BasicProperties.MessageId);
            }
            if (batch == null)
            {
                if (message.Body.Count() > 0)
                {
                    Log.Error(
                        "ProcessingService: Queue_MessageRecieved(message) - message.Body contains data which is not compatible with RecogniseBatchCourtesyAmountRequest for message id {0}",
                        message.BasicProperties.MessageId);
                }
                // need to re-route message to CAR.Invalid queue
                if (!string.IsNullOrEmpty(InvalidQueueName))
                {
                    InvalidExchange.SendMessage(message.Body, InvalidRoutingKey, "");
                }
                return; // acknowledge message to remove from queue;
            }
            RoutingKey = message.RoutingKey;
            if (batch.voucher == null || batch.voucher.Length == 0)
            {
                Log.Error(
                    "ProcessingService: Queue_MessageRecieved(message) - there are no vouchers present for message id {0}",
                    message.BasicProperties.MessageId);
                // need to re-route message to CAR.Invalid queue
                if (!string.IsNullOrEmpty(InvalidQueueName))
                {
                    InvalidExchange.SendMessage(message.Body, InvalidRoutingKey, "");
                }
                return; // acknowledge message to remove from queue;
            }
            var ocrBatch = new OcrBatch
            {
                JobIdentifier = batch.jobIdentifier,
                Vouchers      = batch.voucher.Select(v => new OcrVoucher
                {
                    Id          = v.documentReferenceNumber,
                    ImagePath   = Path.Combine(ImageFilePath, batch.jobIdentifier, string.Format(ImageFileNameTemplate, v.processingDate, v.documentReferenceNumber)),
                    VoucherType = ParseTransactionCode(v.transactionCode)
                }).ToList()
            };

            // Validate the file path
            if (!ValidateImageFiles(ocrBatch))
            {
                return;                               // probably should send to an error queue
            }
            Log.Information("Batch {0} received from message queue containing {1} vouchers", ocrBatch.JobIdentifier, ocrBatch.Vouchers.Count());
            OcrService.ProcessBatch(ocrBatch);
        }
示例#20
0
        public void Tests(string accountNumber, bool isValid)
        {
            IOcrService service = new OcrService();

            Assert.Equal(isValid, service.IsValidAccountNumber(accountNumber));
        }