private bool TryStartUpOcrEngine(OcrEngineType engineType)
        {
            try
            {
                if (engineType == OcrEngineType.LEAD)
                {
                    IOcrEngine engine = OcrEngineManager.CreateEngine(engineType, true);
                    ocrEngines.Add(engine);
                    ocrEngines[0].Startup(null, null, null, null);
                    SetEngineSettings(engine);
                }
                else
                {
                    var engine = OcrEngineManager.CreateEngine(engineType, true);
                    ocrEngines.Add(engine);
                    ocrEngines[0].Startup(null, null, null, null);
                }

                cleanUpOcrEngine = OcrEngineManager.CreateEngine(engineType, true); //engine for cleanup image
                cleanUpOcrEngine.Startup(null, null, null, null);
            }
            catch (Exception ex)
            {
                // log.Error(ex, "Error occurs while startup engines.");
                return(false);
            }

            //  log.Info($"{engineType} engine started successfully!");
            return(true);
        }
Ejemplo n.º 2
0
        private void Startup()
        {
            Properties.Settings settings = new Properties.Settings();

            string engineType = settings.OcrEngineType;

            // Show the engine selection dialog
            using (OcrEngineSelectDialog dlg = new OcrEngineSelectDialog(Messager.Caption, engineType, true))
            {
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    _ocrEngine     = dlg.OcrEngine;
                    _ocrEngineType = dlg.SelectedOcrEngineType;

                    _ocrEngineSettings.SetEngine(_ocrEngine);

                    // Add the selected engine name to the demo caption
                    Text = Text + " [" + _ocrEngineType.ToString() + " Engine]";
                }
                else
                {
                    // Close the demo
                    Close();
                }
            }
        }
Ejemplo n.º 3
0
        public static OcrResult Load(OcrImage image, string language, OcrEngineType targetType)
        {
            try
            {
                string ip = null;
                foreach (KeyValuePair <string, Dictionary <OcrEngineType, List <string> > > remoteType in RemoteTypes)
                {
                    if (remoteType.Value.ContainsKey(targetType))
                    {
                        ip = remoteType.Key;
                        break;
                    }
                }
                if (string.IsNullOrWhiteSpace(ip))
                {
                    return(OcrResult.Create(OcrResultType.NotInstalled));
                }

                using (WebClient webClient = new WebClient())
                {
                    string url = "http://" + ip + ":" + port + "/" + RunOcrCommand;

                    webClient.Proxy    = null;
                    webClient.Encoding = Encoding.UTF8;
                    string response = webClient.UploadString(url, string.Format("type={0}&language={1}&data={2}",
                                                                                targetType.ToString(), language, HttpUtility.UrlEncode(Convert.ToBase64String(image.ToBinary()))));

                    return(OcrResult.FromBinary(Convert.FromBase64String(HttpUtility.UrlDecode(response))));
                }
            }
            catch (Exception e)
            {
                return(OcrResult.Create(OcrResultType.Exception, e.ToString()));
            }
        }
Ejemplo n.º 4
0
        private void Startup()
        {
            Properties.Settings settings = new Properties.Settings();

            string engineType = settings.OcrEngineType;

            // Show the engine selection dialog
            using (OcrEngineSelectDialog dlg = new OcrEngineSelectDialog(Messager.Caption, engineType, true))
            {
                dlg.RasterCodecsInstance = _codecs;

                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    _ocrEngine     = dlg.OcrEngine;
                    _ocrEngineType = dlg.SelectedOcrEngineType;

                    // Add the selected engine name to the demo caption
                    Text = Text + " [" + _ocrEngineType.ToString() + " Engine]";

                    StartupEngine();

                    //load default image
                    LoadImage(true);
                    string message = String.Format(@"To use this demo: {0} 1) Load an image with text on it. {0} 2) Draw a rectangle using the mouse around the portion of text you want to recognize.", Environment.NewLine);
                    MessageBox.Show(message, "Instructions");

                    UpdateMyControls();
                }
                else
                {
                    // Close the demo
                    Close();
                }
            }
        }
Ejemplo n.º 5
0
 public StartConversionEventArgs(OcrEngineType engineType, string[] sourceFiles, string destinationDirectory, DocumentFormat format, bool loopContinuously)
 {
     _engineType           = engineType;
     _sourceFiles          = sourceFiles;
     _destinationDirectory = destinationDirectory;
     _format           = format;
     _loopContinuously = loopContinuously;
 }
Ejemplo n.º 6
0
        public static OcrEngine Create(OcrEngineType type, string language)
        {
            OcrEngine ocrEngine     = null;
            Type      ocrEngineType = GetType(type);

            if (ocrEngineType != null)
            {
                ocrEngine          = (OcrEngine)Activator.CreateInstance(ocrEngineType);
                ocrEngine.Language = language;
            }
            return(ocrEngine);
        }
