Exemplo n.º 1
0
        /// <summary>
        /// execute task
        /// </summary>
        public static void ExecuteTask(Tasks task)
        {
            try
            {
                AssistProcessor assist        = new AssistProcessor();
                Assist          serviceAssist = new Assist();

                string planState = serviceAssist.CheckSubscriptionPlanAvailability(task.UserId);
                if (planState != "OK")
                {
                    serviceAssist.AddErrorToDocuments(task.Id, planState);
                    //update task
                    serviceAssist.UpdateTaskState(task.Id, 4);
                    //update documents
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                    return;
                }

                string url      = serviceAssist.GetSettingValueByName("ApiUrl");
                string json     = task.ProfileContent;
                string error    = "";
                string response = assist.MakeOcr(url, json, ref error);
                if (string.IsNullOrEmpty(response))
                {
                    LogHelper.AddLog(error);
                    serviceAssist.AddErrorToDocuments(task.Id, error);
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                    serviceAssist.UpdateTaskState(task.Id, 4);
                    return;
                }

                OcrResponseModel model = new OcrResponseModel();
                serviceAssist.UpdateTaskReponseContent(task.Id, response);
                model = JsonConvert.DeserializeObject <OcrResponseModel>(response);

                if (model.Status.Equals("Submitted"))
                {
                    serviceAssist.UpdateTaskState(task.Id, 2);
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 2);
                }
                else
                {
                    string errorText = "";
                    foreach (var ocrError in model.Errors)
                    {
                        errorText += ocrError.ErrorName + ": " + ocrError.ErrorMessage;
                    }
                    serviceAssist.AddErrorToDocuments(task.Id, errorText);
                    serviceAssist.UpdateTaskState(task.Id, 4);
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                }
            }
            catch (Exception exception)
            {
                string innerException = exception.InnerException == null ? "" : exception.InnerException.Message;
                string methodName     = System.Reflection.MethodBase.GetCurrentMethod().Name;
                LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " +
                                 innerException);
            }
        }
Exemplo n.º 2
0
        public IHttpActionResult Post([FromBody] PostBase64DataOcrRequestModel value)
        {
            OcrResponseModel response = new OcrResponseModel
            {
                OcrResponseCode = "200",
                OcrTextResponse = this._ocrEnginePool.GetEngineForLang(value.Language).ReadText(value.Base64String)
            };

            return(Ok(response));
        }
Exemplo n.º 3
0
        // POST: api/Ocr
        public IHttpActionResult Post([FromBody] ImageModel image)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            if (image != null)
            {
                try
                {
                    var localImage = createLocalImage(image);

                    lock (syncLock)
                    {
                        tessBaseApi.Process(localImage);
                        stopWatch.Stop();
                        File.Delete(localImage);

                        var response = new OcrResponseModel()
                        {
                            Id = Guid.NewGuid(),
                            RequestDuration = stopWatch.Elapsed,
                            Text            = tessBaseApi.GetUTF8Text()
                        };

                        return(Ok(response));
                    }
                }
                catch { }
            }

            stopWatch.Stop();
            var exception = new ExceptionModel()
            {
                DateCreated      = DateTime.Now,
                ExceptionMessage = "Image object could not be deserialised or ocr process failed.",
                RequestDuration  = stopWatch.Elapsed
            };

            return(BadRequest(exception.ToString()));
        }
