diff --git a/RhSolutions.AddIn/Services/YandexOcrClient.cs b/RhSolutions.AddIn/Services/YandexOcrClient.cs index 960d2f7..27a665f 100644 --- a/RhSolutions.AddIn/Services/YandexOcrClient.cs +++ b/RhSolutions.AddIn/Services/YandexOcrClient.cs @@ -2,6 +2,7 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; +using System.Windows.Forms; using Newtonsoft.Json; namespace RhSolutions.Services; @@ -36,39 +37,46 @@ public class YandexOcrClient : IOcrClient _httpClient.DefaultRequestHeaders.Add("x-data-logging-enable", "true"); using HttpResponseMessage response = await _httpClient.PostAsync("recognizeText", jsonContent); - response.EnsureSuccessStatusCode(); - - string jsonResponse = await response.Content.ReadAsStringAsync(); - OcrResponse deserialized = JsonConvert.DeserializeObject(jsonResponse); - - if (deserialized != null) + if (response.IsSuccessStatusCode) { - var tables = deserialized?.Result?.TextAnnotation?.Tables ?? Enumerable.Empty(); - if (tables.Any()) + string jsonResponse = await response.Content.ReadAsStringAsync(); + OcrResponse deserialized = JsonConvert.DeserializeObject(jsonResponse); + + if (deserialized != null) { - List result = new(); - foreach (var table in tables) + var tables = deserialized?.Result?.TextAnnotation?.Tables ?? Enumerable.Empty
(); + if (tables.Any()) { - if (table.Cells == null || table.Cells.Count == 0) + List result = new(); + foreach (var table in tables) { - continue; + if (table.Cells == null || table.Cells.Count == 0) + { + continue; + } + int columnCount = int.Parse(table.ColumnCount); + int rowCount = int.Parse(table.RowCount); + object[,] cells = new object[rowCount, columnCount]; + + foreach (Cell cell in table.Cells) + { + int rowIndex = int.Parse(cell.RowIndex); + int columnIndex = int.Parse(cell.ColumnIndex); + cells[rowIndex, columnIndex] = double.TryParse(cell.Text, out double v) ? + v : cell.Text ?? string.Empty; + } + result.Add(cells); } - int columnCount = int.Parse(table.ColumnCount); - int rowCount = int.Parse(table.RowCount); - object[,] cells = new object[rowCount, columnCount]; - - foreach (Cell cell in table.Cells) - { - int rowIndex = int.Parse(cell.RowIndex); - int columnIndex = int.Parse(cell.ColumnIndex); - cells[rowIndex, columnIndex] = double.TryParse(cell.Text, out double v) ? - v : cell.Text ?? string.Empty; - } - result.Add(cells); + return result; } - return result; } } + else + { + string content = await response.Content.ReadAsStringAsync(); + MessageBox.Show($"{response.StatusCode}: {content}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + return Enumerable.Empty(); } } \ No newline at end of file