Ejemplo n.º 7
0
        private static void UpdateRemoteEngines(string ip)
        {
            if (string.IsNullOrWhiteSpace(ip))
            {
                return;
            }

            try
            {
                using (WebClient webClient = new WebClient())
                {
                    string url = "http://" + ip + ":" + port + "/" + GetEnginesCommand;

                    webClient.Proxy    = null;
                    webClient.Encoding = Encoding.UTF8;
                    string response = webClient.DownloadString(url);

                    string[] splitted = response.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string value in splitted)
                    {
                        try
                        {
                            string[] splitted2 = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            string        typeStr   = splitted2[0];
                            List <string> languages = new List <string>();
                            for (int i = 1; i < splitted2.Length; i++)
                            {
                                languages.Add(splitted2[i]);
                            }

                            OcrEngineType type = (OcrEngineType)Enum.Parse(typeof(OcrEngineType), typeStr);
                            if (!OcrEngine.Create(type).IsInstalled)
                            {
                                if (!RemoteTypes.ContainsKey(ip))
                                {
                                    RemoteTypes[ip] = new Dictionary <OcrEngineType, List <string> >();
                                }

                                RemoteTypes[ip][type] = languages.ToList();
                                RemoteOcr.SetRemote(type);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 8
0
        public void Init(OcrEngineType ocrEngineType, DocumentWriter docWriter, DemoOptions options, int totalPages)
        {
            _ocrEngineType = ocrEngineType;
            _totalPages    = totalPages;

            SetDocumentWriterOptions(docWriter);
            _documentFormatSelector.SetDocumentWriter(docWriter, true);
            _documentFormatSelector.SetOcrEngineType(_ocrEngineType);

            InitFormats();

            LoadSettings(options);

            UpdateMyControls();
        }
 public void ShowError(Exception ex, IWin32Window owner, OcrEngineType engineType)
 {
     if (ex is OcrException)
      {
     OcrException oe = ex as OcrException;
     Messager.ShowError(owner, string.Format("LEADTOOLS Error\nCode: {0}\nMessage:{1}", oe.Code, ex.Message));
      }
      else if (ex is RasterException)
      {
     RasterException re = ex as RasterException;
     Messager.ShowError(owner, string.Format("OCR Error\nCode: {0}\nMessage:{1}", re.Code, ex.Message));
      }
      else
      {
     Messager.ShowError(owner, ex);
      }
 }
Ejemplo n.º 10
0
 public void ShowError(Exception ex, IWin32Window owner, OcrEngineType engineType)
 {
     if (ex is OcrException)
     {
         OcrException oe = ex as OcrException;
         Messager.ShowError(owner, string.Format("LEADTOOLS Error\nCode: {0}\nMessage:{1}", oe.Code, ex.Message));
     }
     else if (ex is RasterException)
     {
         RasterException re = ex as RasterException;
         Messager.ShowError(owner, string.Format("OCR Error\nCode: {0}\nMessage:{1}", re.Code, ex.Message));
     }
     else
     {
         Messager.ShowError(owner, ex);
     }
 }
Ejemplo n.º 11
0
        public static Type GetType(OcrEngineType type)
        {
            switch (type)
            {
            case OcrEngineType.Tesseract: return(typeof(TesseractOcr));

            case OcrEngineType.Windows: return(typeof(WindowsOcr));

            case OcrEngineType.Google: return(typeof(GoogleOcr));

            case OcrEngineType.GoogleVision: return(typeof(GoogleVisionOcr));

            case OcrEngineType.ABBYY: return(typeof(AbbyyOcr));

            case OcrEngineType.Nicomsoft: return(typeof(NicomsoftOcr));

            default: return(null);
            }
        }
Ejemplo n.º 12
0
        private static IOcrEngine CreateEngine(OcrEngineType engineType, byte[] documentWriterOptions, bool useThunk)
        {
            IOcrEngine ocrEngine = OcrEngineManager.CreateEngine(engineType, useThunk);

            ocrEngine.Startup(null, null, null, null);

            using (MemoryStream ms = new MemoryStream(documentWriterOptions))
            {
                ocrEngine.DocumentWriterInstance.LoadOptions(ms);
            }

            RasterCodecs codecs = ocrEngine.RasterCodecsInstance;

            // Use the new RasterizeDocumentOptions to default loading document files at 300 DPI
            codecs.Options.RasterizeDocument.Load.XResolution = 300;
            codecs.Options.RasterizeDocument.Load.YResolution = 300;
            codecs.Options.Pdf.Load.EnableInterpolate         = true;
            codecs.Options.Load.AutoFixImageResolution        = true;

            // We fine-tuned our app to only run a certain number of threads. The OCR engine can spawn it is own
            // threads to increase the performance of a single recognition process, however, we do not want this
            // in this scenario, these extra threads will decrease the overall performance of our app and we will
            // not be able to keep track of how many threads are actually running

            IOcrSettingManager settingManager = ocrEngine.SettingManager;

            // Disable multi-threaded recognition
            if (settingManager.IsSettingNameSupported("Recognition.Threading.MaximumThreads"))
            {
                settingManager.SetIntegerValue("Recognition.Threading.MaximumThreads", 1);
            }

            // Disable multi-threaded auto-zoning
            if (settingManager.IsSettingNameSupported("Recognition.Zoning.DisableMultiThreading"))
            {
                settingManager.SetBooleanValue("Recognition.Zoning.DisableMultiThreading", true);
            }

            return(ocrEngine);
        }
Ejemplo n.º 13
0
        public OcrResult Load(OcrImage image, string language)
        {
            try
            {
                OcrResult result = null;

                if (GetType() != typeof(RemoteOcr) && RemoteOcr.IsRemote(GetType()))
                {
                    OcrEngineType targetType = GetType(GetType());
                    RemoteOcr     remoteOcr  = new RemoteOcr(targetType);
                    result = remoteOcr.Load(image, language, language);
                }
                else if (!IsInstalled)
                {
                    return(OcrResult.Create(OcrResultType.NotInstalled));
                }
                else
                {
                    string apiLanguage = language == null ? null : GetSupportedLanguageName(language);
                    if (string.IsNullOrEmpty(apiLanguage))
                    {
                        return(OcrResult.Create(OcrResultType.LanguageNotSupported));
                    }
                    result = Load(image, language, apiLanguage);
                }

                if (result != null && result.Rect == OcrRect.Empty)
                {
                    result.Rect = new OcrRect(0, 0, image.Width, image.Height);
                }

                return(result);
            }
            catch (Exception e)
            {
                return(OcrResult.Create(OcrResultType.Exception, e.ToString()));
            }
        }
        public FormAutoRecognitionApi(string masterFormsPath, OcrEngineType engineType, string licensePath, string developerKey)
        {
            if (!TrySetLicense(licensePath, developerKey))
            {
                throw new Exception("Failed to setup license data.");
            }

            if (!TryStartUpRasterCodecs())
            {
                throw new Exception("Failed to startup raster codecs.");
            }

            if (!TryStartUpOcrEngine(engineType))
            {
                throw new Exception("Failed to startup ocr engine.");
            }


            if (!TryCreateRepository(masterFormsPath))
            {
                throw new Exception("Failed to load master forms.");
            }
        }
Ejemplo n.º 15
0
        private void Startup()
        {
            Properties.Settings settings = new Properties.Settings();

            string engineType = settings.OcrEngineType;

            // Show the engine selection dialog
            using (OcrEngineSelectDialog dlg = new OcrEngineSelectDialog(Messager.Caption, engineType, true))
            {
                dlg.RasterCodecsInstance = _codecs;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    _ocrEngine     = dlg.OcrEngine;
                    _ocrEngineType = dlg.SelectedOcrEngineType;

                    InitEngines();
                }
                else
                {
                    // Close the demo
                    Close();
                }
            }
        }
Ejemplo n.º 16
0
 public static bool IsRemote(OcrEngineType type)
 {
     return(IsRemote(OcrEngine.GetType(type)));
 }
Ejemplo n.º 17
0
        public void UpdateSettings()
        {
            if (IsDisposed)
            {
                return;
            }

            if (InvokeRequired)
            {
                Invoke((MethodInvoker) delegate { UpdateSettings(); });
                return;
            }

            isUpdating = true;

            translatableLanguages.Clear();
            ocrableLanguages.Clear();

            if (Program.ActiveOcrEngine != null)
            {
                if (Program.ActiveOcrEngine.IsInstalled)
                {
                    foreach (string language in Program.ActiveOcrEngine.SupportedLanguages.Keys)
                    {
                        CultureInfo culture = CultureInfo.GetCultureInfo(language);
                        if (!ocrableLanguages.Contains(culture.DisplayName))
                        {
                            ocrableLanguages.Add(culture.DisplayName);
                        }
                    }
                }
                else
                {
                    OcrEngineType engineType = OcrEngine.GetType(Program.ActiveOcrEngine.GetType());
                    foreach (Dictionary <OcrEngineType, List <string> > remoteTypes in OcrNetwork.RemoteTypes.Values)
                    {
                        if (remoteTypes.ContainsKey(engineType))
                        {
                            List <string> supportedLanguages = remoteTypes[engineType];
                            foreach (string language in supportedLanguages)
                            {
                                // Remote PC may support different cultures
                                //CultureInfo culture = CultureInfo.GetCultureInfo(language);
                                CultureInfo culture = null;
                                if (LocaleHelper.TryParseCulture(language, out culture) && !ocrableLanguages.Contains(culture.DisplayName))
                                {
                                    ocrableLanguages.Add(culture.DisplayName);
                                }
                            }
                        }
                    }
                }
            }

            if (Program.ActiveTranslator != null)
            {
                foreach (string language in Program.ActiveTranslator.SupportedLanguages.Keys)
                {
                    CultureInfo culture = CultureInfo.GetCultureInfo(language);
                    if (!translatableLanguages.Contains(culture.DisplayName))
                    {
                        translatableLanguages.Add(culture.DisplayName);
                    }
                }
            }

            availableEngines.Clear();
            foreach (var value in Enum.GetValues(typeof(OcrEngineType)))
            {
                OcrEngineType type = (OcrEngineType)value;
                if (RemoteOcr.IsRemote(type) || OcrEngine.Create(type).IsInstalled)
                {
                    availableEngines.Add(type);
                }
            }

            UpdateLanguageComboBoxStyle();
            UpdateEngineComboBoxStyle();
            RunOcr();

            isUpdating = false;
        }
Ejemplo n.º 18
0
        private void StartEngine()
        {
            if (_autoStart)
            {
                _btnCancel.Enabled   = false;
                _lblDownload.Visible = false;
                _lbDownload.Visible  = false;

                _lblStartEngine.Text = string.Format(DemosGlobalization.GetResxString(GetType(), "Resx_StartUp"), _engineProperty.Name);
                Application.DoEvents();

                IOcrEngine ocrEngine = null;

                try
                {
                    ocrEngine = OcrEngineManager.CreateEngine(_engineProperty.EngineType, false);

#if LT_CLICKONCE
                    ocrEngine.Startup(_rasterCodecsInstance, null, null, Application.StartupPath + @"\OCR Engine");
#else
                    ocrEngine.Startup(_rasterCodecsInstance, null, null, null);
#endif // #if LT_CLICKONCE



                    _lblStatus.ForeColor = SystemColors.ControlText;

                    if (_allowNoOcr)
                    {
                        _lblStatus.Text = DemosGlobalization.GetResxString(GetType(), "Resx_SuccessContinuing");
                    }
                    else
                    {
                        _lblStatus.Text = DemosGlobalization.GetResxString(GetType(), "Resx_SuccessStarting");
                    }

                    _ocrEngine             = ocrEngine;
                    _selectedOcrEngineType = _engineProperty.EngineType;

                    // Set document writer options
                    SetDocumentWriterOptions();

                    Application.DoEvents();
                    System.Threading.Thread.Sleep(1000);
                    DialogResult = DialogResult.OK;
                }
                catch (Exception ex)
                {
                    _lblStatus.ForeColor = Color.Red;

                    if (_allowNoOcr)
                    {
                        _lblStatus.Text = string.Format(DemosGlobalization.GetResxString(GetType(), "Resx_ErrorOCRCapabilities"), ex.Message, Environment.NewLine);
                    }
                    else
                    {
                        _lblStatus.Text = string.Format(DemosGlobalization.GetResxString(GetType(), "Resx_ErrorOCRWithoutCapabilities"), ex.Message, Environment.NewLine);
                    }

                    _lblDownload.Visible = false;
                    _lbDownload.Visible  = false;

                    if (_ocrEngine != null)
                    {
                        _ocrEngine.Dispose();
                    }
                }
                finally
                {
                    _btnCancel.Enabled = true;
                }
            }
            else
            {
                _ocrEngine             = null;
                _selectedOcrEngineType = _engineProperty.EngineType;
                DialogResult           = DialogResult.OK;
            }
        }
Ejemplo n.º 19
0
        public void Convert(DocumentWriter docWriter, OcrEngineType engineType, string[] sourceFiles, string destinationDirectory, DocumentFormat format, bool loopContinuously)
        {
            _docWriter            = docWriter;
            _engineType           = engineType;
            _sourceFiles          = sourceFiles;
            _destinationDirectory = destinationDirectory;
            _format           = format;
            _loopContinuously = loopContinuously;
            _logFileName      = Path.Combine(destinationDirectory, "_Log.txt");

            // number of documents to process together maximum of 8 or number of cores
            int maxThreadCount = Math.Min(8, Environment.ProcessorCount);
            int documentCount  = sourceFiles.Length;

            if (loopContinuously)
            {
                _lblInformation.Text = string.Format("Total number of documents is {0}, maximum number of threads is {1}, Iteration {2}", documentCount, maxThreadCount, _iteration + 1);
            }
            else
            {
                _lblInformation.Text = string.Format("Total number of documents is {0}, maximum number of threads is {1}", documentCount, maxThreadCount);
            }

            _pbProgress.Minimum          = 0;
            _pbProgress.Maximum          = documentCount;
            _pbProgress.Value            = 0;
            _btnConvertMoreFiles.Enabled = false;
            _btnCancel.Enabled           = true;
            _lbSuccess.Items.Clear();

            if (!loopContinuously)
            {
                _lbError.Items.Clear();
            }

            _aborted = false;

            byte[] docWriterOptions = null;
            using (MemoryStream ms = new MemoryStream())
            {
                docWriter.SaveOptions(ms);
                docWriterOptions = ms.ToArray();
            }

            try
            {
                _ocrEngine = CreateEngine(_engineType, docWriterOptions, false);
            }
            catch (Exception ex)
            {
                OnError(ex.Message);
                OnDone();
                return;
            }

            ThreadPool.QueueUserWorkItem((object state) =>
            {
                // Queue up to maxThreadCount of threads a time
                int sourceFileIndex = 0;
                int documentLeft    = documentCount;
                while (documentLeft > 0 && !_aborted)
                {
                    int batchCount = Math.Min(maxThreadCount, documentLeft);
                    _workItemCount = batchCount;

                    ClearQuarantine();

                    using (_batchFinishedEvent = new AutoResetEvent(false))
                    {
                        for (int i = 0; i < batchCount; i++)
                        {
                            WorkItemData data          = new WorkItemData();
                            data.DocumentWriterOptions = docWriterOptions;
                            data.EngineType            = engineType;
                            data.OcrEngine             = _ocrEngine;
                            data.SourceFile            = sourceFiles[i + sourceFileIndex];
                            data.DestinationDirectory  = destinationDirectory;
                            data.Format   = format;
                            data.FirstTry = true;

                            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), data);
                        }

                        _batchFinishedEvent.WaitOne();

                        //anything in the quarantine to retry?
                        List <string> quarantineList = new List <string>();
                        GetQuarantine(quarantineList);

                        for (int i = 0; i < quarantineList.Count; i++)
                        {
                            WorkItemData data          = new WorkItemData();
                            data.DocumentWriterOptions = docWriterOptions;
                            data.EngineType            = engineType;
                            data.OcrEngine             = _ocrEngine;
                            data.SourceFile            = quarantineList[i];
                            data.DestinationDirectory  = destinationDirectory;
                            data.Format   = format;
                            data.FirstTry = false;

                            ThreadProc(data);
                        }

                        sourceFileIndex += batchCount;
                        documentLeft    -= batchCount;
                    }
                }

                OnDone();
            });
        }
        private void Startup()
        {
            Properties.Settings settings = new Properties.Settings();

             string engineType = settings.OcrEngineType;

             // Show the engine selection dialog
             using (OcrEngineSelectDialog dlg = new OcrEngineSelectDialog(Messager.Caption, engineType, true))
             {
            dlg.RasterCodecsInstance = _codecs;

            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
               _ocrEngine = dlg.OcrEngine;
               _ocrEngineType = dlg.SelectedOcrEngineType;

               // Add the selected engine name to the demo caption
               Text = Text + " [" + _ocrEngineType.ToString() + " Engine]";

               StartupEngine();

               //load default image
               LoadImage(true);
               string message = String.Format(@"To use this demo: {0} 1) Load an image with text on it. {0} 2) Draw a rectangle using the mouse around the portion of text you want to recognize.", Environment.NewLine);
               MessageBox.Show(message, "Instructions");

               UpdateMyControls();
            }
            else
            {
               // Close the demo
               Close();
            }
             }
        }
Ejemplo n.º 21
0
        public static OcrResult LoadFile(OcrEngineType type, string file, string language)
        {
            OcrEngine ocrEngine = Create(type);

            return(ocrEngine.LoadFile(file, language));
        }
Ejemplo n.º 22
0
        public static void LoadFileAsync(OcrEngineType type, string file, string language, Action <OcrResult> callback)
        {
            OcrEngine ocrEngine = Create(type);

            ocrEngine.LoadFile(file, language);
        }
Ejemplo n.º 23
0
 public void SetOcrEngineType(OcrEngineType ocrEngineType)
 {
     _ocrEngineType = ocrEngineType;
 }
Ejemplo n.º 24
0
        public void Initialize()
        {
            isUpdating = true;

            Program.SetEngines(engines);
            Program.SetTranslators(translators);

            foreach (var value in Enum.GetValues(typeof(OcrEngineType)))
            {
                OcrEngineType type   = (OcrEngineType)value;
                OcrEngine     engine = OcrEngine.Create(type);
                if (engine != null)// && engine.IsInstalled)
                {
                    engines[type] = engine;
                    ocrEngineToolStripComboBox.Items.Add(type);
                }
            }
            if (ocrEngineToolStripComboBox.Items.Count > 0)
            {
                ocrEngineToolStripComboBox.SelectedIndex = 0;
            }

            foreach (var value in Enum.GetValues(typeof(TranslatorType)))
            {
                TranslatorType type       = (TranslatorType)value;
                Translator     translator = Translator.Create(type);
                if (translator != null && translator.IsEnabled)
                {
                    translators[type] = translator;
                    translateApiToolStripComboBox.Items.Add(type);
                }
            }
            if (translateApiToolStripComboBox.Items.Count > 0)
            {
                translateApiToolStripComboBox.SelectedIndex = 0;
            }

            foreach (var value in Enum.GetValues(typeof(OcrEngineProfile)))
            {
                OcrEngineProfile profile = (OcrEngineProfile)value;
                if (profile < OcrEngineProfile.Linear)
                {
                    ocrProfileToolStripComboBox.Items.Add(profile);
                }
                else
                {
                    for (int i = 2; i <= Program.ProfilesCount; i++)
                    {
                        ocrProfileToolStripComboBox.Items.Add(profile + " " + i + "x");
                    }
                }
            }
            if (ocrProfileToolStripComboBox.Items.Count > 0)
            {
                ocrProfileToolStripComboBox.SelectedIndex = 0;
            }

            UpdateLanguages();

            ocrEngineToolStripComboBox.ComboBox.PreviewKeyDown     += ComboBox_PreviewKeyDown;
            ocrProfileToolStripComboBox.ComboBox.PreviewKeyDown    += ComboBox_PreviewKeyDown;
            translateApiToolStripComboBox.ComboBox.PreviewKeyDown  += ComboBox_PreviewKeyDown;
            translateFromToolStripComboBox.ComboBox.PreviewKeyDown += ComboBox_PreviewKeyDown;
            translateToToolStripComboBox.ComboBox.PreviewKeyDown   += ComboBox_PreviewKeyDown;

            ocrEngineToolStripComboBox.ComboBox.MouseWheel     += toolStripComboBox_MouseWheel;
            ocrProfileToolStripComboBox.ComboBox.MouseWheel    += toolStripComboBox_MouseWheel;
            translateApiToolStripComboBox.ComboBox.MouseWheel  += toolStripComboBox_MouseWheel;
            translateFromToolStripComboBox.ComboBox.MouseWheel += toolStripComboBox_MouseWheel;
            translateToToolStripComboBox.ComboBox.MouseWheel   += toolStripComboBox_MouseWheel;

            comboBoxPrevIndex[ocrEngineToolStripComboBox]     = 0;
            comboBoxPrevIndex[ocrProfileToolStripComboBox]    = 0;
            comboBoxPrevIndex[translateApiToolStripComboBox]  = 0;
            comboBoxPrevIndex[translateFromToolStripComboBox] = 0;
            comboBoxPrevIndex[translateToToolStripComboBox]   = 0;

            translateFromToolStripComboBox.ComboBox.DrawItem += LanguageComboBox_DrawItem;
            translateFromToolStripComboBox.ComboBox.DrawMode  = DrawMode.OwnerDrawFixed;

            translateToToolStripComboBox.ComboBox.DrawItem += LanguageComboBox_DrawItem;
            translateToToolStripComboBox.ComboBox.DrawMode  = DrawMode.OwnerDrawFixed;

            ocrEngineToolStripComboBox.ComboBox.DrawItem += EngineComboBox_DrawItem;
            ocrEngineToolStripComboBox.ComboBox.DrawMode  = DrawMode.OwnerDrawFixed;

            ocrImagePanel.ImageChanged += ocrImagePanel_ImageChanged;
            OcrHelper.Complete         += OcrHelper_Complete;
            OcrHelper.Start            += OcrHelper_Start;
            TranslateHelper.Start      += TranslateHelper_Start;
            TranslateHelper.Complete   += TranslateHelper_Complete;

            string from = Program.Settings.LanguageProfiles.Slot1;
            string to   = Program.Settings.TargetLanguage.TargetLanguage;

            if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
            {
                int fromIndex = translateFromToolStripComboBox.Items.IndexOf(from);
                int toIndex   = translateToToolStripComboBox.Items.IndexOf(to);
                if (fromIndex >= 0 && toIndex >= 0)
                {
                    translateFromToolStripComboBox.SelectedIndex = fromIndex;
                    translateToToolStripComboBox.SelectedIndex   = toIndex;
                }
            }

            hotkeys.KeyPressed += hotkeys_KeyPressed;
            hotkeys.ClearHotKey();
            hotkeys.RegisterHotKey(Program.Settings.AutoTyper.Hotkey);

            isUpdating = false;
            SettingsChanged();

            OcrNetwork.Update();
        }
Ejemplo n.º 25
0
            private void Process(HttpListenerContext context)
            {
                try
                {
                    string url = context.Request.Url.OriginalString;

                    string response = string.Empty;

                    if (url.Contains("favicon.ico"))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.OutputStream.Close();
                        return;
                    }

                    if (url.Contains(GetEnginesCommand))
                    {
                        if (Program.Engines != null)
                        {
                            Dictionary <OcrEngineType, OcrEngine> engines = new Dictionary <OcrEngineType, OcrEngine>(Program.Engines);
                            foreach (OcrEngine engine in engines.Values)
                            {
                                if (engine.IsInstalled)
                                {
                                    string languages = string.Empty;
                                    foreach (string language in engine.SupportedLanguages.Keys)
                                    {
                                        languages += language + ",";
                                    }
                                    languages = languages.TrimEnd(',');
                                    response += engine.Name + "," + languages + "|";
                                }
                            }
                            response = response.TrimEnd('|', ',');
                        }
                    }
                    else if (url.Contains(RunOcrCommand))
                    {
                        Dictionary <string, string> postData = GetPostData(context);
                        OcrEngineType type     = (OcrEngineType)Enum.Parse(typeof(OcrEngineType), postData["type"]);
                        string        language = postData["language"];
                        byte[]        data     = Convert.FromBase64String(postData["data"]);
                        OcrImage      image    = OcrImage.FromBinary(data);
                        OcrResult     result   = null;

                        try
                        {
                            result = OcrEngine.Create(type).Load(image, language);
                        }
                        catch (Exception e)
                        {
                            result = OcrResult.Create(OcrResultType.Exception, e.ToString());
                        }

                        try
                        {
                            response = HttpUtility.UrlEncode(Convert.ToBase64String(result.ToBinary()));
                        }
                        catch
                        {
                        }
                    }

                    byte[] resposeBuffer = Encoding.UTF8.GetBytes(response.ToString());

                    context.Response.ContentType     = "text/html";
                    context.Response.ContentEncoding = Encoding.UTF8;
                    context.Response.ContentLength64 = resposeBuffer.Length;
                    context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                    context.Response.AddHeader("Last-Modified", DateTime.Now.ToString("r"));
                    context.Response.OutputStream.Write(resposeBuffer, 0, resposeBuffer.Length);
                    context.Response.OutputStream.Flush();
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                }
                catch
                {
                }

                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.OutputStream.Close();
            }
