forked from microsoft/ai-edu
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCognitiveServiceAgent.cs
More file actions
181 lines (169 loc) · 7.03 KB
/
CognitiveServiceAgent.cs
File metadata and controls
181 lines (169 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace CartoonTranslate
{
class CognitiveServiceAgent
{
const string OcrEndPointV1 = "https://eastasia.api.cognitive.microsoft.com/vision/v2.0/ocr?detectOrientation=true&language=";
const string OcrEndPointV2 = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/recognizeText?mode=Printed";
const string VisionKey1 = "0e2908726aed45d692f6fb97bb621f71";
const string VisionKey2 = "97992f09b87e4be6b52be132309b8e57";
const string UrlContentTemplate = "{{\"url\":\"{0}\"}}";
const string TranslateEndPoint = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={0}&to={1}";
const string TKey1 = "04023df36a4c4599b1fc82510b48826c";
const string TKey2 = "9f763817f48549c6b503dae4a0d80a80";
public static async Task<List<string>> DoTranslate(List<string> text, string fromLanguage, string toLanguage)
{
try
{
using (HttpClient hc = new HttpClient())
{
hc.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", TKey1);
string jsonBody = CreateJsonBodyElement(text);
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
string uri = string.Format(TranslateEndPoint, fromLanguage, toLanguage);
HttpResponseMessage resp = await hc.PostAsync(uri, content);
string json = await resp.Content.ReadAsStringAsync();
var ro = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TranslateResult.Class1>>(json);
List<string> list = new List<string>();
foreach(TranslateResult.Class1 c in ro)
{
list.Add(c.translations[0].text);
}
return list;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
private static string CreateJsonBodyElement(List<string> text)
{
var a = text.Select(t => new { Text = t }).ToList();
var b = JsonConvert.SerializeObject(a);
return b;
}
public static async Task<NewOcrResult.Rootobject> DoRecognizeText(string imageUrl)
{
try
{
using (HttpClient hc = new HttpClient())
{
ByteArrayContent content = CreateHeader(hc, imageUrl);
HttpResponseMessage resp = await hc.PostAsync(OcrEndPointV2, content);
string json = string.Empty;
if (resp.StatusCode == System.Net.HttpStatusCode.Accepted)
{
var headers = resp.Headers;
foreach (var kv in headers)
{
if (kv.Key == "Operation-Location")
{
string url = kv.Value.First();
while (true)
{
// check status every 200ms
await Task.Delay(200);
json = await CheckStatus(url);
if (!string.IsNullOrEmpty(json))
{
break;
}
}
break;
}
}
}
if (string.IsNullOrEmpty(json))
{
return null;
}
else
{
NewOcrResult.Rootobject ro = Newtonsoft.Json.JsonConvert.DeserializeObject<NewOcrResult.Rootobject>(json);
return ro;
}
}
}
catch (Exception ex)
{
Debug.Write(ex.Message);
return null;
}
}
private static async Task<string> CheckStatus(string url)
{
using (HttpClient hc = new HttpClient())
{
hc.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", VisionKey1);
HttpResponseMessage resp = await hc.GetAsync(url);
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
string result = await resp.Content.ReadAsStringAsync();
if (result.Contains("Running"))
{
return null;
}
return result;
}
else
{
return null;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="imageUrl"></param>
/// <param name="language">en, ja, zh</param>
/// <returns></returns>
public static async Task<OcrResult.Rootobject> DoOCR(string imageUrl, string language)
{
try
{
using (HttpClient hc = new HttpClient())
{
ByteArrayContent content = CreateHeader(hc, imageUrl);
var uri = OcrEndPointV1 + language;
HttpResponseMessage resp = await hc.PostAsync(uri, content);
string result = string.Empty;
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
string json = await resp.Content.ReadAsStringAsync();
Debug.WriteLine(json);
OcrResult.Rootobject ro = Newtonsoft.Json.JsonConvert.DeserializeObject<OcrResult.Rootobject>(json);
return ro;
}
}
return null;
}
catch (Exception ex)
{
Debug.Write(ex.Message);
return null;
}
}
private static ByteArrayContent CreateHeader(HttpClient hc, string imageUrl)
{
hc.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", VisionKey1);
string body = string.Format(UrlContentTemplate, imageUrl);
byte[] byteData = Encoding.UTF8.GetBytes(body);
var content = new ByteArrayContent(byteData);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
}
}
}