Esempio n. 1
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()));
            }
        }
Esempio n. 2
0
        public OcrResult LoadFile(string file, string language)
        {
            try
            {
                if (!File.Exists(file))
                {
                    return(OcrResult.Create(OcrResultType.InvalidFilePath));
                }

                OcrImage image = new OcrImage();
                try
                {
                    using (Image bitmap = Bitmap.FromFile(file))
                    {
                        image.Width  = bitmap.Width;
                        image.Height = bitmap.Height;
                    }
                    image.Data = File.ReadAllBytes(file);
                    // Path is mostly ignored, remove it for now to stop it being sent over the network
                    //image.Path = file;
                }
                catch (Exception e)
                {
                    return(OcrResult.Create(OcrResultType.InvalidFile, e.ToString()));
                }

                return(Load(image, language));
            }
            catch (Exception e)
            {
                return(OcrResult.Create(OcrResultType.Exception, e.ToString()));
            }
        }
Esempio n. 3
0
        //public string Path { get; set; }

        public static OcrImage FromBinary(byte[] buffer)
        {
            try
            {
                using (BinaryReader reader = new BinaryReader(new MemoryStream(buffer)))
                {
                    OcrImage image = new OcrImage();

                    uint dataLen = reader.ReadUInt32();
                    image.Data = new byte[dataLen];
                    if (dataLen > 0)
                    {
                        image.Data = reader.ReadBytes((int)dataLen);
                    }
                    image.Width  = reader.ReadInt32();
                    image.Height = reader.ReadInt32();
                    //image.Path = reader.ReadString();

                    return(image);
                }
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 4
0
        public override OcrResult Load(OcrImage image, string language, string apiLanguage)
        {
            string inputPath  = null;
            string outputPath = null;

            try
            {
                inputPath  = GetTempPath();
                outputPath = GetTempPath(false);
                string spacing  = AllowsSpacing(language) ? string.Empty : "--nospacing";
                string newLines = AllowsNewLines(language) ? string.Empty : "--nolines";

                File.WriteAllBytes(inputPath, image.Data);
                RunCommand("\"{0}\" \"{1}\" \"{2}\" {3} {4}", apiLanguage, inputPath, outputPath, spacing, newLines);

                if (File.Exists(outputPath))
                {
                    string[] lines = File.ReadAllLines(outputPath);

                    OcrResult result = new OcrResult();
                    result.ResultType = OcrResultType.Success;
                    foreach (string line in lines)
                    {
                        result.AddLine(line);
                    }
                    return(result);
                }
                else
                {
                    return(OcrResult.Create(OcrResultType.Failed));
                }
            }
            catch (Exception e)
            {
                return(OcrResult.Create(OcrResultType.Exception, e.ToString()));
            }
            finally
            {
                try
                {
                    if (!string.IsNullOrEmpty(inputPath))
                    {
                        File.Delete(inputPath);
                    }
                }
                catch { }
                try
                {
                    if (!string.IsNullOrEmpty(outputPath))
                    {
                        File.Delete(outputPath);
                    }
                }
                catch { }
            }
        }
Esempio n. 5
0
 protected bool SaveLoadableImage(OcrImage image)
 {
     try
     {
         File.WriteAllBytes(GetLoadableImagePath(), image.Data);
         return(true);
     }
     catch { }
     return(false);
 }
Esempio n. 6
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()));
            }
        }
Esempio n. 7
0
        public override OcrResult Load(OcrImage image, string language, string apiLanguage)
        {
            try
            {
                if (!SaveLoadableImage(image))
                {
                    return(OcrResult.Create(OcrResultType.InvalidFilePath));
                }

                Program.ClipSync.Text = null;

                if (automation.Run())
                {
                    string text = WaitForClipSync();
                    if (!string.IsNullOrEmpty(text))
                    {
                        return(new OcrResult(text));
                    }
                    return(OcrResult.Create(OcrResultType.AutomationFailed));
                }
                else
                {
                    //System.Windows.Forms.MessageBox.Show("Failed at index: " + automation.Index);
                }

                return(OcrResult.Create(OcrResultType.AutomationFailed));
            }
            finally
            {
                for (int i = 0; i < 10; i++)
                {
                    automation.SendKey(Keys.Escape);
                    System.Threading.Thread.Sleep(10);
                }
            }
        }
Esempio n. 8
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();
            }
Esempio n. 9
0
        public override OcrResult Load(OcrImage image, string language, string apiLanguage)
        {
            string inputPath   = null;
            string outputPath  = null;
            string outputPath2 = null;
            string outputPath3 = null;

            try
            {
                inputPath   = GetTempPath();
                outputPath  = GetTempPath(false);
                outputPath2 = outputPath + (IncludeTextRegions ? ".hocr" : ".txt");
                outputPath3 = outputPath + (IncludeTextRegions ? ".txt" : ".hocr");

                File.WriteAllBytes(inputPath, image.Data);
                RunCommand("\"{0}\" \"{1}\" -l {2} {3}", inputPath, outputPath, apiLanguage, IncludeTextRegions ? "-c tessedit_create_hocr=1" : string.Empty);

                OcrResult result = null;

                if (IncludeTextRegions)
                {
                    result = OcrXml.FromFile(outputPath2);
                }
                else
                {
                    string[] lines = File.ReadAllLines(outputPath2);

                    result            = new OcrResult();
                    result.ResultType = OcrResultType.Success;
                    foreach (string line in lines)
                    {
                        result.AddLine(line);
                    }
                }

                return(result);
            }
            catch (Exception e)
            {
                return(OcrResult.Create(OcrResultType.Exception, e.ToString()));
            }
            finally
            {
                try
                {
                    if (!string.IsNullOrEmpty(inputPath))
                    {
                        File.Delete(inputPath);
                    }
                }
                catch { }
                try
                {
                    if (!string.IsNullOrEmpty(outputPath))
                    {
                        File.Delete(outputPath);
                    }
                }
                catch { }
                try
                {
                    if (!string.IsNullOrEmpty(outputPath2))
                    {
                        File.Delete(outputPath2);
                    }
                }
                catch { }
                try
                {
                    if (!string.IsNullOrEmpty(outputPath3))
                    {
                        File.Delete(outputPath3);
                    }
                }
                catch { }
            }
        }