Exemplo n.º 4
0
        /// <summary>
        /// execute task
        /// </summary>
        public static void ExecuteTask(Tasks task)
        {
            try
            {
                AssistProcessor assist        = new AssistProcessor();
                Assist          serviceAssist = new Assist();

                FileInfo fileInfo = null;

                Documents document = serviceAssist.GetToDocumentByTaskId(task.Id);
                var       settings = SettingsTasksUnionHelper.GetSettingsByTaskId(task.Id);

                string mainPath     = serviceAssist.GetSettingValueByName("MainPath");
                string resultFolder = serviceAssist.GetSettingValueByName("ResultFolder");
                string jobPattern   = serviceAssist.GetSettingValueByName("ApiUrlJobState");
                string uploadFolder = serviceAssist.GetSettingValueByName("UploadFolder");

                string downloadPath = Path.Combine(mainPath, resultFolder);
                //string uploadPath = Path.Combine(mainPath, uploadFolder);

                string planState = serviceAssist.CheckSubscriptionPlanAvailability(task.UserId);
                if (planState != "OK")
                {
                    serviceAssist.AddErrorToDocuments(task.Id, planState);
                    //update task
                    serviceAssist.UpdateTaskState(task.Id, 4);
                    //update documents
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                    return;
                }

                string url      = serviceAssist.GetSettingValueByName("ApiUrl");
                string json     = task.ProfileContent;
                string error    = "";
                string response = assist.MakeOcr(url, json, ref error);
                if (string.IsNullOrEmpty(response))
                {
                    /// Error! Put to exc. ftp
                    LogHelper.AddLog(error);
                    serviceAssist.AddErrorToDocuments(task.Id, error);
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                    serviceAssist.UpdateTaskState(task.Id, 4);

                    if (settings != null)
                    {
                        string filePath = Path.Combine(mainPath, document.Path);

                        fileInfo = new FileInfo(filePath);
                        var exceptionSettings =
                            FlexiCapture.Cloud.FTPService
                            .Helpers.TasksHelpers.FTPHelper
                            .GetFtpExceptionSettings(settings.Id);

                        var ftpConvSetting = FlexiCapture.Cloud.
                                             ServiceAssist.DBHelpers.FtpConversionSettingsHelper
                                             .GetSettingsByUserId(settings.UserId);

                        string pathToPut = ftpConvSetting.MirrorInput ? settings.Path : exceptionSettings.Path;

                        FTPHelper.PutFileOnFtpServer(fileInfo, document.OriginalFileName, exceptionSettings, pathToPut);
                    }

                    return;
                }

                OcrResponseModel model = new OcrResponseModel();
                serviceAssist.UpdateTaskReponseContent(task.Id, response);
                model = JsonConvert.DeserializeObject <OcrResponseModel>(response);

                if (model.Status.Equals("Submitted"))
                {
                    serviceAssist.UpdateTaskState(task.Id, 2);
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 2);
                }
                else
                {
                    // Error!
                    string errorText = "";
                    foreach (var ocrError in model.Errors)
                    {
                        errorText += ocrError.ErrorName + ": " + ocrError.ErrorMessage;
                    }
                    serviceAssist.AddErrorToDocuments(task.Id, errorText);
                    serviceAssist.UpdateTaskState(task.Id, 4);
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);

                    if (settings != null)
                    {
                        string filePath = Path.Combine(mainPath, document.Path);

                        fileInfo = new FileInfo(filePath);
                        var exceptionSettings =
                            FlexiCapture.Cloud.FTPService
                            .Helpers.TasksHelpers.FTPHelper
                            .GetFtpExceptionSettings(settings.Id);

                        var ftpConvSetting = FlexiCapture.Cloud.
                                             ServiceAssist.DBHelpers.FtpConversionSettingsHelper
                                             .GetSettingsByUserId(settings.UserId);

                        string pathToPut = ftpConvSetting.MirrorInput ? settings.Path : exceptionSettings.Path;

                        FTPHelper.PutFileOnFtpServer(fileInfo, document.OriginalFileName, exceptionSettings, pathToPut);
                    }
                }
            }
            catch (Exception exception)
            {
                string innerException = exception.InnerException == null ? "" : exception.InnerException.Message;
                string methodName     = System.Reflection.MethodBase.GetCurrentMethod().Name;
                LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " +
                                 innerException);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// check task
        /// </summary>
        public static void CheckStateTask(Tasks task)
        {
            try
            {
                AssistProcessor  assist        = new AssistProcessor();
                Assist           serviceAssist = new Assist();
                OcrResponseModel model         = new OcrResponseModel();
                model = JsonConvert.DeserializeObject <OcrResponseModel>(task.ResponseContent);
                FileInfo fileInfo = null;

                Documents document = serviceAssist.GetToDocumentByTaskId(task.Id);
                var       settings = SettingsTasksUnionHelper.GetSettingsByTaskId(task.Id);

                string mainPath     = serviceAssist.GetSettingValueByName("MainPath");
                string resultFolder = serviceAssist.GetSettingValueByName("ResultFolder");
                string jobPattern   = serviceAssist.GetSettingValueByName("ApiUrlJobState");
                string uploadFolder = serviceAssist.GetSettingValueByName("UploadFolder");

                string downloadPath = Path.Combine(mainPath, resultFolder);
                string uploadPath   = Path.Combine(mainPath, uploadFolder);

                string jobStatus = assist.GetJobStatus(model.JobUrl);

                model = JsonConvert.DeserializeObject <OcrResponseModel>(jobStatus);

                if (model.Status.Equals("Finished"))
                {
                    string planState = serviceAssist.CheckSubscriptionPlan(task.UserId, model.Statistics.PagesArea);
                    if (planState != "OK")
                    {
                        // Error!
                        serviceAssist.AddErrorToDocuments(task.Id, planState);
                        //update task
                        serviceAssist.UpdateTaskState(task.Id, 4);
                        //update documents
                        serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);

                        if (settings != null)
                        {
                            string filePath = Path.Combine(uploadPath, document.Path);

                            fileInfo = new FileInfo(filePath);
                            var exceptionSettings =
                                FlexiCapture.Cloud.FTPService
                                .Helpers.TasksHelpers.FTPHelper
                                .GetFtpExceptionSettings(settings.Id);

                            var ftpConvSetting = FlexiCapture.Cloud.
                                                 ServiceAssist.DBHelpers.FtpConversionSettingsHelper
                                                 .GetSettingsByUserId(settings.UserId);

                            string pathToPut = ftpConvSetting.MirrorInput ? settings.Path : exceptionSettings.Path;

                            FTPHelper.PutFileOnFtpServer(fileInfo, document.OriginalFileName, exceptionSettings, pathToPut);
                        }



                        return;
                    }



                    foreach (var file in model.Download)
                    {
                        string jobId = model.JobUrl.Replace(jobPattern, string.Empty);

                        if (document == null)
                        {
                            serviceAssist.UpdateTaskState(task.Id, 4);
                            return;
                        }
                        string originalName = Path.GetFileNameWithoutExtension(document.OriginalFileName);
                        string fileExt      = serviceAssist.GetToFileExtension(file.OutputFormat);

                        Guid   g       = Guid.NewGuid();
                        string newName = g.ToString() + fileExt;

                        originalName = originalName + fileExt;
                        string filePath = Path.Combine(downloadPath, newName);

                        fileInfo = new FileInfo(filePath);



                        string error = "";
                        assist.DownloadFile(file.Uri, filePath, ref error);
                        if (!File.Exists(filePath))
                        {
                            LogHelper.AddLog(error);
                            serviceAssist.AddErrorToDocuments(task.Id, error);
                            //update task
                            serviceAssist.UpdateTaskState(task.Id, 4);
                            //update documents
                            serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                            return;
                        }
                        //add document
                        serviceAssist.AddResultDocument(task.Id, g, originalName, newName, filePath);

                        if (settings != null)
                        {
                            var outputSettings =
                                FlexiCapture.Cloud.FTPService
                                .Helpers.TasksHelpers.FTPHelper
                                .GetFtpOutputSettings(settings.Id);

                            var ftpConvSetting = FlexiCapture.Cloud.
                                                 ServiceAssist.DBHelpers.FtpConversionSettingsHelper
                                                 .GetSettingsByUserId(settings.UserId);

                            string pathToPut = ftpConvSetting.MirrorInput ? settings.Path : outputSettings.Path;

                            FTPHelper.PutFileOnFtpServer(fileInfo, originalName, outputSettings, pathToPut);
                        }
                    }

                    //update task
                    serviceAssist.UpdateTaskState(task.Id, 3);
                    //update documents
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 3);
                    // add statistics
                    serviceAssist.AddStatisctics(task.Id, model.Statistics);
                }
                else if (model.Status.Equals("Processing"))
                {
                }
                else if (!model.Status.Equals("Submitted"))
                {
                    // Error!

                    LogHelper.AddLog("Error in JobStatus: " + jobStatus);
                    string errorText = "";
                    foreach (var ocrError in model.Errors)
                    {
                        errorText += ocrError.ErrorName + ": " + ocrError.ErrorMessage;
                    }
                    serviceAssist.AddErrorToDocuments(task.Id, errorText);
                    //update task
                    serviceAssist.UpdateTaskState(task.Id, 4);
                    //update documents
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);

                    if (settings != null)
                    {
                        string filePath = Path.Combine(uploadPath, document.Path);

                        fileInfo = new FileInfo(filePath);
                        var exceptionSettings =
                            FlexiCapture.Cloud.FTPService
                            .Helpers.TasksHelpers.FTPHelper
                            .GetFtpExceptionSettings(settings.Id);

                        var ftpConvSetting = FlexiCapture.Cloud.
                                             ServiceAssist.DBHelpers.FtpConversionSettingsHelper
                                             .GetSettingsByUserId(settings.UserId);

                        string pathToPut = ftpConvSetting.MirrorInput ? settings.Path : exceptionSettings.Path;

                        FTPHelper.PutFileOnFtpServer(fileInfo, document.OriginalFileName, exceptionSettings, pathToPut);
                    }
                }
            }
            catch (Exception exception)
            {
                string innerException = exception.InnerException == null ? "" : exception.InnerException.Message;
                string methodName     = System.Reflection.MethodBase.GetCurrentMethod().Name;
                LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " +
                                 innerException);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        ///     input in program
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            try
            {
                SettingsModel   settings     = new SettingsModel();
                OcrRequestModel requestModel = new OcrRequestModel();
                string          lang         = "English";
                //init model
                requestModel.ApiKey = settings.ApiKey;

                requestModel.CleanupSettings = new CleanupSettingsModel()
                {
                    Deskew        = true,
                    RemoveGarbage = true,
                    RemoveTexture = true,
                    SplitDualPage = true,
                    RotationType  = "NoRotation",
                    JpegQuality   = "",
                    OutputFormat  = "",
                    Resolution    = ""
                };
                requestModel.OcrSettings = new OcrSettingsModel()
                {
                    SpeedOcr        = false,
                    LookForBarcodes = false,
                    AnalysisMode    = "MixedDocument",
                    PrintType       = "Print",
                    OcrLanguage     = lang
                };

                requestModel.OutputSettings = new OutputSettingsModel()
                {
                    ExportFormat = "Text;PDF"
                };

                requestModel.InputFiles.Add(new InputFileModel()
                {
                    Name      = Path.GetFileName(settings.TestEnglishFile),
                    Password  = "",
                    InputUrl  = "",
                    InputBlob = FileConverter.ConvertFileToBase64(settings.TestEnglishFile),
                    InputType = "JPG",
                    PostFix   = ""
                });

                //end init
                String url  = "http://api.ocr-it.com:40000/api/jobs";
                var    json = JsonConvert.SerializeObject(requestModel);

                AssistProcessor processor = new AssistProcessor();
                //processor.MakeOcr(url,json);


                string baseUrl = "http://api.ocr-it.com:40000/api/Jobs?JobId=";
                string jobId   = "12dea613-f6f3-4982-baa0-60e4f452ae4b";

                string gUrl = baseUrl + jobId;

                string jobStatus = processor.GetJobStatus(gUrl);

                OcrResponseModel desModel    = JsonConvert.DeserializeObject <OcrResponseModel>(jobStatus);
                string           downloadDir = "d://OCRDownload//";
                foreach (var file in desModel.Download)
                {
                    string sName = DateTime.Now.ToString();

                    sName = sName.Replace(":", string.Empty);
                    sName = sName.Replace("-", string.Empty);
                    sName = sName.Replace(".", string.Empty);
                    sName = sName.Replace(",", string.Empty);
                    sName = sName.Replace(";", string.Empty);
                    sName = sName.Replace(" ", string.Empty);

                    string ext = "";

                    switch (file.OutputFormat)
                    {
                    case "PDF":
                        ext = "pdf";
                        break;

                    case "Text":
                        ext = "txt";
                        break;
                    }

                    sName = sName + "." + ext;

                    string downloadPath = Path.Combine(downloadDir, sName);

                    //   processor.DownloadFile(file.Uri,downloadPath);
                }
                //string outReq = JsonConvert.SerializeObject(model);
                Console.ReadKey();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception: " + exception.Message);
                Console.ReadKey();
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// check task
        /// </summary>
        public static void CheckStateTask(Tasks task)
        {
            try
            {
                AssistProcessor  assist        = new AssistProcessor();
                Assist           serviceAssist = new Assist();
                OcrResponseModel model         = new OcrResponseModel();
                model = JsonConvert.DeserializeObject <OcrResponseModel>(task.ResponseContent);

                serviceAssist.EmailSettings = serviceAssist.GetToEmailConversionSettings(task.UserId);
                if (serviceAssist.EmailSettings == null || serviceAssist.EmailSettings.ResponseSettings == null)
                {
                    return;
                }

                string jobStatus = assist.GetJobStatus(model.JobUrl);

                model = JsonConvert.DeserializeObject <OcrResponseModel>(jobStatus);

                if (model.Status.Equals("Finished"))
                {
                    string planState = serviceAssist.CheckSubscriptionPlan(task.UserId, model.Statistics.PagesArea);
                    if (planState != "OK")
                    {
                        serviceAssist.AddErrorToDocuments(task.Id, planState);
                        //update task
                        serviceAssist.UpdateTaskState(task.Id, 4);
                        //update documents
                        serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                        return;
                    }

                    List <Tuple <int, string> >    downloadIds      = new List <Tuple <int, string> >();
                    List <Tuple <string, string> > attachmentsLinks = new List <Tuple <string, string> >();



                    string pathToDownload = serviceAssist.GetSettingValueByName("MainPath");
                    string resultFolder   = serviceAssist.GetSettingValueByName("ResultFolder");
                    string jobPattern     = serviceAssist.GetSettingValueByName("ApiUrlJobState");

                    string downloadPath = Path.Combine(pathToDownload, resultFolder);

                    foreach (var file in model.Download)
                    {
                        string    jobId    = model.JobUrl.Replace(jobPattern, string.Empty);
                        Documents document = serviceAssist.GetToDocumentByTaskId(task.Id);
                        if (document == null)
                        {
                            serviceAssist.UpdateTaskState(task.Id, 4);
                            return;
                        }
                        string originalName = Path.GetFileNameWithoutExtension(document.OriginalFileName);
                        string fileExt      = serviceAssist.GetToFileExtension(file.OutputFormat);

                        Guid   g       = Guid.NewGuid();
                        string newName = g.ToString() + fileExt;

                        originalName = originalName + fileExt;
                        string filePath = Path.Combine(downloadPath, newName);
                        string error    = "";
                        assist.DownloadFile(file.Uri, filePath, ref error);
                        if (!File.Exists(filePath))
                        {
                            LogHelper.AddLog(error);
                            serviceAssist.AddErrorToDocuments(task.Id, error);
                            //update task
                            serviceAssist.UpdateTaskState(task.Id, 4);
                            //update documents
                            serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);
                            return;
                        }
                        //add document
                        int resultDocumentId = serviceAssist.AddResultDocument(task.Id, g, originalName, newName, filePath);
                        if (serviceAssist.EmailSettings.ResponseSettings.AddAttachment)
                        {
                            attachmentsLinks.Add(new Tuple <string, string>(filePath, originalName));
                        }
                        if (serviceAssist.EmailSettings.ResponseSettings.AddLink)
                        {
                            downloadIds.Add(new Tuple <int, string>(resultDocumentId, originalName));
                        }
                    }
                    if (serviceAssist.EmailSettings.ResponseSettings.SendReply)
                    {
                        string text = "DataCapture.Cloud received a conversion request form this e-mail address.  Here is your conversion result:";
                        serviceAssist.SendEmailResponse(task.UserId, downloadIds, attachmentsLinks,
                                                        serviceAssist.EmailSettings.ResponseSettings.CCResponse? serviceAssist.EmailSettings.ResponseSettings.Addresses:"",
                                                        text);
                    }
                    //update task
                    serviceAssist.UpdateTaskState(task.Id, 3);
                    //update documents
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 3);
                    // add statistics
                    serviceAssist.AddStatisctics(task.Id, model.Statistics);
                }
                else if (model.Status.Equals("Processing"))
                {
                }
                else if (!model.Status.Equals("Submitted"))
                {
                    LogHelper.AddLog("Error in JobStatus: " + jobStatus);
                    string errorText = "";
                    foreach (var ocrError in model.Errors)
                    {
                        errorText += ocrError.ErrorName + ": " + ocrError.ErrorMessage;
                    }
                    serviceAssist.AddErrorToDocuments(task.Id, errorText);
                    //update task
                    serviceAssist.UpdateTaskState(task.Id, 4);
                    //update documents
                    serviceAssist.UpdateDocumentStatesByTaskId(task.Id, 4);

                    if (serviceAssist.EmailSettings.ResponseSettings.SendReply)
                    {
                        serviceAssist.SendEmailResponseFail(task.UserId, "DataCapture.Cloud received a conversion request form this e - mail address. Error occured while processing request.", "");
                    }
                }
            }
            catch (Exception exception)
            {
                string innerException = exception.InnerException == null ? "" : exception.InnerException.Message;
                string methodName     = System.Reflection.MethodBase.GetCurrentMethod().Name;
                LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " +
                                 innerException);
            }
        }