public TencentOcrClient(string secretId, string secretKey, string region) { Name = "Tencent OCR"; _actionDictionary = BuildActionDictionary(); var credential = new Credential { SecretId = secretId, SecretKey = secretKey }; var httpProfile = new HttpProfile { Endpoint = "ocr.tencentcloudapi.com" }; var clientProfile = new ClientProfile { HttpProfile = httpProfile, SignMethod = "TC3-HMAC-SHA256" }; _tencentOcrClient = new OcrClient(credential, region, clientProfile); }
public static string recognize(string img) { try { Credential cred = new Credential { SecretId = SecretID, SecretKey = SecretKey }; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("ocr.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; OcrClient client = new OcrClient(cred, "ap-beijing", clientProfile); GeneralBasicOCRRequest req = new GeneralBasicOCRRequest(); string strParams = String.Format("{{\"ImageBase64\":\"{0}\"}}", img); req = GeneralBasicOCRRequest.FromJsonString <GeneralBasicOCRRequest>(strParams); GeneralBasicOCRResponse resp = client.GeneralBasicOCRSync(req); JavaScriptSerializer js = new JavaScriptSerializer(); var dic = js.Deserialize <Dictionary <string, object> >(AbstractModel.ToJsonString(resp)); var list = (System.Collections.ArrayList)dic["TextDetections"]; var output = new StringBuilder(); foreach (var item in list) { output.Append(((Dictionary <string, object>)item)["DetectedText"]).Append("\n"); } return(output.ToString()); } catch (Exception e) { return(e.ToString()); } }
public void UnsetUriThrows() { // Arrange OcrClient client = new OcrClient(API_KEY, REGION); // Act // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => client.GetRegionalUri(OcrRegions.NotSet)); }
public WFwOcrClient(OcrOptions ocr, ILogger <WFwOcrClient> l) { ocrOptions = ocr; logger = l; Credential cred = new Credential { SecretId = ocr.SecretId, SecretKey = ocr.SecretKey }; client = new OcrClient(cred, "ap-guangzhou"); }
public void ParsesEmptyQueryString() { // Arrange OcrClient client = new OcrClient(API_KEY, REGION); // Act string parsedString = client.ParseQueryString(); // Assert Assert.NotNull(parsedString); Assert.Equal(string.Empty, parsedString); }
/// <summary> /// OCR 通用高精度印刷体识别(默认url) /// </summary> /// <param name="Image">图片</param> /// <param name="Type">1:url,2:base64</param> public static TencentOCRResult GeneralAccurateOCR(string Image, int?Type = 1) { try { enterpriseWeChatHelper.OCRFilter(); Credential cred = new Credential { SecretId = ConfigurationUtil.TencentSecretId, SecretKey = ConfigurationUtil.TencentSecretKey }; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("ocr.ap-guangzhou.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; OcrClient client = new OcrClient(cred, "ap-guangzhou", clientProfile); GeneralAccurateOCRRequest req = new GeneralAccurateOCRRequest(); if (Type == null || Type == 1 || Type == 0) { req.ImageUrl = Image; } else { req.ImageBase64 = Image; } enterpriseWeChatHelper.SetHashIncr(1);//优先扣除库存 GeneralAccurateOCRResponse resp = client.GeneralAccurateOCR(req). ConfigureAwait(false).GetAwaiter().GetResult(); return(new TencentOCRResult { WordList = resp.TextDetections .Select(s => new Word { text = s.DetectedText.Replace(" ", "").ToLower() }) .Where(s => !string.IsNullOrEmpty(s.text)) .ToList() }); } catch (Exception e) { if (e.Message != "操作Redis失败")//如果请求接口失败则加回来 { enterpriseWeChatHelper.SetHashIncr(-1); } throw new Exception(e.Message); } }
public async Task <List <string> > AbbyyRunnerAsync(AuthInfo authInfo, string FilePath) { var client = new OcrClient(authInfo); var imageParams = new ImageProcessingParams { ExportFormats = new[] { ExportFormat.Txt }, Language = "English", ReadBarcodes = true, CorrectOrientation = true, }; var fileStream = new FileStream(FilePath, FileMode.Open); var taskInfo = await client.ProcessImageAsync(imageParams, fileStream, Path.GetFileName(FilePath), waitTaskFinished : true); return(taskInfo.ResultUrls); }
public FolderWatcher(string sourcePath) { this._sourcePath = sourcePath; this._orcClient = new OcrClient(); var configuration = new MapperConfiguration(cfg => { cfg.CreateMap <string, decimal>().ConvertUsing(new DecimalTypeConverter()); cfg.CreateMap <PolicyInfoDTO, PolicyInfo>(); }); configuration.AssertConfigurationIsValid(); _mapper = configuration.CreateMapper(); }
public void CastsPostResponseToType() { // Arrange byte[] contentBytes = File.ReadAllBytes(@"..\..\..\OcrTests\AboutUs.png"); OcrClient client = new OcrClient(API_KEY, REGION); string url = client.GetRegionalUri(REGION).ToString(); object response; // Act using (ByteArrayContent content = new ByteArrayContent(contentBytes)) { response = Task.Run(() => client.Post <OcrResponse>(url, content, "Ocp-Apim-Subscription-Key", API_KEY)).Result; } // Assert Assert.NotNull(response); Assert.IsType(typeof(OcrResponse), response); }
public async Task <RecognizeResponse> ExecuteAsync(CancellationToken token) { var image = await GetFileAsync(token); image = PreProcessor.Process(image); var ocrResult = await OcrClient.RecognizeAsync(image, token).ConfigureAwait(false); switch (ocrResult.Status) { case OcrStatus.Success: var text = PostProcessor.Process(ocrResult.Text); return(new RecognizeResponse(text)); case OcrStatus.Error: throw new Exception(ocrResult.Error); default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// 身份证识别 /// </summary> /// <param name="inputParm">输入参数</param> /// <returns></returns> public async Task <IdCard> GetIdCard(InputParm inputParm) { var credential = new Credential(); var config = Ioc.GetService <IConfiguration>(); credential.SecretId = config.GetSection("Tencent:SecretId").Value ?? ""; credential.SecretKey = config.GetSection("Tencent:SecretKey").Value ?? ""; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("ocr.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; OcrClient client = new OcrClient(credential, "ap-guangzhou", clientProfile); IDCardOCRRequest req = new IDCardOCRRequest(); req = IDCardOCRRequest.FromJsonString <IDCardOCRRequest>(Json.ToJson(inputParm)); IDCardOCRResponse resp = await client.IDCardOCR(req); return(resp.MapTo <IdCard>()); }
public void RecognizesWithLanguage(OcrLanguages language) { // Arrange OcrClient client = new OcrClient(API_KEY, REGION); OcrResponse response; // Act response = Task.Run(() => client.RecognizeAsync(new Uri(@"https://oxfordportal.blob.core.windows.net/vision/doc-vision-overview-ocr01.png"), language: language)).Result; // Assert Assert.NotNull(response); Assert.Null(response.ErrorCode); Assert.Equal(response.Language, "en"); Assert.NotNull(response.Regions); Assert.NotEmpty(response.Regions); Assert.NotEqual(response.Regions.First().BoundingBox.Left, default(int)); Assert.NotEqual(response.Regions.First().BoundingBox.Top, default(int)); Assert.NotEqual(response.Regions.First().BoundingBox.Width, default(int)); Assert.NotEqual(response.Regions.First().BoundingBox.Height, default(int)); Assert.NotNull(response.Regions.First().Lines); Assert.NotEmpty(response.Regions.First().Lines); Assert.NotNull(response.Regions.First().Lines.First().Words); }
public void RecognizesWithByteArray(string imageFileName) { // Arrange byte[] contentBytes = File.ReadAllBytes(@"..\..\..\OcrTests\" + imageFileName); OcrClient client = new OcrClient(API_KEY, REGION); OcrResponse response; // Act response = Task.Run(() => client.RecognizeAsync(contentBytes)).Result; // Assert Assert.NotNull(response); Assert.Null(response.ErrorCode); Assert.NotNull(response.Regions); Assert.NotEmpty(response.Regions); Assert.NotEqual(response.Regions.First().BoundingBox.Left, default(int)); Assert.NotEqual(response.Regions.First().BoundingBox.Top, default(int)); Assert.NotEqual(response.Regions.First().BoundingBox.Width, default(int)); Assert.NotEqual(response.Regions.First().BoundingBox.Height, default(int)); Assert.NotNull(response.Regions.First().Lines); Assert.NotEmpty(response.Regions.First().Lines); Assert.NotNull(response.Regions.First().Lines.First().Words); }
private static async Task <List <String> > getReturnStringArrayAsync(string imageBase64) { Credential cred = new Credential { SecretId = TencentToken.secrectId, SecretKey = TencentToken.secrectKey }; ClientProfile profile = new ClientProfile(); profile.SignMethod = "TC3-HMAC-SHA256"; OcrClient client = new OcrClient(cred, "ap-guangzhou", profile); FormulaOCRRequest request = new FormulaOCRRequest(); request.ImageBase64 = imageBase64; FormulaOCRResponse response = await client.FormulaOCR(request); List <String> result = new List <string>(); foreach (var i in response.FormulaInfos) { result.Add(i.DetectedText); } return(result); }
public override string OCR(Image image) { ClientProfile.HttpProfile = HttpProfile; OcrClient client = new OcrClient(Credential, "ap-beijing", ClientProfile); AdvertiseOCRRequest req = new AdvertiseOCRRequest(); var imageByte = ImageToByte(image); req.ImageBase64 = Convert.ToBase64String(imageByte); AdvertiseOCRResponse resp = client.AdvertiseOCRSync(req); var resultJobj = JObject.Parse(AbstractModel.ToJsonString(resp)); var resultWodsJArry = JArray.Parse(resultJobj["TextDetections"].ToString()); var sb = new StringBuilder(""); foreach (var item in resultWodsJArry) { sb.AppendLine(item["DetectedText"].ToString()); } return(sb.ToString()); }
public void ParsesQueryString() { // Arrange Dictionary <string, string> parameters = new Dictionary <string, string> { { "parameter1", "parameter1value" }, { "parameter2", "Parameter2ValueWithCapitals" }, { "parameter3", "parameter3valuewithspecialcharacters@&#να" } }; OcrClient client = new OcrClient(API_KEY, REGION); foreach (var parameter in parameters) { client.QueryStringValues.Add(parameter.Key, parameter.Value); } // Act string parsedString = client.ParseQueryString(); // Assert Assert.NotNull(parsedString); Assert.Equal("?parameter1=parameter1value¶meter2=Parameter2ValueWithCapitals¶meter3=parameter3valuewithspecialcharacters%40%26%23%C5%A1%C3%AD%C3%A1", parsedString); }