Ejemplo n.º 26
0
 public static void SetRemote(OcrEngineType type)
 {
     remoteTypes[OcrEngine.GetType(type)] = type;
 }
Ejemplo n.º 27
0
 public static OcrEngine Create(OcrEngineType type)
 {
     return(Create(type, null));
 }
        public DocumentFormatOptionsDialog(OcrEngineType ocrEngineType, DocumentWriter docWriter, DocumentFormat format, int totalPages)
        {
            InitializeComponent();

            _ocrEngineType  = ocrEngineType;
            _documentWriter = docWriter;
            _format         = format;
            _totalPages     = totalPages;

            _optionsTabControl.TabPages.Clear();

            switch (_format)
            {
            case DocumentFormat.Pdf:
                // Update the PDF options page
            {
                _optionsTabControl.TabPages.Add(_pdfOptionsTabPage);

                PdfDocumentOptions pdfOptions = _documentWriter.GetOptions(DocumentFormat.Pdf) as PdfDocumentOptions;

                // Clone it in case we change it in the Advance PDF options dialog
                _pdfOptions = pdfOptions.Clone() as PdfDocumentOptions;

                Array a = Enum.GetValues(typeof(PdfDocumentType));
                foreach (PdfDocumentType i in a)
                {
                    // PDFA does NOT support Arabic characters so we are not adding it in case of Arabic OCR engine.
                    if (ocrEngineType == OcrEngineType.OmniPageArabic && i == PdfDocumentType.PdfA)
                    {
                        continue;
                    }

                    _pdfDocumentTypeComboBox.Items.Add(i);
                }
                _pdfDocumentTypeComboBox.SelectedItem = pdfOptions.DocumentType;

                _pdfImageOverTextCheckBox.Checked = pdfOptions.ImageOverText;
                _pdfLinearizedCheckBox.Checked    = pdfOptions.Linearized;
            }
            break;

            case DocumentFormat.Doc:
                // Update the DOC options page
            {
                _optionsTabControl.TabPages.Add(_docOptionsTabPage);
                DocDocumentOptions docOptions = _documentWriter.GetOptions(DocumentFormat.Doc) as DocDocumentOptions;
                _docFramedCheckBox.Checked = (docOptions.TextMode == DocumentTextMode.Framed) ? true : false;
            }
            break;

            case DocumentFormat.Docx:
                // Update the DOCX options page
            {
                _optionsTabControl.TabPages.Add(_docxOptionsTabPage);
                DocxDocumentOptions docxOptions = _documentWriter.GetOptions(DocumentFormat.Docx) as DocxDocumentOptions;
                _docxFramedCheckBox.Checked = (docxOptions.TextMode == DocumentTextMode.Framed) ? true : false;
            }
            break;

            case DocumentFormat.Rtf:
                // Update the RTF options page
            {
                _optionsTabControl.TabPages.Add(_rtfOptionsTabPage);
                RtfDocumentOptions rtfOptions = _documentWriter.GetOptions(DocumentFormat.Rtf) as RtfDocumentOptions;
                _rtfFramedCheckBox.Checked = (rtfOptions.TextMode == DocumentTextMode.Framed) ? true : false;
            }
            break;

            case DocumentFormat.Html:
                // Update the HTML options page
            {
                _optionsTabControl.TabPages.Add(_htmlOptionsTabPage);

                HtmlDocumentOptions htmlOptions = _documentWriter.GetOptions(DocumentFormat.Html) as HtmlDocumentOptions;

                Array a = Enum.GetValues(typeof(DocumentFontEmbedMode));
                foreach (DocumentFontEmbedMode i in a)
                {
                    _htmlEmbedFontModeComboBox.Items.Add(i);
                }
                _htmlEmbedFontModeComboBox.SelectedItem = htmlOptions.FontEmbedMode;

                _htmlUseBackgroundColorCheckBox.Checked = htmlOptions.UseBackgroundColor;

                _htmlBackgroundColorValueLabel.BackColor = Leadtools.Demos.Converters.ToGdiPlusColor(htmlOptions.BackgroundColor);

                _htmlBackgroundColorLabel.Enabled      = _htmlUseBackgroundColorCheckBox.Checked;
                _htmlBackgroundColorValueLabel.Enabled = _htmlUseBackgroundColorCheckBox.Checked;
                _htmlBackgroundColorButton.Enabled     = _htmlUseBackgroundColorCheckBox.Checked;
            }
            break;

            case DocumentFormat.Text:
                // Update the TEXT options page
            {
                _optionsTabControl.TabPages.Add(_textOptionsTabPage);

                TextDocumentOptions textOptions = _documentWriter.GetOptions(DocumentFormat.Text) as TextDocumentOptions;

                Array a = Enum.GetValues(typeof(TextDocumentType));
                foreach (TextDocumentType i in a)
                {
                    if (i == TextDocumentType.Ansi && ocrEngineType == OcrEngineType.OmniPageArabic)
                    {
                        continue;
                    }

                    _textDocumentTypeComboBox.Items.Add(i);
                }
                _textDocumentTypeComboBox.SelectedItem = textOptions.DocumentType;

                _textAddPageNumberCheckBox.Checked = textOptions.AddPageNumber;
                _textAddPageBreakCheckBox.Checked  = textOptions.AddPageBreak;
                _textFormattedCheckBox.Checked     = textOptions.Formatted;
            }
            break;

            case DocumentFormat.AltoXml:
                // Update the ALTOXML options page
            {
                _optionsTabControl.TabPages.Add(_altoXmlOptionsTabPage);
                AltoXmlDocumentOptions altoXmlOptions = _documentWriter.GetOptions(DocumentFormat.AltoXml) as AltoXmlDocumentOptions;

                Array a = Enum.GetValues(typeof(AltoXmlMeasurementUnit));
                foreach (AltoXmlMeasurementUnit i in a)
                {
                    _altoXmlMeasurementUnitComboBox.Items.Add(i);
                }
                _altoXmlMeasurementUnitComboBox.SelectedItem = altoXmlOptions.MeasurementUnit;

                _altoXmlFileNameTextBox.Text               = altoXmlOptions.FileName;
                _altoXmlSoftwareCreatorTextBox.Text        = altoXmlOptions.SoftwareCreator;
                _altoXmlSoftwareNameTextBox.Text           = altoXmlOptions.SoftwareName;
                _altoXmlApplicationDescriptionTextBox.Text = altoXmlOptions.ApplicationDescription;
                _altoXmlFormattedCheckBox.Checked          = altoXmlOptions.Formatted;
                _altoXmlIndentationTextBox.Text            = altoXmlOptions.Indentation;
                _altoXmlSortCheckBox.Checked               = altoXmlOptions.Sort;
                _altoXmlPlainTextCheckBox.Checked          = altoXmlOptions.PlainText;
                _altoXmlShowGlyphInfoCheckBox.Checked      = altoXmlOptions.ShowGlyphInfo;
                _altoXmlShowGlyphVariantsCheckBox.Checked  = altoXmlOptions.ShowGlyphVariants;
            }
            break;

            case DocumentFormat.Ltd:
            {
                _optionsTabControl.TabPages.Add(_ldOptionsTabPage);
            }
            break;

            case DocumentFormat.Emf:
            {
                _optionsTabControl.TabPages.Add(_emfOptionsTabPage);
            }
            break;

            default:
            {
                _optionsTabControl.TabPages.Add(_emptyOptionsTabPage);
                _emptyOptionsTabPage.Text = string.Format("{0} Options", DocumentWriter.GetFormatFileExtension(_format).ToUpperInvariant());
            }
            break;
            }

            Text = DocumentWriter.GetFormatFriendlyName(_format) + " " + DemosGlobalization.GetResxString(GetType(), "Resx_Options");

            UpdateUIState();
        }