Esempio n. 10
0
        public override OcrResult Load(OcrImage image, string language, string apiLanguage)
        {
            try
            {
                Automation automation = new Automation();
                automation.UseImageCaching = true;
                automation.Path            = System.IO.Path.Combine("Images", "ABBYY");

                // Task icon
                automation.AddReferenceImage("AbbyyReference.png");

                // Task icon
                automation.AddStartImage("AbbyyStart.png");

                // Click on language text box
                automation.AddRelativeClick(450, 50);
                //automation.AddWait(50);

                // Select language text box text
                automation.AddSelectAll();
                automation.AddWait(50);

                automation.AddText(apiLanguage, true);
                automation.AddWait(50);
                automation.AddKey(Keys.Enter);
                automation.AddWait(50);
                automation.AddKey(Keys.Enter);

                // Click open image button
                automation.AddRelativeClick(140, 30);

                // Wait for the open image dialog
                automation.AddWaitImage("OpenImage.png");

                // Type the file name
                automation.AddOpenImage();

                // Wait for the complete dialog
                automation.AddWaitImage("Complete.png");

                // Press escape to close complete dialog
                automation.AddKey(Keys.Escape);

                // Seems to freeze if we don't do this
                for (int i = 0; i < 15; i++)
                {
                    // Click the ocr text box
                    automation.AddMoveMouseImageOffset("OutputOffset.png", 50 + ((i + 1) * 1), 0 + ((i + 1) * 1));
                    automation.AddWait(100);
                }

                automation.AddClickableImageOffset("OutputOffset.png", 50, 0);
                //automation.AddWait(50);

                automation.AddSelectAll();
                //automation.AddWait(50);

                automation.AddCopy();

                if (!SaveLoadableImage(image))
                {
                    return(OcrResult.Create(OcrResultType.InvalidFilePath));
                }

                // Clear the clipboard
                Clipboard.Clear();

                if (automation.Run())
                {
                    string text = WaitForClipboard();
                    if (!string.IsNullOrEmpty(text))
                    {
                        return(new OcrResult(text));
                    }
                    return(OcrResult.Create(OcrResultType.AutomationFailed));
                }
                else
                {
                    //System.Windows.Forms.MessageBox.Show("Failed at index: " + automation.Index);
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
                return(OcrResult.Create(OcrResultType.Exception, e.ToString()));
            }

            return(OcrResult.Create(OcrResultType.AutomationFailed));
        }
Esempio n. 11
0
 public override OcrResult Load(OcrImage image, string language, string apiLanguage)
 {
     return(OcrNetwork.Load(image, language, TargetType));
 }
Esempio n. 12
0
 public abstract OcrResult Load(OcrImage image, string language, string apiLanguage);
Esempio n. 13
0
        public override OcrResult Load(OcrImage image, string language, string apiLanguage)
        {
            OcrRequests request = new OcrRequests()
            {
                requests = new OcrRequest[1]
                {
                    new OcrRequest()
                    {
                        image = new OcrRequestImage()
                        {
                            content = Convert.ToBase64String(image.Data)
                        },
                        features = new OcrRequestFeature[1]
                        {
                            new OcrRequestFeature()
                            {
                                type       = "TEXT_DETECTION",
                                maxResults = 1
                            }
                        }
                    }
                }
            };

            string requestJson = JSONSerializer <OcrRequests> .Serialize(request);

            using (GZipWebClient webClient = new GZipWebClient())
            {
                string key = Program.Settings.KeyInfo.Key;

                if (string.IsNullOrEmpty(key))
                {
                    key = GetDefaultKey();
                }

                string url = "https://vision.googleapis.com/v1/images:annotate?key=" + key;

                webClient.Proxy    = null;
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType]    = "application/json";
                webClient.Headers[HttpRequestHeader.Accept]         = "application/json";
                webClient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
                string json = webClient.UploadString(url, requestJson);

                string       result    = string.Empty;
                OcrResponses responses = JSONSerializer <OcrResponses> .DeSerialize(json);

                foreach (OcrResponse response in responses.responses)
                {
                    foreach (OcrTextAnnotation annotation in response.textAnnotations)
                    {
                        if (!string.IsNullOrEmpty(annotation.locale))
                        {
                            result += annotation.description;
                        }
                    }
                }
                result = result.TrimEnd('\r', '\n');
                return(new OcrResult(result));
            }
        }