AI_Form.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using Microsoft.Office.Tools.Ribbon;
  2. using Microsoft.Web.WebView2.Core;
  3. using PdfSharp.Drawing;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Diagnostics;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Http;
  14. using System.Net.Http.Headers;
  15. using System.Text;
  16. using System.Text.Json;
  17. using System.Threading.Tasks;
  18. using System.Windows.Forms;
  19. using static HTEXMark.QRCodeForm;
  20. namespace HTEXMark
  21. {
  22. public partial class AI_Form : Form
  23. {
  24. public RibbonButton ai_button;
  25. public RibbonButton user_button;
  26. public MarkLanguage lang;
  27. public MarkRibbon markRibbon;
  28. public RibbonDropDown schoolDropDown;
  29. public RibbonDropDown subjectDropDown;
  30. public string domain;
  31. private HttpClient httpClient;
  32. public List<IdCodeNameCount> periodSubjects = new List<IdCodeNameCount>();
  33. public AI_Form(List<IdCodeNameCount> periodSubjects, RibbonButton ai_button, RibbonButton user_button, RibbonDropDown schoolDropDown, RibbonDropDown subjectDropDown, MarkLanguage lang, MarkRibbon markRibbon, Microsoft.Office.Tools.CustomTaskPane customTaskPane, string domain)
  34. {
  35. this.ai_button=ai_button;
  36. this.user_button=user_button;
  37. this.lang = lang;
  38. this.markRibbon = markRibbon;
  39. this.schoolDropDown=schoolDropDown;
  40. this.subjectDropDown=subjectDropDown;
  41. this.periodSubjects=periodSubjects;
  42. this.httpClient=HttpClientFactory.Create();
  43. InitializeComponent();
  44. this.Load+=FormLoad;
  45. this.domain=domain;
  46. this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.AI_FormClosed);
  47. }
  48. public class ItemType {
  49. public string name { get; set; }
  50. public string type { get; set; }
  51. }
  52. private async void FormLoad(object sender, EventArgs e)
  53. {
  54. List<ItemType> items = new List<ItemType>() {
  55. new ItemType { name=lang.single,type= "single" },
  56. new ItemType { name=lang.multiple,type= "multiple" },
  57. new ItemType { name=lang.sortmultiple,type= "sortmultiple" },
  58. new ItemType { name=lang.judge,type= "judge" },
  59. new ItemType { name=lang.complete,type= "complete" },
  60. new ItemType { name=lang.subjective,type= "subjective" },
  61. new ItemType { name=lang.draw,type= "draw" },
  62. new ItemType { name=lang.connector,type= "connector" },
  63. new ItemType { name=lang.compose,type= "compose" },
  64. };
  65. comboBox_item_type.DataSource= items;
  66. comboBox_item_type.DisplayMember="name";
  67. comboBox_item_type.ValueMember="type";
  68. comboBox_subject.DataSource= periodSubjects;
  69. comboBox_subject.DisplayMember="name";
  70. comboBox_subject.ValueMember="periodType";
  71. // this.Text = lang.ai_title;
  72. // Microsoft.Web.WebView2.Core.CoreWebView2EnvironmentOptions options = new Microsoft.Web.WebView2.Core.CoreWebView2EnvironmentOptions();
  73. //options.AdditionalBrowserArguments = "--disable-web-security"; // 仅在开发/测试中使用,禁用同源策略
  74. //Microsoft.Web.WebView2.Core.CoreWebView2Environment env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(null, null, options);
  75. var userDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp/webview2_temp");
  76. var environment = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
  77. await webView21.EnsureCoreWebView2Async(environment);
  78. // await SparkAI("");
  79. // webView2.Source = new Uri("https://www.baidu.com");
  80. if (webView21 != null)
  81. {
  82. //webView21.Source = new Uri("about:blank"); // 设置源 URL
  83. // webView21.NavigationCompleted += WebView_NavigationCompleted; // 导航完成事件处理函数
  84. // string htmlContent = "<html><body><h1>Hello World!</h1></body></html>"; // 自定义 HTML 内容
  85. // webView21.NavigateToString(htmlContent); // 通过字符串形式传入 HTML 内容
  86. await SparkAI("");
  87. }
  88. }
  89. private void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
  90. {
  91. // 当导航完成时触发该事件,此时可以对 WebView2 进行更多操作
  92. Console.WriteLine($"Navigation completed with status code: {e}");
  93. }
  94. private async Task SparkAI(string name)
  95. {
  96. webView21.Source = new Uri("about:blank"); // 设置源 URL
  97. // InsertHtmlIntoWord(wordApp, processedHtml);
  98. string url = "https://appraisal-test.teammodel.cn/ai/chat/completion";
  99. if (QRCodeForm.token!= null)
  100. {
  101. var checkResult = await HttpClientHelper.CheckToken(UserSettings.Default.access_token, domain, UserSettings.Default.x_auth_token, httpClient);
  102. if (checkResult.ok)
  103. {
  104. QRCodeForm.token.access_token= checkResult.AuthorizationToken;
  105. StringBuilder data = new StringBuilder();
  106. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
  107. var content = new StringContent(JsonSerializer.Serialize(new { appId = "533233bf-4605-4264-ab2d-e57a8084767a", sessionId = "", text = "请按照模板创建10个小学数学题" }), Encoding.UTF8, "application/json");
  108. var httpreq = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
  109. checkResult.httpClient.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8"));
  110. var response = await checkResult.httpClient.SendAsync(httpreq, HttpCompletionOption.ResponseHeadersRead);
  111. // 读取响应内容的异步流
  112. using (var responseStream = await response.Content.ReadAsStreamAsync())
  113. {
  114. //Debug.Print("============start response use minseconds=" + (DateTime.Now - d).TotalMilliseconds + " =================\r\n");
  115. // 逐块读取并处理响应内容
  116. var buffer = new byte[1024];
  117. int bytesRead;
  118. while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
  119. {
  120. // 处理响应内容
  121. string contentData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
  122. if (contentData.Contains("data:"))
  123. {
  124. contentData = contentData.Replace("data:", "").Replace("[DONE]", "");
  125. }
  126. if (contentData.Contains("[DONE]"))
  127. {
  128. contentData = contentData.Replace("data:", "").Replace("[DONE]", "");
  129. }
  130. data.Append(contentData);
  131. webView21.NavigateToString(data.ToString());
  132. var webView2 = webView21.CoreWebView2;
  133. await webView2.ExecuteScriptAsync("window.scrollTo(0, document.body.scrollHeight);");
  134. }
  135. }
  136. webView21.NavigationCompleted += WebView_NavigationCompleted; // 导航完成事件处理函数
  137. }
  138. else { MessageBox.Show(lang.unlogin); }
  139. }
  140. else { MessageBox.Show(lang.unlogin); }
  141. }
  142. private void AI_FormClosed(object sender, FormClosedEventArgs e) {
  143. }
  144. private async void AddAIItem_Click(object sender, EventArgs e)
  145. {
  146. // 使用 JavaScript 选择整个网页内容
  147. await webView21.CoreWebView2.ExecuteScriptAsync("document.execCommand('selectall')");
  148. // 使用 JavaScript 复制选定的内容到剪贴板
  149. await webView21.CoreWebView2.ExecuteScriptAsync("document.execCommand('copy')");
  150. IDataObject dataObject = Clipboard.GetDataObject();
  151. // 检查是否有图像数据
  152. if (dataObject != null && dataObject.GetDataPresent(DataFormats.Bitmap))
  153. {
  154. // 如果有图像数据,粘贴图像
  155. Bitmap bitmap = (Bitmap)dataObject.GetData(DataFormats.Bitmap);
  156. Globals.ThisAddIn.Application.ActiveDocument.Application.Selection.InlineShapes.AddPicture("", false, true).Range.PasteSpecial(DataType: Microsoft.Office.Interop.Word.WdPasteDataType.wdPasteBitmap);
  157. }
  158. else
  159. {
  160. // 如果没有图像数据,可以尝试其他格式的粘贴
  161. Globals.ThisAddIn.Application.ActiveDocument.Application.Selection.Paste();
  162. }
  163. }
  164. private void GenAIItem_Click(object sender, EventArgs e)
  165. {
  166. if (!string.IsNullOrWhiteSpace(richTextBoxEx.Text) && comboBox_subject.SelectedItem!=null && comboBox_item_type.SelectedItem!=null) {
  167. }
  168. }
  169. public void CenterFormOnScreen(Control qrCodeForm)
  170. {
  171. // 获取屏幕的工作区域
  172. var workingArea = System.Windows.Forms.Screen.GetWorkingArea(qrCodeForm);
  173. // 计算窗体应该显示的位置
  174. int x = (workingArea.Width - qrCodeForm.Width) / 2 + workingArea.Left;
  175. int y = (workingArea.Height - qrCodeForm.Height) / 2 + workingArea.Top;
  176. // 设置窗体位置
  177. qrCodeForm.Location = new System.Drawing.Point(x, y);
  178. }
  179. private void Button_AI_Option_Click(object sender, EventArgs e)
  180. {
  181. AISettingForm settingForm = new AISettingForm(schoolDropDown, periodSubjects,lang,markRibbon,domain);
  182. CenterFormOnScreen(settingForm);
  183. settingForm.ShowDialog();
  184. }
  185. }
  186. }