Nowcoder Better!

牛客竞赛题目翻译,markdown视图,一键复制题目

As of 16.08.2023. See ბოლო ვერსია.

  1. // ==UserScript==
  2. // @name Nowcoder Better!
  3. // @namespace https://greatest.deepsurf.us/users/747162
  4. // @version 1.0
  5. // @description 牛客竞赛题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://ac.nowcoder.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect translate.google.com
  11. // @connect openai.api2d.net
  12. // @connect api.openai.com
  13. // @connect www.luogu.com.cn
  14. // @connect greatest.deepsurf.us
  15. // @connect *
  16. // @grant GM_xmlhttpRequest
  17. // @grant GM_info
  18. // @grant GM_setValue
  19. // @grant GM_getValue
  20. // @grant GM_addStyle
  21. // @grant GM_setClipboard
  22. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/nowcoder.png
  23. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  24. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  25. // @license MIT
  26. // @compatible Chrome
  27. // @compatible Firefox
  28. // @compatible Edge
  29. // ==/UserScript==
  30.  
  31. // 状态与初始化
  32. const getGMValue = (key, defaultValue) => {
  33. const value = GM_getValue(key);
  34. if (value === undefined || value === "") {
  35. GM_setValue(key, defaultValue);
  36. return defaultValue;
  37. }
  38. return value;
  39. };
  40.  
  41. const translation = getGMValue("translation", "deepl");
  42. const enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  43. const hoverTargetAreaDisplay = getGMValue("hoverTargetAreaDisplay", false);
  44. //openai
  45. const openai_model = getGMValue("openai_model", "gpt-3.5-turbo");
  46. var showOpneAiAdvanced = getGMValue("showOpneAiAdvanced", false);
  47. // api2d
  48. const api2d_model = getGMValue("api2d_model", "gpt-3.5-turbo");
  49. const api2d_request_entry = getGMValue("api2d_request_entry", "https://openai.api2d.net");
  50. var x_api2d_no_cache = getGMValue("x_api2d_no_cache", true);
  51.  
  52. // 常量
  53. const helpCircleHTML = '<div class="help-icon"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm23.744 191.488c-52.096 0-92.928 14.784-123.2 44.352-30.976 29.568-45.76 70.4-45.76 122.496h80.256c0-29.568 5.632-52.8 17.6-68.992 13.376-19.712 35.2-28.864 66.176-28.864 23.936 0 42.944 6.336 56.32 19.712 12.672 13.376 19.712 31.68 19.712 54.912 0 17.6-6.336 34.496-19.008 49.984l-8.448 9.856c-45.76 40.832-73.216 70.4-82.368 89.408-9.856 19.008-14.08 42.24-14.08 68.992v9.856h80.96v-9.856c0-16.896 3.52-31.68 10.56-45.76 6.336-12.672 15.488-24.64 28.16-35.2 33.792-29.568 54.208-48.576 60.544-55.616 16.896-22.528 26.048-51.392 26.048-86.592 0-42.944-14.08-76.736-42.24-101.376-28.16-25.344-65.472-37.312-111.232-37.312zm-12.672 406.208a54.272 54.272 0 0 0-38.72 14.784 49.408 49.408 0 0 0-15.488 38.016c0 15.488 4.928 28.16 15.488 38.016A54.848 54.848 0 0 0 523.072 768c15.488 0 28.16-4.928 38.72-14.784a51.52 51.52 0 0 0 16.192-38.72 51.968 51.968 0 0 0-15.488-38.016 55.936 55.936 0 0 0-39.424-14.784z"></path></svg></div>';
  54. const darkenPageStyle = `body::before { content: ""; display: block; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.4); z-index: 9999; }`;
  55.  
  56. // 样式
  57. GM_addStyle(`
  58. :root {
  59. --vp-font-family-base: "Chinese Quotes", "Inter var", "Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
  60. }
  61. span.mdViewContent {
  62. white-space: pre-wrap;
  63. }
  64. /*翻译区域提示*/
  65. .overlay {
  66. pointer-events: none;
  67. position: absolute;
  68. top: 0;
  69. left: 0;
  70. width: 100%;
  71. height: 100%;
  72. background: repeating-linear-gradient(135deg, #97e7cacc, #97e7cacc 30px, #e9fbf1cc 0px, #e9fbf1cc 55px);
  73. border-radius: 5px;
  74. display: flex;
  75. align-items: center;
  76. justify-content: center;
  77. color: #00695C;
  78. font-size: 16px;
  79. font-weight: bold;
  80. text-shadow: 0px 0px 2px #edfcf4;
  81. }
  82. /*翻译div*/
  83. .translate-problem-statement {
  84. justify-items: start;
  85. letter-spacing: 1.8px;
  86. color: #059669;
  87. background-color: #f9f9fa;
  88. border: 1px solid #10b981;
  89. border-radius: 0.3rem;
  90. padding: 5px;
  91. margin: 10px 0px;
  92. width: 100%;
  93. box-sizing: border-box;
  94. font-size: 13px;
  95. }
  96. .translate-problem-statement.error_translate {
  97. color: red;
  98. border-color: red;
  99. }
  100.  
  101. .translate-problem-statement h2, .translate-problem-statement h3 {
  102. font-size: 16px;
  103. }
  104.  
  105. .translate-problem-statement ul {
  106. line-height: 100%;
  107. }
  108.  
  109. .translate-problem-statement a {
  110. color: #10b981;
  111. font-weight: 600;
  112. background: 0 0;
  113. text-decoration: none;
  114. }
  115. .translate-problem-statement p {
  116. font-size: 14px !important;
  117. }
  118. .translate-problem-statement img {
  119. max-width: 100.0%;
  120. max-height: 100.0%;
  121. }
  122.  
  123. .translate-problem-statement .katex {
  124. font-size: 14px;
  125. }
  126. .translate-problem-statement a:hover {
  127. text-decoration: revert;
  128. }
  129. .html2md-panel {
  130. display: flex;
  131. justify-content: flex-end;
  132. }
  133. .html2md-panel a {
  134. text-decoration: none;
  135. }
  136. button.html2mdButton {
  137. display: flex;
  138. align-items: center;
  139. cursor: pointer;
  140. background-color: #ffffff;
  141. color: #606266;
  142. height: 22px;
  143. width: auto;
  144. font-size: 13px;
  145. border-radius: 0.3rem;
  146. padding: 1px 5px;
  147. margin: 5px;
  148. border: 1px solid #dcdfe6;
  149. }
  150. button.html2mdButton:hover {
  151. color: #409eff;
  152. border-color: #409eff;
  153. }
  154. button.html2mdButton.copied {
  155. background-color: #f0f9eb;
  156. color: #67c23e;
  157. border: 1px solid #b3e19d;
  158. }
  159. button.html2mdButton.mdViewed {
  160. background-color: #fdf6ec;
  161. color: #e6a23c;
  162. border: 1px solid #f3d19e;
  163. }
  164. button.html2mdButton.error {
  165. background-color: #fef0f0;
  166. color: #f56c6c;
  167. border: 1px solid #fab6b6;
  168. }
  169. button.translated {
  170. cursor: not-allowed;
  171. background-color: #f0f9eb;
  172. color: #67c23e;
  173. border: 1px solid #b3e19d;
  174. }
  175. button.html2mdButton.reTranslation {
  176. background-color: #f4f4f5;
  177. color: #909399;
  178. border: 1px solid #c8c9cc;
  179. }
  180. .translate-problem-statement table {
  181. border: 1px #ccc solid !important;
  182. margin: 1.5em 0 !important;
  183. color: #059669 !important;
  184. }
  185. .translate-problem-statement table thead th {
  186. border: 1px #ccc solid !important;
  187. color: #059669 !important;
  188. }
  189. .translate-problem-statement table td {
  190. border-right: 1px solid #ccc;
  191. border-top: 1px solid #ccc;
  192. padding: 0.7143em 0.5em;
  193. }
  194. .translate-problem-statement table th {
  195. padding: 0.7143em 0.5em;
  196. }
  197. .translate-problem-statement p:not(:first-child) {
  198. margin: 1.5em 0 0;
  199. }
  200. /*设置面板*/
  201. header .enter-or-register-box, header .languages {
  202. position: absolute;
  203. right: 170px;
  204. }
  205. button.html2mdButton.NowcoderBetter_setting {
  206. float: right;
  207. height: 30px;
  208. background: #25bb9b;
  209. color: white;
  210. margin: 10px;
  211. border: 0px;
  212. }
  213.  
  214. button.html2mdButton.NowcoderBetter_setting.open {
  215. background-color: #e6e6e61f;
  216. color: #727378;
  217. cursor: not-allowed;
  218. }
  219. #NowcoderBetter_setting_menu {
  220. z-index: 9999;
  221. box-shadow: 0px 0px 0px 4px #ffffff;
  222. display: grid;
  223. position: fixed;
  224. top: 50%;
  225. left: 50%;
  226. width: 500px;
  227. max-height: 90vh;
  228. overflow-y: auto;
  229. transform: translate(-50%, -50%);
  230. border-radius: 6px;
  231. background-color: #edf1ff;
  232. border-collapse: collapse;
  233. border: 1px solid #ffffff;
  234. color: #697e91;
  235. font-family: var(--vp-font-family-base);
  236. padding: 10px 20px 20px 20px;
  237. }
  238. #NowcoderBetter_setting_menu h3 {
  239. margin-top: 10px;
  240. font-weight: 600;
  241. font-size: 18px;
  242. }
  243. #NowcoderBetter_setting_menu hr {
  244. border: none;
  245. height: 1px;
  246. background-color: #ccc;
  247. margin: 10px 0;
  248. }
  249. /*设置面板-关闭按钮*/
  250. #NowcoderBetter_setting_menu .tool-box {
  251. position: absolute;
  252. display: flex;
  253. align-items: center;
  254. justify-content: center;
  255. width: 2.5rem;
  256. height: 2.5rem;
  257. top: 3px;
  258. right: 3px;
  259. }
  260.  
  261. #NowcoderBetter_setting_menu .btn-close {
  262. display: flex;
  263. align-items: center;
  264. justify-content: center;
  265. text-align: center;
  266. padding: 10px !important;
  267. width: 1px;
  268. height: 1px !important;
  269. color: transparent;
  270. font-size: 0;
  271. cursor: pointer;
  272. background-color: #ff000080;
  273. border: none;
  274. border-radius: 10px;
  275. transition: .15s ease all;
  276. }
  277.  
  278. #NowcoderBetter_setting_menu .btn-close:hover {
  279. width: 20px;
  280. height: 20px !important;
  281. font-size: 17px;
  282. color: #ffffff;
  283. background-color: #ff0000cc;
  284. box-shadow: 0 5px 5px 0 #00000026;
  285. }
  286.  
  287. #NowcoderBetter_setting_menu .btn-close:active {
  288. width: .9rem;
  289. height: .9rem;
  290. font-size: 1px;
  291. color: #ffffffde;
  292. --shadow-btn-close: 0 3px 3px 0 #00000026;
  293. box-shadow: var(--shadow-btn-close);
  294. }
  295.  
  296. /*设置面板-checkbox*/
  297. #NowcoderBetter_setting_menu input[type=checkbox]:focus {
  298. outline: 0px;
  299. }
  300.  
  301. #NowcoderBetter_setting_menu input[type="checkbox"] {
  302. margin: 0px;
  303. appearance: none;
  304. -webkit-appearance: none;
  305. width: 40px;
  306. height: 20px !important;
  307. border: 1.5px solid #D7CCC8;
  308. padding: 0px !important;
  309. border-radius: 20px;
  310. background: #efebe978;
  311. position: relative;
  312. box-sizing: border-box;
  313. }
  314.  
  315. #NowcoderBetter_setting_menu input[type="checkbox"]::before {
  316. content: "";
  317. width: 14px;
  318. height: 14px;
  319. background: #D7CCC8;
  320. border: 1.5px solid #BCAAA4;
  321. border-radius: 50%;
  322. position: absolute;
  323. top: 0;
  324. left: 0;
  325. transform: translate(2%, 2%);
  326. transition: all 0.3s ease-in-out;
  327. -webkit-box-sizing: content-box;
  328. -moz-box-sizing: content-box;
  329. box-sizing: content-box;
  330. }
  331.  
  332. #NowcoderBetter_setting_menu input[type="checkbox"]::after {
  333. content: url("data:image/svg+xml,%3Csvg xmlns='://www.w3.org/2000/svg' width='23' height='23' viewBox='0 0 23 23' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M6.55021 5.84315L17.1568 16.4498L16.4497 17.1569L5.84311 6.55026L6.55021 5.84315Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M17.1567 6.55021L6.55012 17.1568L5.84302 16.4497L16.4496 5.84311L17.1567 6.55021Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3C/svg%3E");
  334. position: absolute;
  335. top: 0;
  336. left: 24px;
  337. }
  338.  
  339. #NowcoderBetter_setting_menu input[type="checkbox"]:checked {
  340. border: 1.5px solid #C5CAE9;
  341. background: #E8EAF6;
  342. }
  343.  
  344. #NowcoderBetter_setting_menu input[type="checkbox"]:checked::before {
  345. background: #C5CAE9;
  346. border: 1.5px solid #7986CB;
  347. transform: translate(122%, 2%);
  348. transition: all 0.3s ease-in-out;
  349. }
  350.  
  351. #NowcoderBetter_setting_menu input[type="text"]:focus-visible{
  352. border-width: 0.2vh;
  353. border-style: solid;
  354. border-color: #8bb2d9;
  355. outline: -webkit-focus-ring-color auto 0px;
  356. }
  357.  
  358. #NowcoderBetter_setting_menu input[type="checkbox"]:checked::after {
  359. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 15 13' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M14.8185 0.114533C15.0314 0.290403 15.0614 0.605559 14.8855 0.818454L5.00187 12.5L0.113036 6.81663C-0.0618274 6.60291 -0.0303263 6.2879 0.183396 6.11304C0.397119 5.93817 0.71213 5.96967 0.886994 6.18339L5.00187 11L14.1145 0.181573C14.2904 -0.0313222 14.6056 -0.0613371 14.8185 0.114533Z' fill='%2303A9F4' fill-opacity='0.9'/%3E%3C/svg%3E");
  360. position: absolute;
  361. top: 1.5px;
  362. left: 4.5px;
  363. }
  364.  
  365. #NowcoderBetter_setting_menu label {
  366. font-size: 16px;
  367. font-weight: initial;
  368. margin-bottom: 0px;
  369. }
  370.  
  371. .NowcoderBetter_setting_list {
  372. display: flex;
  373. align-items: center;
  374. padding: 10px;
  375. margin: 5px 0px;
  376. background-color: #ffffff;
  377. border-bottom: 1px solid #c9c6c696;
  378. border-radius: 8px;
  379. justify-content: space-between;
  380. }
  381.  
  382. /*设置面板-radio*/
  383. #NowcoderBetter_setting_menu>label {
  384. display: flex;
  385. list-style-type: none;
  386. padding-inline-start: 0px;
  387. overflow-x: auto;
  388. max-width: 100%;
  389. margin: 0px;
  390. align-items: center;
  391. margin: 3px 0px;
  392. }
  393.  
  394. .NowcoderBetter_setting_menu_label_text {
  395. display: flex;
  396. border: 1px dashed #00aeeccc;
  397. height: 20px;
  398. width: 100%;
  399. color: gray;
  400. font-weight: 300;
  401. font-size: 14px;
  402. letter-spacing: 2px;
  403. padding: 7px;
  404. align-items: center;
  405. -webkit-box-sizing: content-box;
  406. -moz-box-sizing: content-box;
  407. box-sizing: content-box;
  408. }
  409.  
  410. input[type="radio"]:checked+.NowcoderBetter_setting_menu_label_text {
  411. background: #41e49930;
  412. border: 1px solid green;
  413. color: green;
  414. font-weight: 500;
  415. }
  416.  
  417. #NowcoderBetter_setting_menu>label input[type="radio"] {
  418. -webkit-appearance: none;
  419. appearance: none;
  420. list-style: none;
  421. padding: 0px !important;
  422. margin: 0px;
  423. }
  424.  
  425. #NowcoderBetter_setting_menu input[type="text"] {
  426. display: block;
  427. height: 25px !important;
  428. width: 100%;
  429. background-color: #ffffff;
  430. color: #727378;
  431. font-size: 12px;
  432. border-radius: 0.3rem;
  433. padding: 1px 5px !important;
  434. box-sizing: border-box;
  435. margin: 5px 0px 5px 0px;
  436. border: 1px solid #00aeeccc;
  437. box-shadow: 0 0 1px #0000004d;
  438. }
  439.  
  440. .NowcoderBetter_setting_menu_input {
  441. width: 100%;
  442. display: grid;
  443. margin-top: 5px;
  444. }
  445.  
  446. #NowcoderBetter_setting_menu #save {
  447. cursor: pointer;
  448. display: inline-flex;
  449. padding: 0.5rem 1rem;
  450. background-color: #1aa06d;
  451. color: #ffffff;
  452. font-size: 1rem;
  453. line-height: 1.5rem;
  454. font-weight: 500;
  455. justify-content: center;
  456. width: 100%;
  457. border-radius: 0.375rem;
  458. border: none;
  459. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  460. }
  461. #NowcoderBetter_setting_menu button#debug_button.debug_button {
  462. width: 18%;
  463. }
  464.  
  465. #NowcoderBetter_setting_menu span.tip {
  466. color: #999;
  467. font-size: 12px;
  468. font-weight: 500;
  469. padding: 5px 0px;
  470. }
  471. /*设置面板-tip*/
  472. .help_tip {
  473. margin-right: auto;
  474. }
  475. .help_tip .tip_text {
  476. display: none;
  477. position: absolute;
  478. color: #697e91;
  479. font-weight: 400;
  480. letter-spacing: 0px;
  481. background-color: #ffffff;
  482. padding: 10px;
  483. margin: 5px 0px;
  484. border-radius: 4px;
  485. border: 1px solid #e4e7ed;
  486. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  487. z-index: 999;
  488. }
  489. .help_tip .tip_text p {
  490. margin-bottom: 5px;
  491. }
  492. .help_tip .tip_text:before {
  493. content: "";
  494. position: absolute;
  495. top: -20px;
  496. right: -10px;
  497. bottom: -10px;
  498. left: -10px;
  499. z-index: -1;
  500. }
  501. .help-icon {
  502. display: flex;
  503. cursor: help;
  504. width: 15px;
  505. color: rgb(255, 153, 0);
  506. margin-left: 5px;
  507. }
  508. #CFBetter_setting_menu .CFBetter_setting_menu_label_text .help_tip .help-icon {
  509. color: #7fbeb2;
  510. }
  511. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  512. display: block;
  513. cursor: help;
  514. width: 250px;
  515. }
  516. /*设置面板-展开*/
  517. #is_showOpneAiAdvanced{
  518. width: 100%;
  519. background-color: aliceblue;
  520. padding: 8px;
  521. box-sizing: border-box;
  522. border-radius: 10px;
  523. }
  524. /*确认弹窗*/
  525. .wordsExceeded {
  526. z-index: 99999;
  527. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  528. display: grid;
  529. position: fixed;
  530. top: 50%;
  531. left: 50%;
  532. transform: translate(-50%, -50%);
  533. border-radius: 4px;
  534. background-color: #ffffff;
  535. border: 1px solid #e4e7ed;
  536. color: #697e91;
  537. font-family: var(--vp-font-family-base);
  538. padding: 10px 20px 20px 20px;
  539. }
  540. .wordsExceeded button {
  541. display: inline-flex;
  542. justify-content: center;
  543. align-items: center;
  544. line-height: 1;
  545. white-space: nowrap;
  546. cursor: pointer;
  547. text-align: center;
  548. box-sizing: border-box;
  549. outline: none;
  550. transition: .1s;
  551. user-select: none;
  552. vertical-align: middle;
  553. -webkit-appearance: none;
  554. height: 24px;
  555. padding: 5px 11px;
  556. font-size: 12px;
  557. border-radius: 4px;
  558. color: #ffffff;
  559. background: #409eff;
  560. border-color: #409eff;
  561. border: none;
  562. margin-right: 12px;
  563. }
  564. .wordsExceeded button:hover{
  565. background-color:#79bbff;
  566. }
  567. .wordsExceeded .help-icon {
  568. margin: 0px 8px 0px 0px;
  569. height: 1em;
  570. width: 1em;
  571. line-height: 1em;
  572. display: inline-flex;
  573. justify-content: center;
  574. align-items: center;
  575. position: relative;
  576. fill: currentColor;
  577. font-size: inherit;
  578. }
  579. .wordsExceeded p {
  580. margin: 5px 0px;
  581. }
  582. /*更新检查*/
  583. div#update_panel {
  584. z-index: 9999;
  585. position: fixed;
  586. top: 50%;
  587. left: 50%;
  588. width: 240px;
  589. transform: translate(-50%, -50%);
  590. box-shadow: 0px 0px 4px 0px #0000004d;
  591. padding: 10px 20px 20px 20px;
  592. color: #444242;
  593. background-color: #f5f5f5;
  594. border: 1px solid #848484;
  595. border-radius: 8px;
  596. }
  597. div#update_panel #updating {
  598. cursor: pointer;
  599. display: inline-flex;
  600. padding: 3px;
  601. background-color: #1aa06d;
  602. color: #ffffff;
  603. font-size: 1rem;
  604. line-height: 1.5rem;
  605. font-weight: 500;
  606. justify-content: center;
  607. width: 100%;
  608. border-radius: 0.375rem;
  609. border: none;
  610. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  611. }
  612. div#update_panel #updating a {
  613. text-decoration: none;
  614. color: white;
  615. display: flex;
  616. position: inherit;
  617. top: 0;
  618. left: 0;
  619. width: 100%;
  620. height: 22px;
  621. font-size: 14px;
  622. justify-content: center;
  623. align-items: center;
  624. }
  625. #skip_menu {
  626. display: flex;
  627. margin-top: 10px;
  628. justify-content: flex-end;
  629. align-items: center;
  630. }
  631. #skip_menu .help_tip {
  632. margin-right: 5px;
  633. margin-left: -5px;
  634. }
  635. #skip_menu .help-icon {
  636. color: #f44336;
  637. }
  638. `);
  639.  
  640. // 获取cookie
  641. function getCookie(name) {
  642. const cookies = document.cookie.split(";");
  643. for (let i = 0; i < cookies.length; i++) {
  644. const cookie = cookies[i].trim();
  645. const [cookieName, cookieValue] = cookie.split("=");
  646.  
  647. if (cookieName === name) {
  648. return decodeURIComponent(cookieValue);
  649. }
  650. }
  651. return "";
  652. }
  653.  
  654. // 防抖函数
  655. function debounce(callback) {
  656. let timer;
  657. let immediateExecuted = false;
  658. const delay = 500;
  659. return function () {
  660. clearTimeout(timer);
  661. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  662. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  663. };
  664. }
  665.  
  666. // 更新检查
  667. (function checkScriptVersion() {
  668. function compareVersions(version1 = "0", version2 = "0") {
  669. const v1Array = String(version1).split(".");
  670. const v2Array = String(version2).split(".");
  671. const minLength = Math.min(v1Array.length, v2Array.length);
  672. let result = 0;
  673. for (let i = 0; i < minLength; i++) {
  674. const curV1 = Number(v1Array[i]);
  675. const curV2 = Number(v2Array[i]);
  676. if (curV1 > curV2) {
  677. result = 1;
  678. break;
  679. } else if (curV1 < curV2) {
  680. result = -1;
  681. break;
  682. }
  683. }
  684. if (result === 0 && v1Array.length !== v2Array.length) {
  685. const v1IsBigger = v1Array.length > v2Array.length;
  686. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  687. for (let i = minLength; i < maxLenArray.length; i++) {
  688. const curVersion = Number(maxLenArray[i]);
  689. if (curVersion > 0) {
  690. v1IsBigger ? result = 1 : result = -1;
  691. break;
  692. }
  693. }
  694. }
  695. return result;
  696. }
  697.  
  698. GM_xmlhttpRequest({
  699. method: "GET",
  700. url: "https://greatest.deepsurf.us/zh-CN/scripts/472415.json",
  701. timeout: 10 * 1e3,
  702. onload: function (response) {
  703. const scriptData = JSON.parse(response.responseText);
  704. const skipUpdate = getCookie("skipUpdate");
  705.  
  706. if (
  707. scriptData.name === GM_info.script.name &&
  708. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  709. skipUpdate !== "true"
  710. ) {
  711. const styleElement = GM_addStyle(darkenPageStyle);
  712. $("body").append(`
  713. <div id='update_panel'>
  714. <h3>${GM_info.script.name}有新版本!</h3>
  715. <hr>
  716. <div class='update_panel_menu'>
  717. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  718. </div>
  719. <br>
  720. <div id="skip_menu">
  721. <div class="help_tip">
  722. `+ helpCircleHTML + `
  723. <div class="tip_text">
  724. <p><b>更新遇到了问题?</b></p>
  725. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  726. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  727. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  728. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  729. </div>
  730. </div>
  731. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  732. </div>
  733. </div>
  734. `);
  735.  
  736. $("#skip_update").click(function () {
  737. document.cookie = "skipUpdate=true; expires=session; path=/";
  738. styleElement.remove();
  739. $("#update_panel").remove();
  740. });
  741. }
  742. }
  743. });
  744.  
  745. })();
  746.  
  747. // 设置面板
  748. $(document).ready(function () {
  749. var htmlContent = "<button class='html2mdButton NowcoderBetter_setting'>Nowcoder Better设置</button>";
  750. if ($('.acm-nav-info').length > 0) $('.acm-nav-info > li:last-child').after("<li class='dropdown'>" + htmlContent + "</li>");
  751. else $('.header-bar .header-right > :last-child').after(htmlContent);
  752. });
  753.  
  754. $(document).ready(function () {
  755. const $settingBtns = $(".NowcoderBetter_setting");
  756. $settingBtns.click(() => {
  757. const styleElement = GM_addStyle(darkenPageStyle);
  758. $settingBtns.prop("disabled", true).addClass("open");
  759. $("body").append(`
  760. <div id='NowcoderBetter_setting_menu'>
  761. <div class="tool-box">
  762. <button class="btn-close">×</button>
  763. </div>
  764. <h3>基本设置</h3>
  765. <hr>
  766. <div class='NowcoderBetter_setting_list'>
  767. <label for="hoverTargetAreaDisplay">显示目标区域范围</label>
  768. <div class="help_tip">
  769. `+ helpCircleHTML + `
  770. <div class="tip_text">
  771. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  772. </div>
  773. </div>
  774. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  775. </div>
  776. <div class='NowcoderBetter_setting_list'>
  777. <label for="enableSegmentedTranslation">分段翻译</label>
  778. <div class="help_tip">
  779. `+ helpCircleHTML + `
  780. <div class="tip_text">
  781. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  782. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  783. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  784. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  785. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  786. </div>
  787. </div>
  788. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  789. </div>
  790. <h3>翻译设置</h3>
  791. <hr>
  792. <label>
  793. <input type='radio' name='translation' value='deepl'>
  794. <span class='NowcoderBetter_setting_menu_label_text'>deepl翻译</span>
  795. </label>
  796. <label>
  797. <input type='radio' name='translation' value='youdao'>
  798. <span class='NowcoderBetter_setting_menu_label_text'>有道翻译</span>
  799. </label>
  800. <label>
  801. <input type='radio' name='translation' value='google'>
  802. <span class='NowcoderBetter_setting_menu_label_text'>Google翻译</span>
  803. </label>
  804. <label>
  805. <input type='radio' name='translation' value='openai'>
  806. <span class='NowcoderBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  807. <div class="help_tip">
  808. `+ helpCircleHTML + `
  809. <div class="tip_text">
  810. <p><b>如果你不使用代理API,请确保你能够正常访问OpenAIapi</b></p>
  811. <p>Nowcoder Better!默认使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  812. <p>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  813. </div>
  814. </div>
  815. </span>
  816. </label>
  817. <label>
  818. <input type='radio' name='translation' value='api2d'>
  819. <span class='NowcoderBetter_setting_menu_label_text'>使用api2d翻译(API)
  820. <div class="help_tip">
  821. `+ helpCircleHTML + `
  822. <div class="tip_text">
  823. <p>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳</p>
  824. <p>Nowcoder Better!默认使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  825. <p>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></p>
  826. </div>
  827. </div>
  828. </span>
  829. </label>
  830. <div class='NowcoderBetter_setting_menu_input' id='openai' style='display: none;'>
  831. <label for='openai_model'>
  832. <div style="display: flex;align-items: center;">
  833. <span class="input_label">模型:</span>
  834. <div class="help_tip">
  835. `+ helpCircleHTML + `
  836. <div class="tip_text">
  837. <p>默认为:gpt-3.5-turbo</p>
  838. <p>如需更换,请查阅<a target="_blank" href="https://platform.openai.com/docs/models">官方文档</a></p>
  839. <p><strong>如果你使用的是服务商提供的代理API,请确认服务商是否支持对应模型</strong></p>
  840. </div>
  841. </div>
  842. </div>
  843. </label>
  844. <input type='text' id='openai_model'>
  845. <label for='openai_key'>
  846. <span class="input_label">KEY:</span>
  847. </label>
  848. <input type='text' id='openai_key'>
  849. <div class='NowcoderBetter_setting_list'>
  850. <label for="showOpneAiAdvanced">使用代理API</label>
  851. <div class="help_tip">
  852. `+ helpCircleHTML + `
  853. <div class="tip_text">
  854. <p>使用你指定的API来代理访问OpenAI进行翻译,脚本的所有请求均在本地完成</p>
  855. <p>如果你使用的是OpenAI的官方KEY,建议你自建代理,而不是使用他人公开的代理,那是危险的</p>
  856. <p>如果你使用的是服务商提供的代理和KEY,则这里应该填写其提供的<strong>完整</strong>API地址,<br>
  857. 这里以<a target="_blank" href="https://console.closeai-asia.com/">CloseAI</a>为例,其提供了API Base: https://api.closeai-proxy.xyz,<br>
  858. 那么这里实际应该填写的就是https://api.closeai-proxy.xyz/v1/chat/\ncompletions,而上面的KEY则应该填写CloseAI提供的API Key</p>
  859. <p><strong>由于你指定了自定义的APITampermonkey会对你的跨域请求进行警告,请自行授权</strong></p>
  860. </div>
  861. </div>
  862. <input type="checkbox" id="showOpneAiAdvanced" name="showOpneAiAdvanced">
  863. </div>
  864. <div id="is_showOpneAiAdvanced">
  865. <label for='openai_proxy'>
  866. <span class="input_label">Proxy API:</span>
  867. </label>
  868. <input type='text' id='openai_proxy'>
  869. </div>
  870. </div>
  871. <div class='NowcoderBetter_setting_menu_input' id='api2d' style='display: none;'>
  872. <label for='api2d_model'>
  873. <div style="display: flex;align-items: center;">
  874. <span class="input_label">模型:</span>
  875. <div class="help_tip">
  876. `+ helpCircleHTML + `
  877. <div class="tip_text">
  878. <p>默认为:gpt-3.5-turbo</p>
  879. <p>如需更换,请查阅<a target="_blank" href="https://api2d.com/wiki/doc">官方文档</a></p>
  880. </div>
  881. </div>
  882. </div>
  883. </label>
  884. <input type='text' id='api2d_model'>
  885. <label for='api2d_key'>
  886. <span class="input_label">KEY:</span>
  887. </label>
  888. <input type='text' id='api2d_key'>
  889. <label for='api2d_request_entry'>
  890. <div style="display: flex;align-items: center;">
  891. <span class="input_label">请求入口:</span>
  892. <div class="help_tip">
  893. `+ helpCircleHTML + `
  894. <div class="tip_text">
  895. <p>如果发现请求报错超时未响应,请查看<a target="_blank" href="https://api2d.com/wiki/doc">官方文档</a>以及<a target="_blank" href="https://support.qq.com/product/544571">API2D反馈论坛</a>尝试更换请求入口</p>
  896. <p>默认为:https://openai.api2d.net</p>
  897. <p>注意格式,末尾没有“斜杠/”</p>
  898. </div>
  899. </div>
  900. </div>
  901. </label>
  902. <input type='text' id='api2d_request_entry'>
  903. <div class='NowcoderBetter_setting_list'>
  904. <label for="x_api2d_no_cache">使用缓存</label>
  905. <div class="help_tip">
  906. `+ helpCircleHTML + `
  907. <div class="tip_text">
  908. <p>API2D 的服务器会对请求结果做缓存,如果请求体的hash值相同,会直接返回缓存的结果。缓存命中之后,本次请求不会扣除任何点数。</p>
  909. <p>缓存会保存 24 小时,如果不想使用缓存,你可以关闭“使用缓存”来跳过缓存,强制 API2D 服务器发送新请求。<a target="_blank" href="https://api2d.com/wiki/doc">详请阅读官方文档</a></p>
  910. </div>
  911. </div>
  912. <input type="checkbox" id="x_api2d_no_cache" name="x_api2d_no_cache">
  913. </div>
  914. </div>
  915. <br>
  916. <button id='save'>保存</button>
  917. </div>
  918. `);
  919. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  920. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache") === true);
  921. $("#showOpneAiAdvanced").prop("checked", GM_getValue("showOpneAiAdvanced") === true);
  922. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  923. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  924. $("input[name='translation']").css("color", "gray");
  925. if (translation == "openai") {
  926. $("#openai").show();
  927. $("#openai_model").val(openai_model);
  928. $("#openai_key").val(GM_getValue("openai_key"));
  929. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  930. $("#openai_key").css("color", "gray");
  931. if (showOpneAiAdvanced) $("#is_showOpneAiAdvanced").show();
  932. else $("#is_showOpneAiAdvanced").hide();
  933. } else if (translation == "api2d") {
  934. $("#api2d").show();
  935. $("#api2d_model").val(api2d_model);
  936. $("#api2d_key").val(GM_getValue("api2d_key"));
  937. $("#api2d_request_entry").val(api2d_request_entry);
  938. $("#api2d_key").css("color", "gray");
  939. }
  940. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  941. $("input[name='translation']").change(function () {
  942. var selected = $(this).val(); // 获取当前选中的值
  943. if (selected === "openai") {
  944. $("#openai").show();
  945. $("#openai_model").val(openai_model);
  946. $("#openai_key").val(GM_getValue("openai_key"));
  947. $("#showOpneAiAdvanced").prop("checked", showOpneAiAdvanced);
  948. if (showOpneAiAdvanced) {
  949. $("#is_showOpneAiAdvanced").show();
  950. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  951. }
  952. else $("#is_showOpneAiAdvanced").hide();
  953. $("#api2d").hide();
  954. } else if (selected === "api2d") {
  955. $("#api2d").show();
  956. $("#api2d_model").val(api2d_model);
  957. $("#api2d_key").val(GM_getValue("api2d_key"));
  958. $("#api2d_request_entry").val(api2d_request_entry);
  959. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache"));
  960. $("#openai").hide();
  961. } else {
  962. $("#openai, #api2d").hide();
  963. }
  964. });
  965.  
  966. // ChatGPT高级选项
  967. $("input[name='showOpneAiAdvanced']").change(function () {
  968. var isChecked = $(this).is(":checked");
  969. if (isChecked) {
  970. $("#is_showOpneAiAdvanced").show();
  971. } else {
  972. $("#is_showOpneAiAdvanced").hide();
  973. }
  974. });
  975.  
  976. const $settingMenu = $("#NowcoderBetter_setting_menu");
  977.  
  978. $("#save").click(debounce(function () {
  979. const settings = {
  980. enableSegmentedTranslation: $("#enableSegmentedTranslation").prop("checked"),
  981. showOpneAiAdvanced: $("#showOpneAiAdvanced").prop("checked"),
  982. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  983. translation: $("input[name='translation']:checked").val()
  984. };
  985. if (settings.translation === "openai") {
  986. GM_setValue("openai_model", $("#openai_model").val());
  987. GM_setValue("openai_key", $("#openai_key").val());
  988. GM_setValue("openai_proxy", $("#openai_proxy").val());
  989. } else if (settings.translation === "api2d") {
  990. GM_setValue("api2d_model", $("#api2d_model").val());
  991. GM_setValue("api2d_key", $("#api2d_key").val());
  992. GM_setValue("api2d_request_entry", $("#api2d_request_entry").val());
  993. GM_setValue("x_api2d_no_cache", $("#x_api2d_no_cache").prop("checked"));
  994. }
  995. for (const [key, value] of Object.entries(settings)) {
  996. GM_setValue(key, value);
  997. }
  998.  
  999. $settingMenu.remove();
  1000. $(styleElement).remove();
  1001. location.reload();
  1002. }));
  1003.  
  1004. // 关闭
  1005. $settingMenu.on("click", ".btn-close", () => {
  1006. $settingMenu.remove();
  1007. $settingBtns.prop("disabled", false).removeClass("open");
  1008. $(styleElement).remove();
  1009. });
  1010. });
  1011. });
  1012.  
  1013. // html2md转换/处理规则
  1014. var turndownService = new TurndownService({ bulletListMarker: '-', escape: (text) => text });
  1015. var turndown = turndownService.turndown;
  1016.  
  1017. // 保留原始
  1018. turndownService.keep(['del']);
  1019.  
  1020. turndownService.addRule('removeByClass', {
  1021. filter: function (node) {
  1022. return node.classList.contains('html2md-panel') ||
  1023. node.classList.contains('div-btn-copy') ||
  1024. node.classList.contains('btn-copy') ||
  1025. node.classList.contains('code-copy-btn') ||
  1026. node.classList.contains('overlay')
  1027. },
  1028. replacement: function () {
  1029. return '';
  1030. }
  1031. });
  1032.  
  1033. // inline math
  1034. turndownService.addRule('inline-math1', {
  1035. filter: function (node, options) {
  1036. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  1037. },
  1038. replacement: function (content, node) {
  1039. var text = $(node).find('annotation').text();
  1040. if (text == "") {
  1041. text = $(node).find('math').contents().filter(function () {
  1042. return this.nodeType === Node.TEXT_NODE;
  1043. }).text();
  1044. }
  1045. return "$" + text + "$";
  1046. }
  1047. });
  1048. turndownService.addRule('inline-math2', {
  1049. filter: function (node, options) {
  1050. return node.tagName.toLowerCase() == "span" && node.className == "katex-mathml";
  1051. },
  1052. replacement: function (content, node) {
  1053. var text = "";
  1054. $(node).contents().each(function () {
  1055. if (this.nodeType === Node.TEXT_NODE) {
  1056. text += $(this).text();
  1057. }
  1058. });
  1059. return "$" + text + "$";
  1060. }
  1061. });
  1062.  
  1063. // block math
  1064. turndownService.addRule('block-math', {
  1065. filter: function (node, options) {
  1066. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  1067. },
  1068. replacement: function (content, node) {
  1069. return "\n$$\n" + $(node).find('annotation').text() + "\n$$\n";
  1070. }
  1071. });
  1072.  
  1073. // pre
  1074. turndownService.addRule('pre', {
  1075. filter: function (node, options) {
  1076. return node.tagName.toLowerCase() == "pre";
  1077. },
  1078. replacement: function (content, node) {
  1079. return "```\n" + content + "```\n";
  1080. }
  1081. });
  1082.  
  1083. // bordertable
  1084. turndownService.addRule('bordertable', {
  1085. filter: 'table',
  1086. replacement: function (content, node) {
  1087. if (node.classList.contains('table')) {
  1088. var output = [],
  1089. thead = '',
  1090. trs = node.querySelectorAll('tr');
  1091. if (trs.length > 0) {
  1092. var ths = trs[0].querySelectorAll('th');
  1093. if (ths.length > 0) {
  1094. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1095. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1096. }
  1097. }
  1098. var rows = node.querySelectorAll('tr');
  1099. Array.from(rows).forEach(function (row, i) {
  1100. if (i > 0) {
  1101. var cells = row.querySelectorAll('td,th');
  1102. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1103. output.push(trow);
  1104. }
  1105. });
  1106. return thead + output.join('\n');
  1107. } else {
  1108. return content;
  1109. }
  1110. }
  1111. });
  1112.  
  1113.  
  1114. // 随机数生成
  1115. function getRandomNumber(numDigits) {
  1116. let min = Math.pow(10, numDigits - 1);
  1117. let max = Math.pow(10, numDigits) - 1;
  1118. return Math.floor(Math.random() * (max - min + 1)) + min;
  1119. }
  1120.  
  1121. // 按钮面板
  1122. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1123. let htmlString = `<div class='html2md-panel'>
  1124. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1125. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1126. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1127. </div>`;
  1128. if (type === "this_level") {
  1129. $(parent).before(htmlString);
  1130. } else if (type === "child_level") {
  1131. $(parent).prepend(htmlString);
  1132. }
  1133. if (is_simple) {
  1134. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1135. }
  1136. }
  1137.  
  1138. function addButtonWithHTML2MD(parent, suffix, type) {
  1139. $(document).on("click", ".html2md-view" + suffix, function () {
  1140. var target, removedChildren = $();
  1141. if (type === "this_level") {
  1142. target = $(".html2md-view" + suffix).parent().next().get(0);
  1143. } else if (type === "child_level") {
  1144. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1145. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1146. }
  1147. if (target.viewmd) {
  1148. target.viewmd = false;
  1149. $(this).text("MarkDown视图");
  1150. $(this).removeClass("mdViewed");
  1151. $(target).html(target.original_html);
  1152. } else {
  1153. target.viewmd = true;
  1154. if (!target.original_html) {
  1155. target.original_html = $(target).html();
  1156. }
  1157. if (!target.markdown) {
  1158. target.markdown = turndownService.turndown($(target).html());
  1159. }
  1160. $(this).text("原始内容");
  1161. $(this).addClass("mdViewed");
  1162. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1163. }
  1164. // 恢复删除的元素
  1165. if (removedChildren) $(target).prepend(removedChildren);
  1166. });
  1167. }
  1168.  
  1169. function addButtonWithHTML2MD(parent, suffix, type) {
  1170. $(document).on("click", ".html2md-view" + suffix, debounce(function () {
  1171. var target, removedChildren = $();
  1172. if (type === "this_level") {
  1173. target = $(".html2md-view" + suffix).parent().next().get(0);
  1174. } else if (type === "child_level") {
  1175. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1176. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1177. }
  1178. if (target.viewmd) {
  1179. target.viewmd = false;
  1180. $(this).text("MarkDown视图");
  1181. $(this).removeClass("mdViewed");
  1182. $(target).html(target.original_html);
  1183. } else {
  1184. target.viewmd = true;
  1185. if (!target.original_html) {
  1186. target.original_html = $(target).html();
  1187. }
  1188. if (!target.markdown) {
  1189. target.markdown = turndownService.turndown($(target).html());
  1190. }
  1191. $(this).text("原始内容");
  1192. $(this).addClass("mdViewed");
  1193. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1194. }
  1195. // 恢复删除的元素
  1196. if (removedChildren) $(target).prepend(removedChildren);
  1197. }));
  1198.  
  1199. if (hoverTargetAreaDisplay) {
  1200. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  1201. var target;
  1202.  
  1203. if (type === "this_level") {
  1204. target = $(".html2md-view" + suffix).parent().next().get(0);
  1205. } else if (type === "child_level") {
  1206. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1207. }
  1208.  
  1209. $(target).append('<div class="overlay">目标转换区域</div>');
  1210. $(target).css({
  1211. "position": "relative",
  1212. "display": "block"
  1213. });
  1214. $(".html2md-view" + suffix).parent().css({
  1215. "position": "relative",
  1216. "z-index": "99999"
  1217. })
  1218. });
  1219.  
  1220. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  1221. var target;
  1222.  
  1223. if (type === "this_level") {
  1224. target = $(".html2md-view" + suffix).parent().next().get(0);
  1225. } else if (type === "child_level") {
  1226. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1227. }
  1228.  
  1229. $(target).find('.overlay').remove();
  1230. $(target).css({
  1231. "position": "",
  1232. "display": ""
  1233. });
  1234. $(".html2md-view" + suffix).parent().css({
  1235. "position": "static"
  1236. })
  1237. });
  1238. }
  1239. }
  1240.  
  1241. function addButtonWithCopy(parent, suffix, type) {
  1242. $(document).on("click", ".html2md-cb" + suffix, debounce(function () {
  1243. var target, removedChildren;
  1244. if (type === "this_level") {
  1245. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  1246. } else if (type === "child_level") {
  1247. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  1248. $(target).children(':first').remove();
  1249. }
  1250. if ($(target).find('.mdViewContent').length <= 0) {
  1251. text = turndownService.turndown($(target).html());
  1252. } else {
  1253. text = $(target).find('.mdViewContent').text();
  1254. }
  1255. GM_setClipboard(text);
  1256. $(this).addClass("copied");
  1257. $(this).text("Copied");
  1258. // 更新复制按钮文本
  1259. setTimeout(() => {
  1260. $(this).removeClass("copied");
  1261. $(this).text("Copy");
  1262. }, 2000);
  1263. $(target).remove();
  1264. }));
  1265.  
  1266. if (hoverTargetAreaDisplay) {
  1267. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  1268. var target;
  1269.  
  1270. if (type === "this_level") {
  1271. target = $(".html2md-cb" + suffix).parent().next().get(0);
  1272. } else if (type === "child_level") {
  1273. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  1274. }
  1275.  
  1276. $(target).append('<div class="overlay">目标复制区域</div>');
  1277. $(target).css({
  1278. "position": "relative",
  1279. "display": "block"
  1280. });
  1281. $(".html2md-cb" + suffix).parent().css({
  1282. "position": "relative",
  1283. "z-index": "99999"
  1284. })
  1285. });
  1286.  
  1287. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  1288. var target;
  1289.  
  1290. if (type === "this_level") {
  1291. target = $(".html2md-cb" + suffix).parent().next().get(0);
  1292. } else if (type === "child_level") {
  1293. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  1294. }
  1295.  
  1296. $(target).find('.overlay').remove();
  1297. $(target).css({
  1298. "position": "",
  1299. "display": ""
  1300. });
  1301. $(".html2md-cb" + suffix).parent().css({
  1302. "position": "static"
  1303. })
  1304. });
  1305. }
  1306. }
  1307.  
  1308. async function addButtonWithTranslation(parent, suffix, type) {
  1309. var result;
  1310. $(document).on('click', '.translateButton' + suffix, debounce(async function () {
  1311. $(this).removeClass("translated");
  1312. $(this).text("翻译中");
  1313. $(this).css("cursor", "not-allowed");
  1314. $(this).trigger('mouseout');
  1315. $(this).prop("disabled", true);
  1316. var target, element_node, block, errerNum = 0, is_x_api2d_no_cache = false;
  1317. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  1318. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  1319.  
  1320. // 重新翻译
  1321. if (result) {
  1322. if (result.translateDiv) {
  1323. $(result.translateDiv).remove();
  1324. }
  1325. if (result.copyDiv) {
  1326. $(result.copyDiv).remove();
  1327. }
  1328. if (result.copyButton) {
  1329. $(result.copyButton).remove();
  1330. }
  1331. // 重新翻译时暂时关闭 x_api2d_no_cache
  1332. if (x_api2d_no_cache) {
  1333. x_api2d_no_cache = false;
  1334. is_x_api2d_no_cache = true;
  1335. }
  1336. // 移除旧的事件
  1337. $(document).off("mouseover", ".translateButton" + suffix);
  1338. $(document).off("mouseout", ".translateButton" + suffix);
  1339. // 重新绑定悬停事件
  1340. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  1341. }
  1342.  
  1343. // 分段翻译
  1344. if (enableSegmentedTranslation) {
  1345. var pElements = block.find("p, li");
  1346. for (let i = 0; i < pElements.length; i++) {
  1347. target = $(pElements[i]).eq(0).clone();
  1348. if (type === "child_level") $(target).children(':first').remove();
  1349. element_node = pElements[i];
  1350. if (type === "child_level") {
  1351. $(pElements[i]).append("<div></div>");
  1352. element_node = $(pElements[i]).find("div:last-child").get(0);
  1353. }
  1354. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1355. if (result.status) errerNum += 1;
  1356. $(target).remove();
  1357. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  1358. }
  1359. } else {
  1360. target = block.eq(0).clone();
  1361. if (type === "child_level") $(target).children(':first').remove();
  1362. element_node = $(block).get(0);
  1363. if (type === "child_level") {
  1364. $(parent).append("<div></div>");
  1365. element_node = $(parent).find("div:last-child").get(0);
  1366. }
  1367. //是否跳过折叠块
  1368. if ($(target).find('.spoiler').length > 0) {
  1369. const shouldSkip = await skiFoldingBlocks();
  1370. if (shouldSkip) {
  1371. $(target).find('.spoiler').remove();
  1372. } else {
  1373. $(target).find('.html2md-panel').remove();
  1374. }
  1375. }
  1376. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1377. if (result.status) errerNum += 1;
  1378. $(target).remove();
  1379. }
  1380. if (!errerNum) {
  1381. $(this).addClass("translated")
  1382. .text("已翻译")
  1383. .css("cursor", "pointer")
  1384. .removeClass("error")
  1385. .prop("disabled", false);
  1386. } else {
  1387. $(this).prop("disabled", false);
  1388. }
  1389.  
  1390. // 恢复x_api2d_no_cache设置
  1391. if (is_x_api2d_no_cache) x_api2d_no_cache = true;
  1392.  
  1393. // 重新翻译
  1394. let currentText, is_error;
  1395. $(document).on("mouseover", ".translateButton" + suffix, function () {
  1396. currentText = $(this).text();
  1397. $(this).text("重新翻译");
  1398. if ($(this).hasClass("error")) {
  1399. is_error = true;
  1400. $(this).removeClass("error");
  1401. }
  1402. });
  1403.  
  1404. $(document).on("mouseout", ".translateButton" + suffix, function () {
  1405. $(this).text(currentText);
  1406. if (is_error) $(this).addClass("error");
  1407. });
  1408. }));
  1409.  
  1410. // 目标区域指示
  1411. function bindHoverEvents(suffix, type) {
  1412. $(document).on("mouseover", ".translateButton" + suffix, function () {
  1413. var target;
  1414.  
  1415. if (type === "this_level") {
  1416. target = $(".translateButton" + suffix).parent().next().get(0);
  1417. } else if (type === "child_level") {
  1418. target = $(".translateButton" + suffix).parent().parent().get(0);
  1419. }
  1420.  
  1421. $(target).append('<div class="overlay">目标翻译区域</div>');
  1422. $(target).css({
  1423. "position": "relative",
  1424. "display": "block"
  1425. });
  1426. $(".translateButton" + suffix).parent().css({
  1427. "position": "relative",
  1428. "z-index": "99999"
  1429. });
  1430. });
  1431.  
  1432. $(document).on("mouseout", ".translateButton" + suffix, function () {
  1433. var target;
  1434.  
  1435. if (type === "this_level") {
  1436. target = $(".translateButton" + suffix).parent().next().get(0);
  1437. } else if (type === "child_level") {
  1438. target = $(".translateButton" + suffix).parent().parent().get(0);
  1439. }
  1440.  
  1441. $(target).find('.overlay').remove();
  1442. $(target).css({
  1443. "position": "",
  1444. "display": ""
  1445. });
  1446. $(".translateButton" + suffix).parent().css({
  1447. "position": "static"
  1448. });
  1449. });
  1450. }
  1451.  
  1452. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  1453. }
  1454.  
  1455. // 块处理
  1456. async function blockProcessing(target, element_node, button) {
  1457. if (!target.markdown) {
  1458. target.markdown = turndownService.turndown($(target).html());
  1459. }
  1460. const textarea = document.createElement('textarea');
  1461. textarea.value = target.markdown;
  1462. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  1463. //
  1464. if (result.status == 1) {
  1465. $(button).addClass("error")
  1466. .text("翻译中止")
  1467. .css("cursor", "pointer")
  1468. .prop("disabled", false);
  1469. $(result.translateDiv).remove();
  1470. $(target).remove();
  1471. } else if (result.status == 2) {
  1472. result.translateDiv.classList.add("error_translate");
  1473. $(button).addClass("error")
  1474. .text("翻译出错")
  1475. .css("cursor", "pointer")
  1476. .prop("disabled", false);
  1477. $(target).remove();
  1478. }
  1479. return result;
  1480. }
  1481.  
  1482. function addConversionButton() {
  1483. // 添加按钮到题目部分
  1484. $('.subject-question').each(function () {
  1485. let id = "_" + getRandomNumber(8);
  1486. addButtonPanel(this, id, "this_level");
  1487. addButtonWithHTML2MD(this, id, "this_level");
  1488. addButtonWithCopy(this, id, "this_level");
  1489. addButtonWithTranslation(this, id, "this_level");
  1490. });
  1491.  
  1492. // 添加按钮到question-oi-bd部分
  1493. $('.question-oi-bd').each(function () {
  1494. let id = "_question-oi-bd_" + getRandomNumber(8);
  1495. addButtonPanel(this, id, "this_level");
  1496. addButtonWithHTML2MD(this, id, "this_level");
  1497. addButtonWithCopy(this, id, "this_level");
  1498. addButtonWithTranslation(this, id, "this_level");
  1499. });
  1500.  
  1501. // 添加按钮到pre部分
  1502. var selectorList = ['.question-oi-bd', '.CodeMirror'];//排除有这些祖宗节点的pre
  1503. $('pre').each(function () {
  1504. for (var i = 0; i < selectorList.length; i++) {
  1505. if ($(this).closest(selectorList[i]).length > 0) {
  1506. return true;
  1507. }
  1508. }
  1509. let id = "_pre_" + getRandomNumber(8);
  1510. addButtonPanel(this, id, "this_level");
  1511. addButtonWithHTML2MD(this, id, "this_level");
  1512. addButtonWithCopy(this, id, "this_level");
  1513. addButtonWithTranslation(this, id, "this_level");
  1514. });
  1515.  
  1516. // 添加按钮到题解部分
  1517. $('div.nc-post-content').each(function () {
  1518. let id = "_nc-post-content_" + getRandomNumber(8);
  1519. addButtonPanel(this, id, "this_level");
  1520. addButtonWithHTML2MD(this, id, "this_level");
  1521. addButtonWithCopy(this, id, "this_level");
  1522. addButtonWithTranslation(this, id, "this_level");
  1523. });
  1524. // 监听展开按钮
  1525. $(document).on('click', '.more-unfold', function (event) {
  1526. var interval = setInterval(function () {
  1527. if ($("div.nc-post-content:not(div.html2md-panel + div.nc-post-content)").length > 0) {
  1528. $("div.nc-post-content:not(div.html2md-panel + div.nc-post-content)").each(function () {
  1529. let id = "_nc-post-content_" + getRandomNumber(8);
  1530. addButtonPanel(this, id, "this_level");
  1531. addButtonWithHTML2MD(this, id, "this_level");
  1532. addButtonWithCopy(this, id, "this_level");
  1533. addButtonWithTranslation(this, id, "this_level");
  1534. });
  1535. clearInterval(interval);
  1536. }
  1537. }, 1000);
  1538. });
  1539. };
  1540.  
  1541. $(document).ready(function () {
  1542. var tip_SegmentedTranslation = $("<div></div>")
  1543. .addClass("alert alert-danger")
  1544. .html(`
  1545. Nowcoder Better! —— 注意!分段翻译已开启,这会造成负面效果,
  1546. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>
  1547. `)
  1548. .css({
  1549. margin: "1em",
  1550. "text-align": "center",
  1551. "font-weight": "600",
  1552. position: "relative",
  1553. });
  1554.  
  1555. if (enableSegmentedTranslation)
  1556. $(".content-board").before(tip_SegmentedTranslation); //显示分段翻译警告
  1557.  
  1558. addConversionButton();
  1559. });
  1560.  
  1561. // 字数超限确认
  1562. function showWordsExceededDialog(button) {
  1563. return new Promise(resolve => {
  1564. const styleElement = GM_addStyle(darkenPageStyle);
  1565. $(button).removeClass("translated");
  1566. $(button).text("字数超限");
  1567. $(button).css("cursor", "not-allowed");
  1568. $(button).prop("disabled", true);
  1569. let htmlString = `
  1570. <div class="wordsExceeded">
  1571. <h3>字数超限!</h3>
  1572. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  1573. <div style="display:flex; padding:5px 0px; align-items: center;">
  1574. `+ helpCircleHTML + `
  1575. <p>
  1576. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  1577. <br>或者在设置面板中开启 分段翻译 后重试。
  1578. </p>
  1579. </div>
  1580. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  1581. <p>您确定要继续翻译吗?</p>
  1582. <div style="display:flex; padding-top:10px">
  1583. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  1584. </div>
  1585. </div>
  1586. `;
  1587. $('body').before(htmlString);
  1588. $("#continueButton").click(function () {
  1589. $(styleElement).remove();
  1590. $('.wordsExceeded').remove();
  1591. resolve(true);
  1592. });
  1593. $("#cancelButton").click(function () {
  1594. $(styleElement).remove();
  1595. $('.wordsExceeded').remove();
  1596. resolve(false);
  1597. });
  1598. });
  1599. }
  1600.  
  1601. // 跳过折叠块确认
  1602. function skiFoldingBlocks() {
  1603. return new Promise(resolve => {
  1604. const styleElement = GM_addStyle(darkenPageStyle);
  1605. let htmlString = `
  1606. <div class="wordsExceeded">
  1607. <h3>是否跳过折叠块?</h3>
  1608. <p></p>
  1609. <div style="display:grid; padding:5px 0px; align-items: center;">
  1610. <p>
  1611. 即将翻译的区域中包含折叠块,可能不需要翻译,现在您需要选择是否跳过这些折叠块,
  1612. </p>
  1613. <p>
  1614. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  1615. </p>
  1616. </div>
  1617. <p>要跳过折叠块吗?(建议选择跳过)</p>
  1618. <div style="display:flex; padding-top:10px">
  1619. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  1620. </div>
  1621. </div>
  1622. `;
  1623. $('body').before(htmlString);
  1624. $("#skipButton").click(function () {
  1625. $(styleElement).remove();
  1626. $('.wordsExceeded').remove();
  1627. resolve(true);
  1628. });
  1629. $("#cancelButton").click(function () {
  1630. $(styleElement).remove();
  1631. $('.wordsExceeded').remove();
  1632. resolve(false);
  1633. });
  1634. });
  1635. }
  1636.  
  1637. // 翻译框/翻译处理器
  1638. var translatedText = "";
  1639. async function translateProblemStatement(text, element_node, button) {
  1640. let status = 0;
  1641. let id = getRandomNumber(8);
  1642. let matches = [];
  1643. let replacements = {};
  1644. // 创建元素并放在element_node的后面
  1645. const translateDiv = document.createElement('div');
  1646. translateDiv.setAttribute('id', id);
  1647. translateDiv.classList.add('translate-problem-statement');
  1648. const spanElement = document.createElement('span');
  1649. translateDiv.appendChild(spanElement);
  1650. element_node.insertAdjacentElement('afterend', translateDiv);
  1651. // 替换latex公式
  1652. if (translation != "api2d" && translation != "openai") {
  1653. // 使用GPT翻译时不必替换latex公式
  1654. let i = 0;
  1655. // 块公式
  1656. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1657. try {
  1658. for (i; i < matches.length; i++) {
  1659. let match = matches[i];
  1660. text = text.replace(match, `【${i + 1}】`);
  1661. replacements[`【${i + 1}】`] = match;
  1662. }
  1663. } catch (e) { }
  1664. // 行内公式
  1665. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1666. try {
  1667. for (i; i < matches.length; i++) {
  1668. let match = matches[i];
  1669. text = text.replace(match, `【${i + 1}】`);
  1670. replacements[`【${i + 1}】`] = match;
  1671. }
  1672. } catch (e) { }
  1673. }
  1674. if (text.length > 4950) {
  1675. const shouldContinue = await showWordsExceededDialog(button);
  1676. if (!shouldContinue) {
  1677. status = 1;
  1678. return {
  1679. translateDiv: translateDiv,
  1680. status: status
  1681. };
  1682. }
  1683. }
  1684. // 翻译
  1685. if (translation == "deepl") {
  1686. translateDiv.innerHTML = "正在翻译中……请稍等";
  1687. translatedText = await translate_deepl(text);
  1688. } else if (translation == "youdao") {
  1689. translateDiv.innerHTML = "正在翻译中……请稍等";
  1690. translatedText = await translate_youdao_mobile(text);
  1691. } else if (translation == "google") {
  1692. translateDiv.innerHTML = "正在翻译中……请稍等";
  1693. translatedText = await translate_gg(text);
  1694. } else if (translation == "openai") {
  1695. try {
  1696. translateDiv.innerHTML = "正在翻译中……<br><br>使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1697. translatedText = await translate_openai(text);
  1698. } catch (error) {
  1699. status = 2;
  1700. translatedText = error;
  1701. }
  1702. } else if (translation == "api2d") {
  1703. try {
  1704. translateDiv.innerHTML = "正在翻译中……<br><br>使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1705. translatedText = await translate_api2d(text);
  1706. } catch (error) {
  1707. status = 2;
  1708. translatedText = error;
  1709. }
  1710. }
  1711. if (/^翻译出错/.test(translatedText)) status = 2;
  1712. // 还原latex公式
  1713. if (translation != "api2d" && translation != "openai") {
  1714. try {
  1715. for (let i = 0; i < matches.length; i++) {
  1716. let match = matches[i];
  1717. let replacement = replacements[`【${i + 1}】`];
  1718. let regex;
  1719. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  1720. translatedText = translatedText.replace(regex, replacement);
  1721. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  1722. translatedText = translatedText.replace(regex, replacement);
  1723. regex = new RegExp(`【\\s*${i + 1}[^】\\d]`, 'g');
  1724. translatedText = translatedText.replace(regex, replacement);
  1725. regex = new RegExp(`[^【\\d]${i + 1}\\s*】`, 'g');
  1726. translatedText = translatedText.replace(regex, " " + replacement);
  1727. }
  1728. } catch (e) { }
  1729. }
  1730.  
  1731. // 创建一个隐藏的元素来保存 translatedText 的值
  1732. var textElement = document.createElement("div");
  1733. textElement.style.display = "none";
  1734. textElement.textContent = translatedText;
  1735. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  1736.  
  1737. // 翻译复制按钮
  1738. var copyButton = document.createElement("button");
  1739. copyButton.textContent = "Copy";
  1740. var wrapperDiv = document.createElement("div");
  1741. $(wrapperDiv).css({
  1742. display: "flex",
  1743. justifyContent: "flex-end"
  1744. });
  1745. $(wrapperDiv).append(copyButton);
  1746. $(copyButton).addClass("html2mdButton html2md-cb");
  1747.  
  1748. copyButton.addEventListener("click", function () {
  1749. var translatedText = textElement.textContent;
  1750. GM_setClipboard(translatedText);
  1751. $(this).addClass("copied").text("Copied");
  1752. // 更新复制按钮文本
  1753. setTimeout(() => {
  1754. $(this).removeClass("copied");
  1755. $(this).text("Copy");
  1756. }, 2000);
  1757. });
  1758. translateDiv.parentNode.insertBefore(wrapperDiv, translateDiv);
  1759.  
  1760. // 转义LaTex中的特殊符号
  1761. const escapeRules = [
  1762. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  1763. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  1764. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  1765. { pattern: /(?<!\\)& /g, replacement: "\\&" }, // &符号
  1766. ];
  1767.  
  1768. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$/g)];
  1769.  
  1770. for (const match of latexMatches) {
  1771. const matchedText = match[0];
  1772.  
  1773. for (const rule of escapeRules) {
  1774. const escapedText = matchedText.replaceAll(rule.pattern, rule.replacement);
  1775. translatedText = translatedText.replace(matchedText, escapedText);
  1776. }
  1777. }
  1778.  
  1779. // 渲染MarkDown
  1780. var md = window.markdownit();
  1781. var html = md.render(translatedText);
  1782. translateDiv.innerHTML = html;
  1783. // 渲染Latex
  1784. if (typeof renderMathInElement === 'function') {
  1785. renderMathInElement(translateDiv, {
  1786. delimiters: [{
  1787. left: "$$",
  1788. right: "$$",
  1789. display: true
  1790. }, {
  1791. left: "$",
  1792. right: "$",
  1793. display: false
  1794. }]
  1795. });
  1796. }
  1797. return {
  1798. translateDiv: translateDiv,
  1799. status: status,
  1800. copyDiv: textElement,
  1801. copyButton: copyButton
  1802. };
  1803.  
  1804. }
  1805.  
  1806. // ChatGPT
  1807. async function translate_openai(raw) {
  1808. var openai_key = GM_getValue("openai_key");
  1809. var openai_retext = "";
  1810. var data = {
  1811. model: openai_model,
  1812. messages: [{
  1813. role: "user",
  1814. content: "(请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")"
  1815. }],
  1816. temperature: 0.7
  1817. };
  1818. return new Promise(function (resolve, reject) {
  1819. GM_xmlhttpRequest({
  1820. method: 'POST',
  1821. url: (showOpneAiAdvanced && GM_getValue("openai_proxy") !== null && GM_getValue("openai_proxy") !== "") ? GM_getValue("openai_proxy") : 'https://api.openai.com/v1/chat/completions', // Use the chat endpoint here
  1822.  
  1823. data: JSON.stringify(data),
  1824. headers: {
  1825. 'Content-Type': 'application/json',
  1826. 'Authorization': 'Bearer ' + GM_getValue("openai_key")
  1827. },
  1828. responseType: 'json',
  1829. onload: function (response) {
  1830. if (!response.response) {
  1831. reject("发生了未知的错误,如果你启用了代理API,请确认是否填写正确,并确保代理能够正常工作。\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  1832. }
  1833. else if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  1834. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, ''));
  1835. } else {
  1836. openai_retext = response.response.choices[0].message.content;
  1837. resolve(openai_retext);
  1838. }
  1839. },
  1840. onerror: function (response) {
  1841. reject("发生了未知的错误,请确认你是否能正常访问OpenAi的接口,如果使用代理API,请检查是否正常工作\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  1842. },
  1843. });
  1844.  
  1845. });
  1846. }
  1847.  
  1848. // api2d
  1849. async function translate_api2d(raw) {
  1850. var api2d_key = GM_getValue("api2d_key");
  1851. var api2d_retext = "";
  1852. var postData = JSON.stringify({
  1853. model: api2d_model,
  1854. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1855. temperature: 0.7
  1856. });
  1857. const options = {
  1858. method: 'POST',
  1859. headers: {
  1860. 'Content-Type': 'application/json',
  1861. 'Authorization': 'Bearer ' + api2d_key,
  1862. ...(x_api2d_no_cache ? {} : { 'x-api2d-no-cache': 1 })
  1863. },
  1864. data: postData,
  1865. };
  1866.  
  1867. return new Promise(function (resolve, reject) {
  1868. GM_xmlhttpRequest({
  1869. method: options.method,
  1870. url: api2d_request_entry + `/v1/chat/completions`,
  1871. headers: options.headers,
  1872. data: options.data,
  1873. responseType: 'json',
  1874. onload: function (response) {
  1875. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  1876. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  1877. } else {
  1878. api2d_retext = response.response.choices[0].message.content;
  1879. resolve(api2d_retext);
  1880. }
  1881. },
  1882. onerror: function (response) {
  1883. reject("发生了未知的错误,请检查请求入口地址是否正确,能否正常访问\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  1884. },
  1885. });
  1886. });
  1887.  
  1888.  
  1889. }
  1890. //
  1891.  
  1892. //--谷歌翻译--start
  1893. async function translate_gg(raw) {
  1894. return new Promise((resolve, reject) => {
  1895. const url = 'https://translate.google.com/m';
  1896. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  1897.  
  1898. GM_xmlhttpRequest({
  1899. method: 'GET',
  1900. url: `${url}?${params}`,
  1901. onload: function (response) {
  1902. const html = response.responseText;
  1903. const translatedText = $(html).find('.result-container').text();
  1904. resolve(translatedText);
  1905. },
  1906. onerror: function (error) {
  1907. console.error('Error:', error);
  1908. reject(error);
  1909. }
  1910. });
  1911. });
  1912. }
  1913. //--谷歌翻译--end
  1914.  
  1915. //--有道翻译m--start
  1916. async function translate_youdao_mobile(raw) {
  1917. const options = {
  1918. method: "POST",
  1919. url: 'http://m.youdao.com/translate',
  1920. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1921. anonymous: true,
  1922. headers: {
  1923. "Content-Type": "application/x-www-form-urlencoded",
  1924. 'Host': 'm.youdao.com',
  1925. 'Origin': 'http://m.youdao.com',
  1926. 'Referer': 'http://m.youdao.com/translate',
  1927. }
  1928. }
  1929. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1930. }
  1931. //--有道翻译m--end
  1932.  
  1933. //--Deepl翻译--start
  1934. function getTimeStamp(iCount) {
  1935. const ts = Date.now();
  1936. if (iCount !== 0) {
  1937. iCount = iCount + 1;
  1938. return ts - (ts % iCount) + iCount;
  1939. } else {
  1940. return ts;
  1941. }
  1942. }
  1943.  
  1944. async function translate_deepl(raw) {
  1945. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1946. const data = {
  1947. jsonrpc: '2.0',
  1948. method: 'LMT_handle_texts',
  1949. id,
  1950. params: {
  1951. splitting: 'newlines',
  1952. lang: {
  1953. source_lang_user_selected: 'auto',
  1954. target_lang: 'ZH',
  1955. },
  1956. texts: [{
  1957. text: raw,
  1958. requestAlternatives: 3
  1959. }],
  1960. timestamp: getTimeStamp(raw.split('i').length - 1)
  1961. }
  1962. }
  1963. let postData = JSON.stringify(data);
  1964. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1965. postData = postData.replace('"method":"', '"method" : "');
  1966. } else {
  1967. postData = postData.replace('"method":"', '"method": "');
  1968. }
  1969. const options = {
  1970. method: 'POST',
  1971. url: 'https://www2.deepl.com/jsonrpc',
  1972. data: postData,
  1973. headers: {
  1974. 'Content-Type': 'application/json',
  1975. 'Host': 'www2.deepl.com',
  1976. 'Origin': 'https://www.deepl.com',
  1977. 'Referer': 'https://www.deepl.com/',
  1978. },
  1979. anonymous: true,
  1980. nocache: true,
  1981. }
  1982. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1983. }
  1984.  
  1985. //--Deepl翻译--end
  1986.  
  1987. //--异步请求包装工具--start
  1988. async function PromiseRetryWrap(task, options, ...values) {
  1989. const { RetryTimes, ErrProcesser } = options || {};
  1990. let retryTimes = RetryTimes || 5;
  1991. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1992. if (!task) return;
  1993. while (true) {
  1994. try {
  1995. return await task(...values);
  1996. } catch (err) {
  1997. if (!--retryTimes) {
  1998. console.log(err);
  1999. return usedErrProcesser(err);
  2000. }
  2001. }
  2002. }
  2003. }
  2004.  
  2005. async function BaseTranslate(name, raw, options, processer) {
  2006. let errtext;
  2007. const toDo = async () => {
  2008. var tmp;
  2009. try {
  2010. const data = await Request(options);
  2011. tmp = data.responseText;
  2012. const result = await processer(tmp);
  2013. if (result) sessionStorage.setItem(name + '-' + raw, result);
  2014. return result
  2015. } catch (err) {
  2016. errtext = tmp;
  2017. throw {
  2018. responseText: tmp,
  2019. err: err
  2020. }
  2021. }
  2022. }
  2023. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈 请注意打码报错信息的敏感部分\n\n报错信息:" + errtext })
  2024. }
  2025.  
  2026.  
  2027. function Request(options) {
  2028. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  2029. }
  2030.  
  2031. //--异步请求包装工具--end