ChatGTPAIHelper.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. using ComPDFKit_Conversion.Options;
  2. using DryIoc;
  3. using ImTools;
  4. using Microsoft.Office.Interop.Word;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Linq;
  7. using PDF_Master.Properties;
  8. using PDF_Master.ViewModels.Dialog.ChatGPTAIDialogs;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Net.Http;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Web;
  21. using static Dropbox.Api.Files.SearchMatchType;
  22. using static Dropbox.Api.TeamLog.EventCategory;
  23. using static Google.Apis.Requests.BatchRequest;
  24. namespace PDF_Master.Helper
  25. {
  26. public static class ChatGTPAIHelper
  27. {
  28. #if DEBUG
  29. //测试环境
  30. //纠错重写
  31. private static string host = "https://ai.compdf.com";
  32. //百度翻译
  33. private static string translate = "http://101.132.103.13:8030";
  34. #else
  35. //纠错重写
  36. private static string host = "https://ai.compdf.com";
  37. //百度翻译
  38. private static string translate ="https://api-server.compdf.com";
  39. #endif
  40. /// <summary>
  41. /// 翻译文档Key接口
  42. /// </summary>
  43. private static string Uri_fileKeytranslate = translate + "/v1/translate/fileUpload";
  44. /// <summary>
  45. /// 翻译文档接口
  46. /// </summary>
  47. private static string Uri_filetranslate = translate + "/v1/translate/fileTranslateHandle";
  48. /// <summary>
  49. /// 翻译文本接口
  50. /// </summary>
  51. private static string Uri_texttranslate = translate + "/v1/translate/textTrans";
  52. /// <summary>
  53. /// 错别字纠正
  54. /// </summary>
  55. private static string Uri_Correction = host + "/api/correct-typos";
  56. /// <summary>
  57. /// 错别字纠正
  58. /// </summary>
  59. private static string Uri_Rewrite = host + "/api/rewrite";
  60. /// <summary>
  61. /// chatGPT错误码
  62. /// </summary>
  63. public static string ChatGPTCode = "";
  64. #region AI服务器对接接口
  65. /// <summary>
  66. /// 获取
  67. /// </summary>
  68. /// <param name="content"></param>
  69. /// <param name="filename"></param>
  70. /// <returns></returns>
  71. public static async Task<string> fileKeyTranslate(string content, string filename)
  72. {
  73. string Code = "Code" + "300";
  74. ServicePointManager.DefaultConnectionLimit = 200;
  75. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri_fileKeytranslate);
  76. //关闭请求
  77. //弹窗内进度条关闭
  78. DocumentaryTranslationDialogViewModel.CancelProgress = () =>
  79. {
  80. if (request != null)
  81. {
  82. Code = "Code" + "-1";
  83. request.Abort();
  84. }
  85. };
  86. //进度条关闭
  87. App.mainWindowViewModel.ProcessCloseAction = () =>
  88. {
  89. if (request != null)
  90. {
  91. Code = "Code" + "-1";
  92. request.Abort();
  93. }
  94. };
  95. request.Method = "Post";
  96. //request.Accept = "application/vnd.api+json;version=1";
  97. request.UserAgent = "Apifox/1.0.0 (https://www.apifox.cn)";
  98. request.Timeout = 20000;
  99. request.ServicePoint.Expect100Continue = false;
  100. request.KeepAlive = false;
  101. var formData = new MultipartFormDataContent();
  102. byte[] data = File.ReadAllBytes(@content);
  103. MemoryStream stream = new MemoryStream(data);
  104. formData.Add(new ByteArrayContent(data), "file", filename);
  105. formData.Add(new StringContent("2"), "projectId");
  106. formData.Add(new StringContent("1.0.1"), "version");
  107. if (!string.IsNullOrEmpty(Settings.Default.UserDate.id))
  108. {
  109. formData.Add(new StringContent(Settings.Default.UserDate.id), "userId");
  110. }
  111. else
  112. {
  113. formData.Add(new StringContent("1"), "userId");
  114. }
  115. // 设置请求体格式
  116. request.ContentType = formData.Headers.ContentType.ToString();
  117. request.ContentLength = formData.Headers.ContentLength.Value;
  118. // 将FormData写入请求体
  119. try
  120. {
  121. using (var requestStream = request.GetRequestStream())
  122. {
  123. await formData.CopyToAsync(requestStream);
  124. }
  125. // 获取HTTP响应
  126. HttpWebResponse response2 = (HttpWebResponse)request.GetResponse();
  127. using (StreamReader reader = new StreamReader(response2.GetResponseStream()))
  128. {
  129. string responseData = reader.ReadToEnd();
  130. Console.WriteLine(responseData);
  131. reader.Close();
  132. JObject jobject = (JObject)JsonConvert.DeserializeObject(responseData);
  133. if (response2 != null)
  134. {
  135. response2.Close();
  136. }
  137. if (request != null)
  138. {
  139. request.Abort();
  140. }
  141. string translation = "";
  142. if (jobject["code"].ToObject<string>().ToLower() == "200")
  143. {
  144. translation = jobject["data"]["fileKey"].ToObject<string>().ToLower();
  145. return translation;
  146. }
  147. return "Code" + jobject["code"].ToObject<string>().ToLower();
  148. }
  149. }
  150. catch (WebException ex)
  151. {
  152. int statusCode = 0;
  153. if (ex.Response is HttpWebResponse)
  154. {
  155. //从网络异常信息里解析错误,后面的逻辑根据错误码判断会更准确
  156. statusCode = (int)((HttpWebResponse)ex.Response).StatusCode;
  157. }
  158. Trace.WriteLine("HTTP异常:" + ex.Message);
  159. if (statusCode == 401)
  160. {
  161. return "Code" + "401";
  162. }
  163. else
  164. {
  165. //-1为自己取消,300为一般错误
  166. return Code;
  167. }
  168. }
  169. catch
  170. {
  171. return "300";
  172. }
  173. }
  174. public static string HttpDownloadFile(string url, string path)
  175. {
  176. // 设置参数
  177. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  178. //发送请求并获取相应回应数据
  179. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  180. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  181. Stream responseStream = response.GetResponseStream();
  182. //创建本地文件写入流
  183. Stream stream = new FileStream(path, FileMode.Create);
  184. byte[] bArr = new byte[1024];
  185. int size = responseStream.Read(bArr, 0, (int)bArr.Length);
  186. while (size > 0)
  187. {
  188. stream.Write(bArr, 0, size);
  189. size = responseStream.Read(bArr, 0, (int)bArr.Length);
  190. }
  191. stream.Close();
  192. responseStream.Close();
  193. return path;
  194. }
  195. /// <summary>
  196. /// 翻译指定内容,可以指定语言
  197. /// </summary>
  198. /// <param name="content">文件</param>
  199. /// <param name="fromlanguage">文本语言</param>
  200. /// <param name="tolanguage">需要翻译的语言</param>
  201. /// <param name="isprocess">是否需要阅读也进度条</param>
  202. /// <returns>code与文件路径</returns>
  203. public static async Task<string> fileTranslate(string content, string fromlanguage, string tolanguage, bool isprocess = true)
  204. {
  205. string Code = "300";
  206. intProcess(isprocess, "Translating...", System.Windows.Visibility.Visible);
  207. //判断word文档大小
  208. if (!GetDocumentPagesWord(content))
  209. {
  210. clossProcess();
  211. return "05011";
  212. }
  213. FileInfo file = new FileInfo(content);
  214. string fileKey = await fileKeyTranslate(content, file.Name);
  215. App.mainWindowViewModel.Value = 1;
  216. if (fileKey.Contains("Code"))
  217. {
  218. clossProcess();
  219. return fileKey.Replace("Code", "");
  220. }
  221. HttpWebResponse response = null;
  222. ServicePointManager.DefaultConnectionLimit = 200;
  223. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri_filetranslate);
  224. //关闭请求
  225. DocumentaryTranslationDialogViewModel.CancelProgress = () =>
  226. {
  227. if (request != null)
  228. {
  229. Code = "-1";
  230. request.Abort();
  231. }
  232. };
  233. App.mainWindowViewModel.ProcessCloseAction = () =>
  234. {
  235. if (request != null)
  236. {
  237. Code = "-1";
  238. request.Abort();
  239. }
  240. };
  241. request.Method = "Post";
  242. request.ContentType = "application/json";
  243. //request.Accept = "application/vnd.api+json;version=1";
  244. request.UserAgent = "Apifox/1.0.0 (https://www.apifox.cn)";
  245. //设置无限请求时间:由于文本翻译时间不确定且时间长
  246. request.Timeout = Timeout.Infinite;
  247. request.ServicePoint.Expect100Continue = false;
  248. request.KeepAlive = false;
  249. StringWriter sw = new StringWriter();
  250. using (JsonWriter writer = new JsonTextWriter(sw))
  251. {
  252. writer.WriteStartObject();
  253. writer.WritePropertyName("fileKey");
  254. writer.WriteValue(fileKey);
  255. writer.WritePropertyName("from");
  256. writer.WriteValue(fromlanguage);
  257. writer.WritePropertyName("to");
  258. writer.WriteValue(tolanguage);
  259. writer.WritePropertyName("projectId");
  260. writer.WriteValue("2");
  261. writer.WritePropertyName("version");
  262. writer.WriteValue("1.0.1");
  263. writer.WritePropertyName("userId");
  264. writer.WriteValue(Settings.Default.UserDate.id);
  265. writer.WriteEndObject();
  266. }
  267. try
  268. {
  269. App.mainWindowViewModel.Value = 2;
  270. string postBody = sw.ToString();
  271. using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
  272. {
  273. writer.Write(postBody);
  274. writer.Close();
  275. }
  276. App.mainWindowViewModel.Value = 3;
  277. response = (HttpWebResponse)request.GetResponse();
  278. using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  279. {
  280. App.mainWindowViewModel.Value = 4;
  281. string responseData = reader.ReadToEnd();
  282. Console.WriteLine(responseData);
  283. reader.Close();
  284. JObject jobject = (JObject)JsonConvert.DeserializeObject(responseData);
  285. App.mainWindowViewModel.Value = 6;
  286. if (response != null)
  287. {
  288. response.Close();
  289. }
  290. if (request != null)
  291. {
  292. request.Abort();
  293. }
  294. if (jobject["code"].ToObject<string>().ToLower() == "200")
  295. {
  296. translate = jobject["data"]["ossDownUrl"].ToObject<string>().ToLower();
  297. //return jobject["code"].ToObject<string>().ToLower();
  298. using (var client = new WebClient())
  299. {
  300. App.mainWindowViewModel.Value = 8;
  301. string folderPath = file.FullName.Remove(file.FullName.LastIndexOf("."), file.FullName.Length - file.FullName.LastIndexOf(".")) + "_aiTranslation.pdf";
  302. folderPath = CommonHelper.CreateFilePath(folderPath);
  303. client.DownloadProgressChanged += (sender, e) =>
  304. {
  305. };
  306. client.DownloadFile(translate, folderPath);
  307. clossProcess();
  308. return folderPath;
  309. }
  310. }
  311. clossProcess();
  312. return jobject["code"].ToObject<string>().ToLower();
  313. }
  314. }
  315. catch (WebException ex)
  316. {
  317. clossProcess();
  318. int statusCode = 0;
  319. if (ex.Response is HttpWebResponse)
  320. {
  321. //从网络异常信息里解析错误,后面的逻辑根据错误码判断会更准确
  322. statusCode = (int)((HttpWebResponse)ex.Response).StatusCode;
  323. }
  324. Trace.WriteLine("HTTP异常:" + ex.Message);
  325. if (statusCode == 401)
  326. {
  327. return "401";
  328. }
  329. else
  330. {
  331. //-1为自己取消,300为一般错误
  332. return Code;
  333. }
  334. }
  335. catch
  336. {
  337. return "300";
  338. }
  339. }
  340. /// <summary>
  341. /// 翻译指定内容,可以指定语言
  342. /// </summary>
  343. /// <param name="content">翻译内容</param>
  344. /// <param name="fromlanguage">文本语言</param>
  345. /// <param name="tolanguage">需要翻译的语言</param>
  346. /// <returns></returns>
  347. public static String textTranslate(string content, string fromlanguage, string tolanguage, ref string translate)
  348. {
  349. HttpWebResponse response = null;
  350. ServicePointManager.DefaultConnectionLimit = 200;
  351. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri_texttranslate);
  352. request.Method = "Post";
  353. request.ContentType = "application/json";
  354. //request.Accept = "application/vnd.api+json;version=1";
  355. request.UserAgent = "Apifox/1.0.0 (https://www.apifox.cn)";
  356. request.Timeout = 60000;
  357. request.ServicePoint.Expect100Continue = false;
  358. StringWriter sw = new StringWriter();
  359. using (JsonWriter writer = new JsonTextWriter(sw))
  360. {
  361. writer.WriteStartObject();
  362. writer.WritePropertyName("q");
  363. writer.WriteValue(content);
  364. writer.WritePropertyName("from");
  365. writer.WriteValue(fromlanguage);
  366. writer.WritePropertyName("to");
  367. writer.WriteValue(tolanguage);
  368. writer.WritePropertyName("projectId");
  369. writer.WriteValue("2");
  370. writer.WritePropertyName("version");
  371. writer.WriteValue("1.0.1");
  372. writer.WritePropertyName("userId");
  373. writer.WriteValue(Settings.Default.UserDate.id);
  374. writer.WriteEndObject();
  375. }
  376. try
  377. {
  378. string postBody = sw.ToString();
  379. using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
  380. {
  381. writer.Write(postBody);
  382. writer.Close();
  383. }
  384. response = (HttpWebResponse)request.GetResponse();
  385. using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  386. {
  387. string responseData = reader.ReadToEnd();
  388. Console.WriteLine(responseData);
  389. reader.Close();
  390. JObject jobject = (JObject)JsonConvert.DeserializeObject(responseData);
  391. if (response != null)
  392. {
  393. response.Close();
  394. }
  395. if (request != null)
  396. {
  397. request.Abort();
  398. }
  399. if (jobject["code"].ToObject<string>().ToLower() == "200")
  400. {
  401. translate = jobject["data"]["dst"].ToObject<string>().ToLower();
  402. }
  403. //return jobject["code"].ToObject<string>().ToLower();
  404. return jobject["code"].ToObject<string>().ToLower();
  405. }
  406. }
  407. catch (WebException ex)
  408. {
  409. int statusCode = 0;
  410. if (ex.Response is HttpWebResponse)
  411. {
  412. //从网络异常信息里解析错误,后面的逻辑根据错误码判断会更准确
  413. statusCode = (int)((HttpWebResponse)ex.Response).StatusCode;
  414. }
  415. if (statusCode == 401)
  416. {
  417. return "401";
  418. }
  419. else return "300";
  420. }
  421. catch
  422. {
  423. return "300";
  424. }
  425. }
  426. /// <summary>
  427. /// 纠错
  428. /// </summary>
  429. /// <param name="content"></param>
  430. /// <returns></returns>
  431. public static async Task<string> Correction(string content)
  432. {
  433. intProcess(true, "Correcting...");
  434. App.mainWindowViewModel.Value = 1;
  435. ServicePointManager.DefaultConnectionLimit = 200;
  436. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri_Correction);
  437. request.Method = "Post";
  438. //request.Accept = "application/vnd.api+json;version=1";
  439. request.UserAgent = "Apifox/1.0.0 (https://www.apifox.cn)";
  440. request.Timeout = 60000;
  441. request.ServicePoint.Expect100Continue = false;
  442. var formData = new MultipartFormDataContent();
  443. formData.Add(new StringContent("2"), "project_id");
  444. formData.Add(new StringContent("1.0.1"), "version");
  445. if (!string.IsNullOrEmpty(Settings.Default.UserDate.id))
  446. {
  447. formData.Add(new StringContent(Settings.Default.UserDate.id), "user_id");
  448. }
  449. else
  450. {
  451. formData.Add(new StringContent("1"), "user_id");
  452. }
  453. formData.Add(new StringContent(content), "content");
  454. // 设置请求体格式
  455. request.ContentType = formData.Headers.ContentType.ToString();
  456. request.ContentLength = formData.Headers.ContentLength.Value;
  457. App.mainWindowViewModel.Value = 3;
  458. return await PostStringHttpWeb(formData, request, "content");
  459. }
  460. /// <summary>
  461. /// 重写
  462. /// </summary>
  463. /// <param name="content"></param>
  464. /// <returns></returns>
  465. public static async Task<string> Rewrite(string content)
  466. {
  467. intProcess(true, "Rewriting...");
  468. App.mainWindowViewModel.Value = 1;
  469. ServicePointManager.DefaultConnectionLimit = 200;
  470. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri_Rewrite);
  471. request.Method = "Post";
  472. //request.Accept = "application/vnd.api+json;version=1";
  473. request.UserAgent = "Apifox/1.0.0 (https://www.apifox.cn)";
  474. request.Timeout = 60000;
  475. request.ServicePoint.Expect100Continue = false;
  476. var formData = new MultipartFormDataContent();
  477. formData.Add(new StringContent("2"), "project_id");
  478. formData.Add(new StringContent("1.0.1"), "version");
  479. if (!string.IsNullOrEmpty(Settings.Default.UserDate.id))
  480. {
  481. formData.Add(new StringContent(Settings.Default.UserDate.id), "user_id");
  482. }
  483. else
  484. {
  485. formData.Add(new StringContent("1"), "user_id");
  486. }
  487. formData.Add(new StringContent(content), "content");
  488. // 设置请求体格式
  489. request.ContentType = formData.Headers.ContentType.ToString();
  490. request.ContentLength = formData.Headers.ContentLength.Value;
  491. App.mainWindowViewModel.Value = 3;
  492. return await PostStringHttpWeb(formData, request, "content");
  493. }
  494. /// <summary>
  495. /// 从链接中返回存在的链接(仅返回第一个找到的链接)
  496. /// </summary>
  497. /// <param name="content"></param>
  498. /// <returns></returns>
  499. public static List<string> GetLinkFromString(string content)
  500. {
  501. if (string.IsNullOrEmpty(content))
  502. {
  503. return null;
  504. }
  505. // 创建正则表达式模式
  506. string pattern = @"(https?://[^\s]+)";
  507. // 获取所有匹配项
  508. MatchCollection matches = Regex.Matches(content, pattern);
  509. List<string> list = new List<string>();
  510. // 遍历并打印所有匹配项
  511. foreach (Match match in matches)
  512. {
  513. list.Add(match.Value);
  514. }
  515. return list;
  516. }
  517. /// <summary>
  518. /// 从接口获取信息,获取message对应value值
  519. /// </summary>
  520. /// <param name="formData">传入参数</param>
  521. /// <param name="request">请求体</param>
  522. /// /// <param name="key">值</param>
  523. /// <returns></returns>
  524. private static async Task<string> PostStringHttpWeb(MultipartFormDataContent formData, HttpWebRequest request, string key = "message")
  525. {
  526. App.mainWindowViewModel.Value = 6;
  527. string repsonseData = "";
  528. try
  529. {
  530. using (var requestStream = request.GetRequestStream())
  531. {
  532. await formData.CopyToAsync(requestStream);
  533. }
  534. // 获取HTTP响应
  535. HttpWebResponse response2 = (HttpWebResponse)request.GetResponse();
  536. using (StreamReader reader = new StreamReader(response2.GetResponseStream()))
  537. {
  538. string responseData = reader.ReadToEnd();
  539. Console.WriteLine(responseData);
  540. reader.Close();
  541. App.mainWindowViewModel.Value = 7;
  542. JObject jobject = (JObject)JsonConvert.DeserializeObject(responseData);
  543. App.mainWindowViewModel.Value = 8;
  544. if (response2 != null)
  545. {
  546. response2.Close();
  547. }
  548. if (request != null)
  549. {
  550. request.Abort();
  551. }
  552. string unicode = "";
  553. // 遍历字典对象输出键值对
  554. ChatGPTCode = jobject["code"].ToObject<string>().ToLower();
  555. if (ChatGPTCode == "200")
  556. {
  557. unicode = jobject["data"][key].ToObject<string>().ToLower();
  558. }
  559. //将Unicode格式转换成String
  560. //repsonseData = Regex.Unescape(unicode);
  561. repsonseData = unicode;
  562. clossProcess();
  563. }
  564. }
  565. catch (WebException ex)
  566. {
  567. App.mainWindowViewModel.Value = 8;
  568. int statusCode = 0;
  569. if (ex.Response is HttpWebResponse)
  570. {
  571. //从网络异常信息里解析错误,后面的逻辑根据错误码判断会更准确
  572. statusCode = (int)((HttpWebResponse)ex.Response).StatusCode;
  573. }
  574. if (statusCode == 401)
  575. {
  576. ChatGPTCode = "401";
  577. }
  578. else ChatGPTCode = "300";
  579. clossProcess();
  580. return null;
  581. }
  582. catch
  583. {
  584. ChatGPTCode = "300";
  585. clossProcess();
  586. }
  587. clossProcess();
  588. return repsonseData;
  589. }
  590. /// <summary>
  591. /// 从接口获取信息,获取message对应value值,WebClient没有设置请求时间参数换一种方案
  592. /// </summary>
  593. /// <param name="url"></param>
  594. /// <param name="namevalue"></param>
  595. /// <returns></returns>
  596. private static async Task<string> PostStringWebClient(string url, System.Collections.Specialized.NameValueCollection namevalue, string key = "message")
  597. {
  598. App.mainWindowViewModel.Value = 5;
  599. string repsonseData = "";
  600. try
  601. {
  602. using (var client = new WebClient())
  603. {
  604. byte[] bytes = await client.UploadValuesTaskAsync(url, namevalue);
  605. //转换成字符串类型
  606. var json = Encoding.Default.GetString(bytes);
  607. //将Json格式字符串转换成键值对
  608. //var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  609. JObject jobject = (JObject)JsonConvert.DeserializeObject(json);
  610. App.mainWindowViewModel.Value = 8;
  611. string unicode = "";
  612. // 遍历字典对象输出键值对
  613. ChatGPTCode = jobject["code"].ToObject<string>().ToLower();
  614. if (ChatGPTCode == "200")
  615. {
  616. unicode = jobject["data"][key].ToObject<string>().ToLower();
  617. }
  618. //将Unicode格式转换成String
  619. //repsonseData = Regex.Unescape(unicode);
  620. repsonseData = unicode;
  621. }
  622. clossProcess();
  623. }
  624. catch (WebException ex)
  625. {
  626. int statusCode = 0;
  627. if (ex.Response is HttpWebResponse)
  628. {
  629. //从网络异常信息里解析错误,后面的逻辑根据错误码判断会更准确
  630. statusCode = (int)((HttpWebResponse)ex.Response).StatusCode;
  631. }
  632. if (statusCode == 401)
  633. {
  634. ChatGPTCode = "401";
  635. }
  636. else ChatGPTCode = "300";
  637. clossProcess();
  638. return null;
  639. }
  640. return repsonseData;
  641. }
  642. /// <summary>
  643. /// 初始进度条
  644. /// </summary>
  645. /// <param name="isprocess">是否需要进度条</param>
  646. /// <param name="progressTitle">文案</param>
  647. public static void intProcess(bool isprocess = true, string progressTitle = "Translating...", System.Windows.Visibility ProcessCloseBtnVisible = System.Windows.Visibility.Collapsed)
  648. {
  649. if (isprocess)
  650. {
  651. App.mainWindowViewModel.ProgressTitle = progressTitle;
  652. App.mainWindowViewModel.MaxValue = 10;
  653. App.mainWindowViewModel.Value = 0;
  654. App.mainWindowViewModel.IsProcessVisible = System.Windows.Visibility.Visible;
  655. App.mainWindowViewModel.ProcessCloseBtnVisible = ProcessCloseBtnVisible;
  656. }
  657. }
  658. /// <summary>
  659. /// 初始进度条
  660. /// </summary>
  661. /// <param name="isprocess">是否需要进度条</param>
  662. /// <param name="progressTitle">文案</param>
  663. /// <param name="maxValue">进度条最大值</param>
  664. /// <param name="ProcessCloseBtnVisible">进度条关闭按钮是否可见</param>
  665. public static void SetIntProcess(bool isprocess = true, string progressTitle = "Splitting...", int maxValue = 10, System.Windows.Visibility ProcessCloseBtnVisible = System.Windows.Visibility.Collapsed)
  666. {
  667. if (isprocess)
  668. {
  669. App.mainWindowViewModel.ProgressTitle = progressTitle;
  670. App.mainWindowViewModel.MaxValue = maxValue;
  671. App.mainWindowViewModel.Value = 0;
  672. App.mainWindowViewModel.IsProcessVisible = System.Windows.Visibility.Visible;
  673. App.mainWindowViewModel.ProcessCloseBtnVisible = ProcessCloseBtnVisible;
  674. }
  675. }
  676. /// <summary>
  677. /// 关闭进度条
  678. /// </summary>
  679. public static void clossProcess()
  680. {
  681. App.mainWindowViewModel.Value = 9;
  682. App.mainWindowViewModel.IsProcessVisible = System.Windows.Visibility.Collapsed;
  683. App.mainWindowViewModel.ProcessCloseBtnVisible = System.Windows.Visibility.Visible;
  684. }
  685. /// <summary>
  686. /// 关闭进度条
  687. /// </summary>
  688. /// <param name="value">进度条当前值</param>
  689. public static void clossProcess(int value = 9)
  690. {
  691. App.mainWindowViewModel.Value = value;
  692. App.mainWindowViewModel.IsProcessVisible = System.Windows.Visibility.Collapsed;
  693. App.mainWindowViewModel.ProcessCloseBtnVisible = System.Windows.Visibility.Visible;
  694. }
  695. /// <summary>
  696. /// 判断word文档页面大小,如果接口有问题则交给服务器判断
  697. /// </summary>
  698. /// <param name="filepath"></param>
  699. /// <returns>返回值为是否拿到页码没拿到则为true,页面过小为true</returns>
  700. public static bool GetDocumentPagesWord(string filepath)
  701. {
  702. try
  703. {
  704. FileInfo fileInfo = new FileInfo(filepath);
  705. if (fileInfo.Extension.ToLower() != ".pdf")
  706. {
  707. Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.Application();
  708. object Nothing = System.Reflection.Missing.Value;
  709. object oMissing = System.Reflection.Missing.Value;
  710. //这里是Word文件的路径
  711. object filePath = filepath;
  712. //打开文件
  713. Document myWordDoc = myWordApp.Documents.Open(
  714. ref filePath, ref oMissing, ref oMissing, ref oMissing,
  715. ref oMissing, ref oMissing, ref oMissing, ref oMissing,
  716. ref oMissing, ref oMissing, ref oMissing, ref oMissing,
  717. ref oMissing, ref oMissing, ref oMissing, ref oMissing);
  718. //下面是取得打开文件的页数
  719. int pages = myWordDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref Nothing);
  720. //关闭文件
  721. myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
  722. //退出Word程序
  723. myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
  724. if (pages > 30)
  725. {
  726. return false;
  727. }
  728. }
  729. return true;
  730. }
  731. catch
  732. {
  733. return true;
  734. }
  735. }
  736. #endregion AI服务器对接接口
  737. #region 支持翻译的语言
  738. /// <summary>
  739. /// 当前语言列表
  740. /// </summary>
  741. public static List<string> FromlanguageFamily { set; get; } = new List<string>();
  742. public static List<string> SetFromlanguageOrigin()
  743. {
  744. FromlanguageFamily.Clear();
  745. FromlanguageFamily.Add("Automatic Identification");
  746. FromlanguageFamily.Add("English");
  747. FromlanguageFamily.Add("Simplified Chinese");
  748. FromlanguageFamily.Add("Traditional Chinese");
  749. FromlanguageFamily.Add("Japanese");
  750. FromlanguageFamily.Add("Korean");
  751. FromlanguageFamily.Add("French");
  752. FromlanguageFamily.Add("Spanish");
  753. FromlanguageFamily.Add("Italian");
  754. FromlanguageFamily.Add("German");
  755. FromlanguageFamily.Add("Portuguese");
  756. FromlanguageFamily.Add("Russian");
  757. FromlanguageFamily.Add("Vietnamese");
  758. FromlanguageFamily.Add("Thai");
  759. FromlanguageFamily.Add("Arabic");
  760. FromlanguageFamily.Add("Greek");
  761. FromlanguageFamily.Add("Bulgarian");
  762. FromlanguageFamily.Add("Finnish");
  763. FromlanguageFamily.Add("Slovene");
  764. FromlanguageFamily.Add("Dutch");
  765. FromlanguageFamily.Add("Czech");
  766. FromlanguageFamily.Add("Swedish");
  767. FromlanguageFamily.Add("Polish");
  768. FromlanguageFamily.Add("Danish");
  769. FromlanguageFamily.Add("Romanian");
  770. FromlanguageFamily.Add("Hungarian");
  771. return FromlanguageFamily;
  772. }
  773. /// <summary>
  774. /// 需要翻译成对应语言列表
  775. /// </summary>
  776. public static List<string> TolanguageFamily { set; get; } = new List<string>();
  777. public static List<string> SetTolanguageOrigin()
  778. {
  779. TolanguageFamily.Clear();
  780. TolanguageFamily.Add("English");
  781. TolanguageFamily.Add("Simplified Chinese");
  782. TolanguageFamily.Add("Traditional Chinese");
  783. TolanguageFamily.Add("Japanese");
  784. TolanguageFamily.Add("Korean");
  785. TolanguageFamily.Add("French");
  786. TolanguageFamily.Add("Spanish");
  787. TolanguageFamily.Add("Italian");
  788. TolanguageFamily.Add("German");
  789. TolanguageFamily.Add("Portuguese");
  790. TolanguageFamily.Add("Russian");
  791. TolanguageFamily.Add("Vietnamese");
  792. TolanguageFamily.Add("Thai");
  793. TolanguageFamily.Add("Arabic");
  794. TolanguageFamily.Add("Greek");
  795. TolanguageFamily.Add("Bulgarian");
  796. TolanguageFamily.Add("Finnish");
  797. TolanguageFamily.Add("Slovene");
  798. TolanguageFamily.Add("Dutch");
  799. TolanguageFamily.Add("Czech");
  800. TolanguageFamily.Add("Swedish");
  801. TolanguageFamily.Add("Polish");
  802. TolanguageFamily.Add("Danish");
  803. TolanguageFamily.Add("Romanian");
  804. TolanguageFamily.Add("Hungarian");
  805. return TolanguageFamily;
  806. }
  807. /// <summary>
  808. /// 接口传值对应字符
  809. /// </summary>
  810. /// <param name="index">控制form与to的区别,form为0开始,to为1开始,因为to没有auto</param>
  811. /// <returns></returns>
  812. public static string UpdateLanguagebType(int index)
  813. {
  814. switch (index)
  815. {
  816. case 0:
  817. return "auto";
  818. case 1:
  819. return "en";
  820. case 2:
  821. return "zh";
  822. case 3:
  823. return "cht";
  824. case 4:
  825. return "jp";
  826. case 5:
  827. return "kor";
  828. case 6:
  829. return "fra";
  830. case 7:
  831. return "spa";
  832. case 8:
  833. return "it";
  834. case 9:
  835. return "de";
  836. case 10:
  837. return "pt";
  838. case 11:
  839. return "ru";
  840. case 12:
  841. return "vie";
  842. case 13:
  843. return "th";
  844. case 14:
  845. return "ara";
  846. case 15:
  847. return "el";
  848. case 16:
  849. return "bul";
  850. case 17:
  851. return "fin";
  852. case 18:
  853. return "slo";
  854. case 19:
  855. return "nl";
  856. case 20:
  857. return "cs";
  858. case 21:
  859. return "swe";
  860. case 22:
  861. return "pl";
  862. case 23:
  863. return "dan";
  864. case 24:
  865. return "rom";
  866. case 25:
  867. return "hu";
  868. default:
  869. return "";
  870. }
  871. }
  872. #endregion 支持翻译的语言
  873. #region 错误码
  874. public static string GetBaiduTranslationCode(string code)
  875. {
  876. if (code == "300" || code == "401") { return App.HomePageLoader.GetString("ChatGTPNetworkError"); }
  877. if (!String.IsNullOrEmpty(App.HomePageLoader.GetString("BaiduTranslation" + code)))
  878. {
  879. return App.HomePageLoader.GetString("BaiduTranslation" + code);
  880. }
  881. return code;
  882. }
  883. public static string GetChatGPTCode(string code)
  884. {
  885. if (code == "300" || code == "401") { return App.HomePageLoader.GetString("ChatGTPNetworkError"); }
  886. if (!String.IsNullOrEmpty(App.HomePageLoader.GetString("ChatGTP" + code)))
  887. {
  888. return App.HomePageLoader.GetString("ChatGTP" + code);
  889. }
  890. return code;
  891. }
  892. #endregion 错误码
  893. }
  894. }