Ejemplo n.º 29
0
 public RemoteOcr(OcrEngineType targetType)
 {
     TargetType = targetType;
 }
Ejemplo n.º 30
0
        private bool LoadSettings()
        {
            Properties.Settings settings = new Properties.Settings();

            string engineType = settings.OcrEngineType;

            // Show the engine selection dialog
            using (OcrEngineSelectDialog dlg = new OcrEngineSelectDialog(Messager.Caption, engineType, true))
            {
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    _ocrEngine     = dlg.OcrEngine;
                    _ocrEngineType = dlg.SelectedOcrEngineType;

                    RasterCodecs codecs = _ocrEngine.RasterCodecsInstance;
#if !LEADTOOLS_V175_OR_LATER
                    codecs.Options.Pdf.Load.XResolution           = 300;
                    codecs.Options.Pdf.Load.YResolution           = 300;
                    codecs.Options.RasterizeDocument.Load.Enabled = true;
                    codecs.Options.Load.AutoFixImageResolution    = true;
#endif

#if LEADTOOLS_V16_OR_LATER
                    // Use the new RasterizeDocumentOptions to default loading document files at 300 DPI
                    codecs.Options.RasterizeDocument.Load.XResolution = 300;
                    codecs.Options.RasterizeDocument.Load.YResolution = 300;
                    codecs.Options.Pdf.Load.EnableInterpolate         = true;
                    codecs.Options.Load.AutoFixImageResolution        = true;
#endif // #if LEADTOOLS_V16_OR_LATER
                }
                else
                {
                    return(false);
                }
            }

            UpdateDocumentFormats();

            string twainSourceName = settings.TwainSourceName;
            if (!string.IsNullOrEmpty(twainSourceName))
            {
                try
                {
                    _twainSession.SelectSource(twainSourceName);
                }
                catch
                {
                }
            }

            _tbFinalDocumentFileName.Text = settings.DocumentFileName.Trim();
            if (string.IsNullOrEmpty(_tbFinalDocumentFileName.Text))
            {
                _tbFinalDocumentFileName.Text = Path.Combine(Path.GetFullPath(DemosGlobal.ImagesFolder), "OcrTwainScanningDemo");
            }

            SelectFormatByName(settings.DocumentFormat);

            _documentFormatSelector_SelectedFormatChanged(null, EventArgs.Empty);

            return(true);
        }