Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目

当前为 2023-05-16 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.21
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect openai.api2d.net
  11. // @connect api.openai.com
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_info
  14. // @connect greasyfork.org
  15. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  16. // @require https://cdn.bootcdn.net/ajax/libs/turndown/7.1.1/turndown.min.js
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js
  18. // @license MIT
  19. // ==/UserScript==
  20. // 样式
  21. function loadCssCode(code){
  22. var style = document.createElement('style');
  23. style.type = 'text/css';
  24. style.rel = 'stylesheet';
  25. style.appendChild(document.createTextNode(code));
  26. var head = document.getElementsByTagName('head')[0];
  27. head.appendChild(style);
  28. }
  29. loadCssCode(`
  30. span.mdViewContent {
  31. white-space: pre-wrap;
  32. }
  33. /*翻译div*/
  34. .translate-problem-statement {
  35. display: grid;
  36. justify-items: start;
  37. white-space: pre-wrap;
  38. border: 1px dashed #00aeeccc;
  39. border-radius: 0.3rem;
  40. padding: 5px;
  41. margin: 10px 0px;
  42. font-size: 13px;
  43. }
  44. .translate-problem-statement a {
  45. color: #4d87c7;
  46. background: 0 0;
  47. text-decoration: none;
  48. }
  49. .translate-problem-statement a:hover {
  50. background-color: #800;
  51. color: #fff;
  52. text-decoration: none;
  53. }
  54. .html2md-panel {
  55. display: flex;
  56. justify-content: flex-end;
  57. }
  58. button.html2mdButton {
  59. cursor: pointer;
  60. background-color: #e6e6e6;
  61. color: #727378;
  62. height: 22px;
  63. width: auto;
  64. font-size: 13px;
  65. border-radius: 0.3rem;
  66. border: none;
  67. padding: 1px 5px;
  68. margin: 5px;
  69. box-shadow: 0 0 1px #0000004d;
  70. }
  71. button.html2mdButton.copied {
  72. background-color: #07e65196;
  73. color: #104f2b;
  74. }
  75. button.html2mdButton.mdViewed {
  76. background-color: #ff980057;
  77. color: #5a3a0c;
  78. }
  79. button.translated {
  80. cursor: not-allowed;
  81. background-color: #2a6dc296;
  82. color: #fffdfd;
  83. }
  84. .translate-problem-statement table {
  85. border: 1px #ccc solid;
  86. border-collapse: collapse;
  87. margin: 1.3571em 0 0;
  88. color: #222;
  89. }
  90. .translate-problem-statement table td {
  91. border-right: 1px solid #ccc;
  92. border-top: 1px solid #ccc;
  93. padding: 0.7143em 0.5em;
  94. }
  95. .translate-problem-statement table th {
  96. padding: 0.7143em 0.5em;
  97. }
  98. .translate-problem-statement p:not(:first-child) {
  99. margin: 1.5em 0 0;
  100. }
  101. /*设置面板*/
  102. button.html2mdButton.CFBetter_setting {
  103. float: right;
  104. height: 30px;
  105. background: #60a5fa;
  106. color: white;
  107. box-shadow: 0px 0px 1px 1px #0000004d;
  108. margin: 10px;
  109. }
  110. #CFBetter_setting_menu {
  111. z-index: 9999;
  112. border-radius: 0.5rem;
  113. box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  114. display: grid;
  115. position: fixed;
  116. top: 50%;
  117. left: 50%;
  118. width: 270px;
  119. transform: translate(-50%, -50%);
  120. border-radius: 16px;
  121. background-color: #ecf0ff;
  122. border: 6px solid #ffffff;
  123. color: #697e91;
  124. padding: 10px 20px 20px 20px;
  125. }
  126.  
  127. /*设置面板-关闭按钮*/
  128. #CFBetter_setting_menu .tool-box {
  129. position: absolute;
  130. display: flex;
  131. align-items: center;
  132. justify-content: center;
  133. width: 2.5rem;
  134. height: 2.5rem;
  135. top: 3px;
  136. right: 3px;
  137. }
  138.  
  139. #CFBetter_setting_menu .btn-close {
  140. display: flex;
  141. align-items: center;
  142. justify-content: center;
  143. text-align: center;
  144. width: 2rem;
  145. height: 2rem;
  146. color: transparent;
  147. font-size: 0;
  148. cursor: pointer;
  149. background-color: #ff000080;
  150. border: none;
  151. border-radius: 10px;
  152. transition: .2s ease all;
  153. }
  154.  
  155. #CFBetter_setting_menu .btn-close:hover {
  156. width: 2rem;
  157. height: 2rem;
  158. font-size: 1rem;
  159. color: #ffffff;
  160. background-color: #ff0000cc;
  161. box-shadow: 0 5px 5px 0 #00000026;
  162. }
  163.  
  164. #CFBetter_setting_menu .btn-close:active {
  165. width: .9rem;
  166. height: .9rem;
  167. font-size: .9rem;
  168. color: #ffffffde;
  169. --shadow-btn-close: 0 3px 3px 0 #00000026;
  170. box-shadow: var(--shadow-btn-close);
  171. }
  172.  
  173. /*设置面板-checkbox*/
  174. #CFBetter_setting_menu input[type=checkbox]:focus {
  175. outline: 0px;
  176. }
  177.  
  178. #CFBetter_setting_menu input[type="checkbox"] {
  179. margin: 0px;
  180. appearance: none;
  181. width: 48px;
  182. height: 24px;
  183. border: 2px solid #6b8092;
  184. border-radius: 20px;
  185. background: #f1e1e1;
  186. position: relative;
  187. box-sizing: border-box;
  188. }
  189.  
  190. #CFBetter_setting_menu input[type="checkbox"]::before {
  191. content: "";
  192. width: 16px;
  193. height: 16px;
  194. background: #6b80927a;
  195. border: 2px solid #6b8092;
  196. border-radius: 50%;
  197. position: absolute;
  198. top: 0;
  199. left: 0;
  200. transform: translate(0%, 0%);
  201. transition: all 0.3s ease-in-out;
  202. }
  203.  
  204. #CFBetter_setting_menu input[type="checkbox"]::after {
  205. 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");
  206. position: absolute;
  207. top: 0;
  208. left: 24px;
  209. }
  210.  
  211. #CFBetter_setting_menu input[type="checkbox"]:checked {
  212. border: 2px solid #02c202;
  213. background: #e2f1e1;
  214. }
  215.  
  216. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  217. background: rgba(2, 194, 2, 0.5);
  218. border: 2px solid #02c202;
  219. transform: translate(119%, 0%);
  220. transition: all 0.3s ease-in-out;
  221. }
  222.  
  223. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  224. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='13' 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='%2302C202' fill-opacity='0.9'/%3E%3C/svg%3E");
  225. position: absolute;
  226. top: 3px;
  227. left: 4px;
  228. }
  229.  
  230. #CFBetter_setting_menu input[type="checkbox"] + label {
  231. margin: 0px 0px 0px 10px !important;
  232. font-size: 16px;
  233. }
  234.  
  235. .CFBetter_setting_list {
  236. display: flex;
  237. align-items: center;
  238. margin-bottom: 18px;
  239. }
  240.  
  241. /*设置面板-radio*/
  242. #CFBetter_setting_menu>label {
  243. display: flex;
  244. list-style-type: none;
  245. padding-inline-start: 0px;
  246. overflow-x: auto;
  247. max-width: 100%;
  248. margin: 0px;
  249. align-items: center;
  250. margin: 3px 0px;
  251. }
  252.  
  253. .CFBetter_setting_menu_label_text {
  254. border: 1px dashed #00aeeccc;
  255. display: block;
  256. height: 20px;
  257. width: 100%;
  258. color: gray;
  259. font-weight: 300;
  260. font-size: 14px;
  261. letter-spacing: 2px;
  262. padding: 7px;
  263. }
  264.  
  265. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  266. background: #41e49930;
  267. border: 1px solid green;
  268. color: green;
  269. font-weight: 500;
  270. }
  271.  
  272. #CFBetter_setting_menu>label input[type="radio"] {
  273. -webkit-appearance: none;
  274. appearance: none;
  275. list-style: none;
  276. margin: 0px;
  277. }
  278.  
  279. #CFBetter_setting_menu input[type="text"] {
  280. display: block;
  281. height: 25px;
  282. background-color: #ffffff;
  283. color: #727378;
  284. font-size: 10px;
  285. border-radius: 0.3rem;
  286. padding: 1px 5px;
  287. margin: 5px 0px 5px 0px;
  288. border: 1px solid #00aeeccc;
  289. box-shadow: 0 0 1px #0000004d;
  290. }
  291.  
  292. .CFBetter_setting_menu_input {
  293. width: 100%;
  294. display: grid;
  295. justify-content: start;
  296. }
  297.  
  298. #CFBetter_setting_menu #save {
  299. cursor: pointer;
  300. display: inline-flex;
  301. padding: 0.5rem 1rem;
  302. background-color: #1aa06d;
  303. color: #ffffff;
  304. font-size: 1rem;
  305. line-height: 1.5rem;
  306. font-weight: 500;
  307. justify-content: center;
  308. width: 100%;
  309. border-radius: 0.375rem;
  310. border: none;
  311. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  312. }
  313.  
  314. #CFBetter_setting_menu span.tip {
  315. color: red;
  316. font-size: 2px;
  317. font-weight: 500;
  318. padding: 0px 0px 10px 0px;
  319. }
  320. /*更新检查*/
  321. div#update_panel {
  322. position: fixed;
  323. top: 50%;
  324. left: 50%;
  325. width: 240px;
  326. transform: translate(-50%, -50%);
  327. background-color: #fdfdfd;
  328. border: 1px solid #00aeeccc;
  329. border-radius: 5px;
  330. box-shadow: 2px 2px 3px 1px #0000004d;
  331. padding: 10px 20px 20px 20px;
  332. color: #444242;
  333. background-color: #ecf0ff;
  334. border: 6px solid #ffffff;
  335. border-radius: 16px;
  336. }
  337. div#update_panel #updating {
  338. cursor: pointer;
  339. display: inline-flex;
  340. padding: 0px;
  341. background-color: #1aa06d;
  342. color: #ffffff;
  343. font-size: 1rem;
  344. line-height: 1.5rem;
  345. font-weight: 500;
  346. justify-content: center;
  347. width: 100%;
  348. border-radius: 0.375rem;
  349. border: none;
  350. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  351. }
  352. div#update_panel #updating a {
  353. text-decoration: none;
  354. color: white;
  355. display: flex;
  356. position: inherit;
  357. top: 0;
  358. left: 0;
  359. width: 100%;
  360. height: 22px;
  361. font-size: 14px;
  362. justify-content: center;
  363. align-items: center;
  364. }
  365. `);
  366.  
  367. // 更新检查
  368. (function checkScriptVersion() {
  369. function compareVersions(version1 = "0", version2 = "0") {
  370. const v1Array = String(version1).split(".");
  371. const v2Array = String(version2).split(".");
  372. const minLength = Math.min(v1Array.length, v2Array.length);
  373. let result = 0;
  374. for (let i = 0; i < minLength; i++) {
  375. const curV1 = Number(v1Array[i]);
  376. const curV2 = Number(v2Array[i]);
  377. if (curV1 > curV2) {
  378. result = 1;
  379. break;
  380. } else if (curV1 < curV2) {
  381. result = -1;
  382. break;
  383. }
  384. }
  385. if (result === 0 && v1Array.length !== v2Array.length) {
  386. const v1IsBigger = v1Array.length > v2Array.length;
  387. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  388. for (let i = minLength; i < maxLenArray.length; i++) {
  389. const curVersion = Number(maxLenArray[i]);
  390. if (curVersion > 0) {
  391. v1IsBigger ? result = 1 : result = -1;
  392. break;
  393. }
  394. }
  395. }
  396. return result;
  397. }
  398.  
  399. GM_xmlhttpRequest({
  400. method: "GET",
  401. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  402. timeout: 10 * 1e3,
  403. onload: function(response) {
  404. const scriptData = JSON.parse(response.responseText);
  405. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  406. $("body").append(`
  407. <div id='update_panel'>
  408. <h3>${GM_info.script.name}有新版本!</h3>
  409. <hr>
  410. <div class='update_panel_menu'>
  411. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  412. </div>
  413. <br>
  414. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  415. </div>
  416. `);
  417. }
  418. }
  419. });
  420. })();
  421.  
  422. // 汉化替换
  423. (function() {
  424. if(getCookie("bottomZh_CN")=== '') setCookie("bottomZh_CN", "true", 3650);
  425. if(getCookie("bottomZh_CN") != "true")return;
  426. // 设置语言为zh
  427. var htmlTag = document.getElementsByTagName("html")[0];
  428. htmlTag.setAttribute("lang", "zh-CN");
  429.  
  430. // 暴力html替换
  431. const classData = {
  432. '.menu-list.main-menu-list': [
  433. { match: 'Help', replace: '帮助' },
  434. { match: 'Calendar', replace: '日历' },
  435. { match: 'Edu', replace: '培训' },
  436. { match: 'Rating', replace: '积分榜' },
  437. { match: 'Groups', replace: '团体' },
  438. { match: 'Problemset', replace: '题单' },
  439. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  440. { match: 'Contests', replace: '比赛' },
  441. { match: 'Catalog', replace: '指南目录' },
  442. { match: 'Top', replace: '热门' },
  443. { match: 'Home', replace: '主页' },
  444. ],
  445. '.personal-sidebar ': [
  446. { match: 'Contribution', replace: '贡献' },
  447. { match: 'Settings', replace: '设置' },
  448. { match: 'Blog', replace: '博客' },
  449. { match: 'Teams', replace: '队伍' },
  450. { match: 'Submissions', replace: '提交' },
  451. { match: 'Talks', replace: '私信' },
  452. { match: 'Contests', replace: '比赛' },
  453. ],
  454. '.contest-state-phase': [
  455. { match: 'Before contest', replace: '即将进行的比赛' },
  456. ],
  457. '.notice': [
  458. { match: 'has extra registration', replace: '有额外的报名时期' },
  459. { match: 'If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes.', replace: '如果您在比赛开始前5分钟前还未报名,您可以在额外的报名期间稍后报名。额外的报名将在比赛开始后10分钟开放,并持续25分钟。' },
  460. ],
  461. '.act-item': [
  462. { match: 'Add to favourites', replace: '添加到收藏' },
  463. { match: 'Submit', replace: '提交' },
  464. ],
  465. '.datatable': [
  466. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  467. { match: 'Enter', replace: '进入' },
  468. { match: 'Final standings', replace: '榜单' },
  469. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  470. { match: 'Official School Contest', replace: '学校官方比赛' },
  471. { match: 'Training Contest', replace: '训练赛' },
  472. { match: 'Training Camp Contest', replace: '训练营比赛' },
  473. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  474. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  475. { match: 'China', replace: '中国' },
  476. { match: 'Statements', replace: '题目描述' },
  477. { match: 'in Chinese', replace: '中文' },
  478. { match: 'Trainings', replace: '训练' },
  479. { match: 'Prepared by', replace: '编写人' },
  480. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  481. { match: 'Past contests', replace: '过去的比赛' },
  482. { match: 'Exclusions', replace: '排除' },
  483. { match: 'Before start', replace: '还有' },
  484. { match: 'Before registration', replace: '报名还有' },
  485. { match: 'Until closing ', replace: '结束报名' },
  486. { match: 'Register', replace: '报名' },
  487. { match: 'Registration completed', replace: '已报名' },
  488. { match: 'Questions about problems', replace: '关于题目的提问' },
  489. ],
  490. '.ask-question-link': [
  491. { match: 'Ask a question', replace: '提一个问题' },
  492. ],
  493. '.contests-table': [
  494. { match: 'Contest history', replace: '比赛历史' },
  495. ],
  496. '.roundbox.sidebox.borderTopRound ': [
  497. { match: 'Register now', replace: '现在报名' },
  498. ],
  499. '.icon-eye-close.icon-large': [
  500. { match: 'Add to exclusions', replace: '添加到排除列表' },
  501. ],
  502. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  503. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  504. ],
  505. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  506. { match: 'Announcement', replace: '公告' },
  507. { match: 'Statements', replace: '统计报表' },
  508. { match: 'Tutorial', replace: '题解' },
  509. ],
  510. '.second-level-menu ': [
  511. { match: 'Problems', replace: '问题' },
  512. { match: 'Submit Code', replace: '提交代码' },
  513. { match: 'My Submissions', replace: '我的提交' },
  514. { match: 'Status', replace: '状态' },
  515. { match: 'Standings', replace: '榜单' },
  516. { match: 'Custom Invocation', replace: '自定义调试' },
  517. { match: 'Common standings', replace: '全部排行' },
  518. { match: 'Friends standings', replace: '只看朋友' },
  519. { match: 'Submit', replace: '提交' },
  520. { match: 'Custom test', replace: '自定义测试' },
  521. { match: 'Blog', replace: '博客' },
  522. { match: 'Teams', replace: '队伍' },
  523. { match: 'Submissions', replace: '提交' },
  524. { match: 'Groups', replace: '团体' },
  525. { match: 'Contests', replace: '比赛' },
  526. { match: '问题etting', replace: '参与编写的问题' },
  527. { match: 'Gym', replace: '训练营' },
  528. { match: 'Mashups', replace: '组合混搭' },
  529. { match: 'Posts', replace: '帖子' },
  530. { match: '>Comments<', replace: '>回复<' },
  531. { match: 'Main', replace: '主要' },
  532. { match: 'Settings', replace: '设置' },
  533. { match: 'Lists', replace: '列表' },
  534. ],
  535. '.topic-toggle-collapse': [
  536. { match: 'Expand', replace: '展开' },
  537. ],
  538. '.topic-read-more': [
  539. { match: 'Full text and comments', replace: '阅读全文/评论' },
  540. ],
  541. '.toggleEditorCheckboxLabel': [
  542. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  543. ],
  544. '.content-with-sidebar': [
  545. { match: 'Notice', replace: '注意' },
  546. { match: 'virtual participation', replace: '虚拟参与' },
  547. { match: 'Registration for the contest', replace: '比赛报名' },
  548. { match: 'Terms of agreement', replace: '协议条款' },
  549. { match: 'Take part', replace: '参与' },
  550. { match: 'as individual participant', replace: '作为个人参与者' },
  551. { match: 'as a team member', replace: '作为团队成员' },
  552. { match: 'Virtual start time', replace: '虚拟开始时间' },
  553. { match: 'Complete problemset', replace: '完整的问题集' },
  554. ],
  555. '.submit': [
  556. { match: 'Registration for the contest', replace: '比赛报名' },
  557. ],
  558. '.table-form': [
  559. { match: 'Problem', replace: '题目' },
  560. { match: 'Language', replace: '语言' },
  561. { match: 'Source code', replace: '源代码' },
  562. { match: 'Or choose file', replace: '或者选择文件' },
  563. { match: 'Choose file', replace: '选择文件' },
  564. ],
  565. };
  566. for (const className in classData) {
  567. const elements = document.querySelectorAll(className);
  568. elements.forEach((element) => {
  569. let html = element.outerHTML;
  570. const parent = element.parentNode;
  571. const childIndex = Array.from(parent.children).indexOf(element);
  572. let matched = false;
  573. classData[className].forEach((rule) => {
  574. if (html.match(new RegExp(rule.match, 'g'))) {
  575. matched = true;
  576. html = html.replace(new RegExp(rule.match, 'g'), rule.replace);
  577. const temp = document.createElement('div');
  578. temp.innerHTML = html.trim();
  579. const newElement = element.cloneNode(true);
  580. newElement.innerHTML = temp.firstChild.innerHTML;
  581. parent.replaceChild(newElement, parent.children[childIndex]);
  582. }
  583. });
  584. });
  585. }
  586.  
  587. // 元素选择替换
  588. // 侧栏titled汉化
  589. (function () {
  590. var translations = {
  591. "Pay attention": "→ 注意",
  592. "Top rated": "→ 积分排行",
  593. "Top contributors": "→ 贡献者排行",
  594. "Find user": "→ 查找用户",
  595. "Recent actions": "→ 最近热帖",
  596. "Training filter": "→ 过滤筛选",
  597. "Find training": "→ 搜索比赛/问题",
  598. "Virtual participation": "→ 什么是虚拟参赛",
  599. "Contest materials": "→ 比赛相关资料",
  600. "Settings": "→ 设置",
  601. "Clone Contest to Mashup": "→ Clone比赛到组合混搭",
  602. "Submit": "→ 提交",
  603. "Practice": "→ 练习",
  604. "Problem tags": "→ 问题标签",
  605. "Filter Problems": "→ 过滤问题",
  606. "Attention": "→ 注意",
  607. "About Contest": "→ 关于比赛",
  608. };
  609.  
  610. $(".caption.titled").each(function() {
  611. var tag = $(this).text();
  612. for (var property in translations) {
  613. if (tag.match(property)) {
  614. $(this).addClass(property);
  615. $(this).text(translations[property]);
  616. break;
  617. }
  618. }
  619. });
  620. })();
  621. // 题目Tag汉化
  622. (function () {
  623. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  624. var selectElement = parentElement.find('select');
  625. var translations = {
  626. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  627. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  628. "2-sat": "二分图可满足性问题(2-sat)",
  629. "binary search": "二分搜索(binary search)",
  630. "bitmasks": "位掩码(bitmasks)",
  631. "brute force": "暴力枚举(brute force)",
  632. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  633. "combinatorics": "组合数学(combinatorics)",
  634. "constructive algorithms": "构造算法(constructive algorithms)",
  635. "data structures": "数据结构(data structures)",
  636. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  637. "divide and conquer": "分治算法(divide and conquer)",
  638. "dp": "动态规划(dp)",
  639. "dsu": "并查集(dsu)",
  640. "expression parsing": "表达式解析(expression parsing)",
  641. "fft": "快速傅里叶变换(fft)",
  642. "flows": "流(flows)",
  643. "games": "博弈论(games)",
  644. "geometry": "计算几何(geometry)",
  645. "graph matchings": "图匹配(graph matchings)",
  646. "graphs": "图论(graphs)",
  647. "greedy": "贪心策略(greedy)",
  648. "hashing": "哈希表(hashing)",
  649. "implementation": "实现问题,编程技巧,模拟(implementation)",
  650. "interactive": "交互性问题(interactive)",
  651. "math": "数学(math)",
  652. "matrices": "矩阵(matrices)",
  653. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  654. "number theory": "数论(number theory)",
  655. "probabilities": "概率论(probabilities)",
  656. "schedules": "调度算法(schedules)",
  657. "shortest paths": "最短路算法(shortest paths)",
  658. "sortings": "排序算法(sortings)",
  659. "string suffix structures": "字符串后缀结构(string suffix structures)",
  660. "strings": "字符串处理(strings)",
  661. "ternary search": "三分搜索(ternary search)",
  662. "trees": "树形结构(trees)",
  663. "two pointers": "双指针算法(two pointers)"
  664. };
  665. selectElement.find("option").each(function() {
  666. var optionValue = $(this).val();
  667. if (translations[optionValue]) {
  668. $(this).text(translations[optionValue]);
  669. }
  670. });
  671. $("._FilterByTagsFrame_tagBoxCaption").each(function() {
  672. var tag = $(this).text();
  673. if (tag in translations) {
  674. $(this).text(translations[tag]);
  675. }
  676. });
  677. $(".notice").each(function() {
  678. var tag = $(this).text();
  679. if (tag in translations) {
  680. $(this).text(translations[tag]);
  681. }
  682. });
  683. $(".tag-box").each(function() {
  684. var tag = $(this).text();
  685. for (var property in translations) {
  686. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  687. if (tag.match(property)) {
  688. $(this).text(translations[property]);
  689. break;
  690. }
  691. }
  692. });
  693. })();
  694. // 题目过滤器选项汉化
  695. (function () {
  696. var parentElement = $('#gym-filter-form');
  697. var selectElement = parentElement.find('div');
  698. var translations = {
  699. "Contest type:": "比赛类型:",
  700. "ICPC region:": "ICPC地区:",
  701. "Contest format:": "比赛形式:",
  702. "Order by:": "排序方式:",
  703. "Secondary order by:": "次要排序方式:",
  704. "Hide, if participated:": "隐藏我参加过的:",
  705. };
  706. selectElement.find("label").each(function() {
  707. var optionValue = $(this).text();
  708. if (translations[optionValue]) {
  709. $(this).text(translations[optionValue]);
  710. }
  711. });
  712. translations = {
  713. "Season:": "时间范围(年度)",
  714. "Duration, hours:": "持续时间(小时):",
  715. "Difficulty:": "难度:"
  716. };
  717. selectElement.each(function() {
  718. var optionValue = $(this).text();
  719. if (translations[optionValue]) {
  720. $(this).text(translations[optionValue]);
  721. }
  722. });
  723. })();
  724. (function () {
  725. var parentElement = $('.setting-value');
  726. var selectElement = parentElement.find('select');
  727. var translations = {
  728. "Official ACM-ICPC Contest": "ICPC官方比赛",
  729. "Official School Contest": "学校官方比赛",
  730. "Opencup Contest": "Opencup比赛",
  731. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  732. "Training Camp Contest": "训练营比赛",
  733. "Official International Personal Contest": "官方国际个人赛",
  734. "Training Contest": "训练比赛",
  735. "ID_ASC": "创建时间(升序)",
  736. "ID_DESC": "创建时间(降序)",
  737. "RATING_ASC": "评分(升序)",
  738. "RATING_DESC": "评分(降序)",
  739. "DIFFICULTY_ASC": "难度(升序)",
  740. "DIFFICULTY_DESC": "难度(降序)",
  741. "START_TIME_ASC": "开始时间(升序)",
  742. "START_TIME_DESC": "开始时间(降序)",
  743. "DURATION_ASC": "持续时间(升序)",
  744. "DURATION_DESC": "持续时间(降序)",
  745. "POPULARITY_ASC": "热度(升序)",
  746. "POPULARITY_DESC": "热度(降序)",
  747. "UPDATE_TIME_ASC": "更新时间(升序)",
  748. "UPDATE_TIME_DESC": "更新时间(降序)"
  749. };
  750. selectElement.find("option").each(function() {
  751. var optionValue = $(this).val();
  752. if (translations[optionValue]) {
  753. $(this).text(translations[optionValue]);
  754. }
  755. });
  756. parentElement = $('.setting-last-value');
  757. selectElement = parentElement.find('select');
  758. selectElement.find("option").each(function() {
  759. var optionValue = $(this).val();
  760. if (translations[optionValue]) {
  761. $(this).text(translations[optionValue]);
  762. }
  763. });
  764. })();
  765. // 右侧sidebox通用汉化
  766. (function () {
  767. var parentElement = $('.sidebox');
  768. var selectElement = parentElement.find('div');
  769. var translations = {
  770. "Show tags for unsolved problems": "显示未解决问题的标签",
  771. "Hide solved problems": "隐藏已解决的问题",
  772. };
  773. selectElement.find("label").each(function() {
  774. var optionValue = $(this).text();
  775. if (translations[optionValue]) {
  776. $(this).text(translations[optionValue]);
  777. }
  778. });
  779. })();
  780. // 杂项汉化
  781. (function () {
  782. var translations = {
  783. "(standard input\/output)": "标准输入/输出",
  784. };
  785. $("div.notice").each(function() {
  786. var tag = $(this).children().eq(0).text();
  787. for (var property in translations) {
  788. if (tag.match(property)) {
  789. $(this).children().eq(0).text(translations[property]);
  790. break;
  791. }
  792. }
  793. });
  794. })();
  795.  
  796. })();
  797.  
  798. // **设置面板**
  799. $("div[class='lang-chooser']").each(function() {
  800. $(this).before(
  801. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  802. );
  803. });
  804. $(document).ready(function () {
  805. $(".CFBetter_setting").click(function () {
  806. $(".CFBetter_setting").attr("disabled", true);
  807. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  808. $(".CFBetter_setting").css("color", "#727378");
  809. $(".CFBetter_setting").css("cursor", "not-allowed");
  810. $("body").append(`
  811. <div id='CFBetter_setting_menu'>
  812. <div class="tool-box">
  813. <button class="btn-close">×</button>
  814. </div>
  815. <h3>基本设置</h3>
  816. <hr>
  817. <div class='CFBetter_setting_list'>
  818. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  819. <label for="bottomZh_CN">界面汉化</label>
  820. </div>
  821. <h3>翻译设置</h3>
  822. <hr>
  823. <label>
  824. <input type='radio' name='translation' value='deepl'>
  825. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  826. </label>
  827. <label>
  828. <input type='radio' name='translation' value='youdao'>
  829. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  830. </label>
  831. <label>
  832. <input type='radio' name='translation' value='openai'>
  833. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  834. </label>
  835. <label>
  836. <input type='radio' name='translation' value='api2d'>
  837. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  838. </label><br>
  839. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  840. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  841. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  842. </div>
  843. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  844. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  845. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  846. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  847. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  848. </div>
  849. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  850. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  851. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  852. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  853. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  854. </div>
  855. <br>
  856. <button id='save'>保存</button>
  857. </div>
  858. `);
  859. var translation = getCookie("translation");
  860. $("#bottomZh_CN").prop("checked", getCookie("bottomZh_CN") === "true");
  861. if (translation === 'undefined' || translation === '') {
  862. setCookie("translation", "deepl", 3650);
  863. $("input[name='translation'][value='deepl']").prop("checked", true);
  864. } else {
  865. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  866. $("input[name='translation']").css("color", "gray");
  867. if (translation == "baidu") {
  868. $("#baidu").show();
  869. $("#baidu_uid").val(getCookie("baidu_uid"));
  870. $("#baidu_key").val(getCookie("baidu_key"));
  871. $("#baidu_uid").css("color", "gray");
  872. $("#baidu_key").css("color", "gray");
  873. } else if (translation == "openai") {
  874. $("#openai").show();
  875. $("#openai_key").val(getCookie("openai_key"));
  876. $("#openai_key").css("color", "gray");
  877. } else if (translation == "api2d") {
  878. $("#api2d").show();
  879. $("#api2d_key").val(getCookie("api2d_key"));
  880. $("#api2d_key").css("color", "gray");
  881. }
  882. }
  883.  
  884. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  885. $("input[name='translation']").change(function () {
  886. var selected = $(this).val(); // 获取当前选中的值
  887. if (selected === 'baidu') {
  888. $("#baidu").show();
  889. $("#baidu_uid").val(getCookie("baidu_uid"));
  890. $("#baidu_key").val(getCookie("baidu_key"));
  891. $("#openai, #api2d").hide();
  892. } else if (selected === 'openai') {
  893. $("#openai").show();
  894. $("#openai_key").val(getCookie("openai_key"));
  895. $("#baidu, #api2d").hide();
  896. } else if (selected === 'api2d') {
  897. $("#api2d").show();
  898. $("#api2d_key").val(getCookie("api2d_key"));
  899. $("#baidu, #openai").hide();
  900. } else {
  901. $("#baidu, #openai, #api2d").hide();
  902. }
  903. });
  904.  
  905. $("#save").click(function () {
  906. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  907. var translation = $("input[name='translation']:checked").val();
  908. var baidu_uid = $("#baidu_uid").val();
  909. var baidu_key = $("#baidu_key").val();
  910. var openai_key = $("#openai_key").val();
  911. var api2d_key = $("#api2d_key").val();
  912. setCookie("translation", translation, 3650);
  913. if (translation == "baidu") {
  914. setCookie("baidu_uid", baidu_uid, 3650);
  915. setCookie("baidu_key", baidu_key, 3650);
  916. } else if (translation == "openai") {
  917. setCookie("openai_key", openai_key, 3650);
  918. } else if (translation == "api2d") {
  919. setCookie("api2d_key", api2d_key, 3650);
  920. }
  921. location.reload();
  922. });
  923. // 关闭
  924. $("#CFBetter_setting_menu .btn-close").click(function () {
  925. $("#CFBetter_setting_menu").remove();
  926. $(".CFBetter_setting").attr("disabled", false);
  927. $(".CFBetter_setting").css("background-color", "#60a5fa");
  928. $(".CFBetter_setting").css("color", "white");
  929. $(".CFBetter_setting").css("cursor", "pointer");
  930. });
  931. });
  932. });
  933.  
  934. // 题目markdown转换/翻译面板
  935. function addButtonPanel(parent, suffix, type, is_simple = false){
  936. if(type === "upper_level_2"||type === "problem"){
  937. $(parent).children(':eq(1)').before(
  938. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  939. }else if(is_simple){
  940. $(parent).before(
  941. "<div class='html2md-panel'><button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  942. }else{
  943. $(parent).before(
  944. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  945. }
  946. }
  947. function addButtonWithHTML2MD(parent, suffix, type) {
  948. $(".html2md-view" + suffix).click(function () {
  949. var target, removedChildren;
  950. if(type === "problem") {
  951. target = $(parent).children().next().next().get(0);
  952. } else if(type === "problem_QA"){
  953. target = $(this).parent().parent().get(0);
  954. removedChildren = $(this).parent().parent().children().eq(0).detach();
  955. } else if(type === "upper_level_2") {
  956. target = parent;
  957. removedChildren = $(parent).children().slice(0, 2).detach();
  958. } else {
  959. target = parent;
  960. }
  961. if (target.viewmd) {
  962. target.viewmd = false;
  963. $(this).text("MarkDown视图");
  964. $(this).removeClass("mdViewed");
  965. $(target).html(target.original_html);
  966. } else {
  967. target.viewmd = true;
  968. if (!target.original_html){
  969. target.original_html = $(target).html();
  970. }
  971. if (!target.markdown){
  972. target.markdown = turndownService.turndown($(target).html());
  973. }
  974. $(this).text("原始内容");
  975. $(this).addClass("mdViewed");
  976. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  977. }
  978. // 恢复删除的元素
  979. if(type === "problem_QA"||type === "upper_level_2") $(target).prepend(removedChildren);
  980. });
  981. }
  982.  
  983. function addButtonWithCopy(parent, suffix, type) {
  984. $(".html2md-cb" + suffix).click(function () {
  985. var target, removedChildren;
  986. if(type === "problem") {
  987. target = $($(parent).children().next().next().get(0)).clone();
  988. } else if(type === "problem_QA"){
  989. target = $(this).parent().parent().eq(0).clone();
  990. $(target).children(':first').remove();
  991. } else if(type === "upper_level_2") {
  992. target = $(parent).clone();
  993. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  994. $(target).children(':first').remove();
  995. } else {
  996. target = $(parent).clone();
  997. }
  998. if (!target.markdown) {
  999. target.markdown = turndownService.turndown($(target).html());
  1000. }
  1001. const textarea = document.createElement('textarea');
  1002. textarea.value = target.markdown;
  1003. document.body.appendChild(textarea);
  1004. textarea.select();
  1005. document.execCommand('copy');
  1006. document.body.removeChild(textarea);
  1007. $(this).addClass("copied");
  1008. $(this).text("Copied");
  1009. // 更新复制按钮文本
  1010. setTimeout(() => {
  1011. $(this).removeClass("copied");
  1012. $(this).text("Copy");
  1013. }, 2000);
  1014. $(target).remove();
  1015. });
  1016. }
  1017.  
  1018. function addButtonWithTranslation(parent, suffix, type) {
  1019. $(".translateButton" + suffix).click(async function () {
  1020. var target, removedChildren;
  1021. if(type === "problem") {
  1022. target = $($(parent).children().next().next().get(0)).clone();
  1023. } else if(type === "problem_QA"){
  1024. target = $(this).parent().parent().eq(0).clone();
  1025. $(target).children(':first').remove();
  1026. } else if(type === "upper_level_2") {
  1027. target = $(parent).clone();
  1028. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1029. $(target).children(':first').remove();
  1030. } else {
  1031. target = $(parent).clone();
  1032. }
  1033. if (!target.markdown) {
  1034. target.markdown = turndownService.turndown($(target).html());
  1035. }
  1036. const textarea = document.createElement('textarea');
  1037. textarea.value = target.markdown;
  1038. // 翻译处理
  1039. $(this).text("翻译中");
  1040. $(this).css("cursor", "not-allowed");
  1041. var element_node;
  1042. if(type === "problem"){
  1043. element_node = $(parent).children()[2]; // 题面特殊处理
  1044. } else if(type === "problem_QA"){
  1045. element_node = $(parent).children().last().get(0);
  1046. }else{
  1047. element_node = parent;
  1048. }
  1049. await translateProblemStatement(textarea.value, element_node);
  1050. //
  1051. $(this).addClass("translated");
  1052. $(this).text("已翻译");
  1053. $(this).prop("disabled", true);
  1054. $(target).remove();
  1055. });
  1056. }
  1057.  
  1058. var turndownService = new TurndownService();
  1059. window.onload = function() {
  1060. turndownService.keep(['del']);
  1061.  
  1062. // **处理规则**
  1063. // 忽略sample-tests
  1064. turndownService.addRule('ignore-sample-tests', {
  1065. filter: function(node) {
  1066. return node.classList.contains('sample-tests')|| node.classList.contains('header');
  1067. },
  1068. replacement: function (content, node) {
  1069. return "";
  1070. }
  1071. });
  1072.  
  1073. // remove <script> math
  1074. turndownService.addRule('remove-script', {
  1075. filter: function (node, options) {
  1076. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1077. },
  1078. replacement: function (content, node) {
  1079. return "";
  1080. }
  1081. });
  1082.  
  1083. // inline math
  1084. turndownService.addRule('inline-math', {
  1085. filter: function (node, options) {
  1086. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1087. },
  1088. replacement: function (content, node) {
  1089. return "$ " + $(node).next().text() + " $";
  1090. }
  1091. });
  1092.  
  1093. // block math
  1094. turndownService.addRule('block-math', {
  1095. filter: function (node, options) {
  1096. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1097. },
  1098. replacement: function (content, node) {
  1099. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1100. }
  1101. });
  1102.  
  1103. // bordertable
  1104. turndownService.addRule('bordertable', {
  1105. filter: 'table',
  1106. replacement: function(content, node) {
  1107. if (node.classList.contains('bordertable')) {
  1108. var output = [],
  1109. thead = '',
  1110. trs = node.querySelectorAll('tr');
  1111. if (trs.length > 0) {
  1112. var ths = trs[0].querySelectorAll('th');
  1113. if (ths.length > 0) {
  1114. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1115. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1116. }
  1117. }
  1118. var rows = node.querySelectorAll('tr');
  1119. Array.from(rows).forEach(function(row, i) {
  1120. if (i > 0) {
  1121. var cells = row.querySelectorAll('td,th');
  1122. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1123. output.push(trow);
  1124. }
  1125. });
  1126. return thead + output.join('\n');
  1127. } else {
  1128. return content;
  1129. }
  1130. }
  1131. });
  1132.  
  1133.  
  1134. // 添加按钮到题面部分
  1135. $("div[class='problem-statement']").each(function () {
  1136. var problem_id = "_comment_"+getRandomNumber(8);
  1137. addButtonPanel(this, problem_id, "problem");
  1138. addButtonWithHTML2MD(this, problem_id, "problem");
  1139. addButtonWithCopy(this, problem_id, "problem");
  1140. addButtonWithTranslation(this, problem_id, "problem");
  1141. });
  1142.  
  1143. // 添加按钮到input部分
  1144. $("div[class='input-specification']").each(function () {
  1145. var id = "_"+getRandomNumber(8);
  1146. addButtonPanel(this, id, "upper_level_2");
  1147. addButtonWithHTML2MD(this, id, "upper_level_2");
  1148. addButtonWithCopy(this, id, "upper_level_2");
  1149. addButtonWithTranslation(this, id, "upper_level_2");
  1150. });
  1151.  
  1152. // 添加按钮到output部分
  1153. $("div[class='output-specification']").each(function () {
  1154. var id = "_"+getRandomNumber(8);
  1155. addButtonPanel(this, id, "upper_level_2");
  1156. addButtonWithHTML2MD(this, id, "upper_level_2");
  1157. addButtonWithCopy(this, id, "upper_level_2");
  1158. addButtonWithTranslation(this, id, "upper_level_2");
  1159. });
  1160.  
  1161. // 添加按钮到note部分
  1162. $("div[class='note']").each(function () {
  1163. var id = "_"+getRandomNumber(8);
  1164. addButtonPanel(this, id, "upper_level_2");
  1165. addButtonWithHTML2MD(this, id, "upper_level_2");
  1166. addButtonWithCopy(this, id, "upper_level_2");
  1167. addButtonWithTranslation(this, id, "upper_level_2");
  1168. });
  1169.  
  1170. // 添加按钮到ttypography部分
  1171. $(".ttypography").each(function () {
  1172. // 题目页特判
  1173. if(!$(this).parent().hasClass('problemindexholder')){
  1174. var comment_id = "_comment_"+getRandomNumber(8);
  1175. addButtonPanel(this,comment_id, "this_level");
  1176. addButtonWithHTML2MD(this, comment_id, "this_level");
  1177. addButtonWithCopy(this, comment_id, "this_level");
  1178. addButtonWithTranslation(this, comment_id, "this_level");
  1179. }
  1180. });
  1181.  
  1182. // 添加按钮到titled部分
  1183. (function(){
  1184. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1185. $.each(elements, function(index, value) {
  1186. $(value).each(function () {
  1187. var titled_id = "_titled_"+getRandomNumber(8);
  1188. var $nextDiv = $(this).next().get(0);
  1189. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1190. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1191. });
  1192. });
  1193. })();
  1194.  
  1195. // 添加按钮到比赛QA部分
  1196. $(".question-requestText-td").each(function () {
  1197. var $nextDiv = $(this).children().get(0);
  1198. var question_id = "_question_"+getRandomNumber(8);
  1199. addButtonPanel($nextDiv,question_id, "problem_QA", true);
  1200. addButtonWithTranslation(this, question_id, "problem_QA");
  1201. });
  1202. };
  1203.  
  1204. // **翻译框/翻译处理器**
  1205. var translatedText = "";
  1206. async function translateProblemStatement(text, element_node){
  1207. let id = Math.floor(Date.now() / 1000);
  1208. let matches =[];
  1209. let replacements= {};
  1210. // 创建元素并放在element_node的后面
  1211. const translateDiv = document.createElement('div');
  1212. translateDiv.setAttribute('id', id);
  1213. translateDiv.classList.add('translate-problem-statement');
  1214. const spanElement = document.createElement('span');
  1215. translateDiv.appendChild(spanElement);
  1216. element_node.insertAdjacentElement('afterend', translateDiv);
  1217. // 替换latex公式
  1218. if(getCookie("translation")!= "api2d"&&getCookie("translation")!= "openai"){
  1219. let i = 0;
  1220. // 块公式
  1221. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1222. try{
  1223. for (i; i < matches.length; i++) {
  1224. let match = matches[i];
  1225. text = text.replace(match, `【${i + 1}】`);
  1226. replacements[`【${i + 1}】`] = match;
  1227. }
  1228. }catch(e){}
  1229. // 行内公式
  1230. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1231. try{
  1232. for (i; i < matches.length; i++) {
  1233. let match = matches[i];
  1234. text = text.replace(match, `【${i + 1}】`);
  1235. replacements[`【${i + 1}】`] = match;
  1236. }
  1237. }catch(e){}
  1238. }
  1239. // 翻译
  1240. var translation = getCookie("translation");
  1241. if (translation === 'undefined' || translation === ''){
  1242. setCookie("translation", "deepl", 3650);
  1243. translation = "deepl";
  1244. }
  1245. if(translation == "deepl") {
  1246. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1247. translatedText = await translate_deepl(text);
  1248. }else if (translation == "youdao" ){
  1249. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1250. translatedText = await translate_youdao_mobile(text);
  1251. }else if (translation == "baidu") {
  1252. var baidu_appid = getCookie("baidu_uid");
  1253. var baidu_key = getCookie("baidu_key");
  1254. } else if (translation == "openai") {
  1255. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1256. translatedText = await translate_openai(text);
  1257. } else if (translation == "api2d") {
  1258. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1259. translatedText = await translate_api2d(text);
  1260. }
  1261. // 还原latex公式
  1262. if(getCookie("translation")!= "api2d"&&getCookie("translation")!= "openai"){
  1263. try{
  1264. for (let i = 0; i < matches.length; i++) {
  1265. let match = matches[i];
  1266. let replacement = replacements[`【${i + 1}】`];
  1267. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1268. }
  1269. }catch(e){}
  1270. }
  1271. // 使符合mathjx的转换语法
  1272. translatedText = translatedText.replace(/(\$\$)/g, "");
  1273. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1274. // 更新
  1275. translateDiv.textContent = translatedText;
  1276. // 渲染MarkDown
  1277. var md = window.markdownit();
  1278. var html = md.render(translateDiv.innerText);
  1279. translateDiv.innerHTML = html;
  1280. // 渲染Latex
  1281. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1282. }
  1283.  
  1284. // ChatGPT
  1285. async function translate_openai(raw) {
  1286. var openai_key = getCookie("openai_key");
  1287. var openai_retext = "";
  1288. const data = {
  1289. prompt: "(You:请帮我翻译将下面的文本翻译为中文,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n"+ raw + ")",
  1290. max_tokens: 2048,
  1291. model: "text-davinci-003",
  1292. }
  1293. return new Promise(function(resolve, reject) {
  1294. GM_xmlhttpRequest({
  1295. method: 'POST',
  1296. url: 'https://api.openai.com/v1/completions',
  1297. data: JSON.stringify(data),
  1298. headers: {
  1299. 'Content-Type': 'application/json',
  1300. 'Authorization': 'Bearer ' + getCookie("openai_key") + ''
  1301. },
  1302. responseType: 'json',
  1303. onload: function (res) {
  1304. if (res.status === 200) {
  1305. openai_retext = res.response.choices[0].text;
  1306. openai_retext = openai_retext.replace(/^\s+/, '');
  1307. resolve(openai_retext);
  1308. }
  1309. else {
  1310. console.error(res.statusText);
  1311. reject(res.statusText);
  1312. }
  1313. }
  1314. });
  1315. });
  1316. }
  1317.  
  1318. // api2d
  1319. async function translate_api2d(raw) {
  1320. var api2d_key = getCookie("api2d_key");
  1321. var api2d_retext = "";
  1322. const postData = JSON.stringify({
  1323. model: 'gpt-3.5-turbo',
  1324. messages: [{ role: 'user', content: '请帮我翻译将下面的文本翻译为中文,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n'+ raw }],
  1325. });
  1326.  
  1327. const options = {
  1328. method: 'POST',
  1329. headers: {
  1330. 'Content-Type': 'application/json',
  1331. Authorization: 'Bearer '+api2d_key,
  1332. },
  1333. data: postData,
  1334. };
  1335.  
  1336. return new Promise(function(resolve, reject) {
  1337. GM_xmlhttpRequest({
  1338. method: options.method,
  1339. url: `https://openai.api2d.net/v1/chat/completions`,
  1340. headers: options.headers,
  1341. data: options.data,
  1342. responseType: 'json',
  1343. onload: function (response) {
  1344. api2d_retext = response.response.choices[0].message.content;
  1345. resolve(api2d_retext);
  1346. },
  1347. onerror: function (response) {
  1348. console.error(response.statusText);
  1349. reject(response.statusText);
  1350. },
  1351. });
  1352. });
  1353. }
  1354. //
  1355.  
  1356. //--有道翻译m--start
  1357. async function translate_youdao_mobile(raw){
  1358. const options = {
  1359. method:"POST",
  1360. url:'http://m.youdao.com/translate',
  1361. data:"inputtext="+encodeURIComponent(raw)+"&type=AUTO",
  1362. anonymous:true,
  1363. headers: {
  1364. "Content-Type": "application/x-www-form-urlencoded"
  1365. }
  1366. }
  1367. return await BaseTranslate('有道翻译mobile',raw,options,res=>/id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1368. }
  1369. //--有道翻译m--end
  1370.  
  1371. //--Deepl翻译--start
  1372. function getTimeStamp(iCount) {
  1373. const ts = Date.now();
  1374. if (iCount !== 0) {
  1375. iCount = iCount + 1;
  1376. return ts - (ts % iCount) + iCount;
  1377. } else {
  1378. return ts;
  1379. }
  1380. }
  1381.  
  1382. async function translate_deepl(raw) {
  1383. const id = (Math.floor(Math.random() * 99999) + 100000)* 1000;
  1384. const data = {
  1385. jsonrpc: '2.0',
  1386. method: 'LMT_handle_texts',
  1387. id,
  1388. params: {
  1389. splitting: 'newlines',
  1390. lang: {
  1391. source_lang_user_selected: 'auto',
  1392. target_lang: 'ZH',
  1393. },
  1394. texts: [{
  1395. text: raw,
  1396. requestAlternatives:3
  1397. }],
  1398. timestamp: getTimeStamp(raw.split('i').length - 1)
  1399. }
  1400. }
  1401. let postData = JSON.stringify(data);
  1402. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1403. postData = postData.replace('"method":"', '"method" : "');
  1404. } else {
  1405. postData = postData.replace('"method":"', '"method": "');
  1406. }
  1407. const options = {
  1408. method: 'POST',
  1409. url: 'https://www2.deepl.com/jsonrpc',
  1410. data: postData,
  1411. headers: {
  1412. 'Content-Type': 'application/json',
  1413. 'Host': 'www.deepl.com',
  1414. 'Origin': 'https://www.deepl.com',
  1415. 'Referer': 'https://www.deepl.com/'
  1416. },
  1417. anonymous:true,
  1418. nocache:true,
  1419. }
  1420. return await BaseTranslate('Deepl翻译',raw,options,res=>JSON.parse(res).result.texts[0].text)
  1421. }
  1422.  
  1423. //--Deepl翻译--end
  1424.  
  1425. // Cookie Get/Set
  1426. function setCookie(cname, cvalue, exdays) {
  1427. var d = new Date();
  1428. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  1429. var expires = "expires=" + d.toUTCString();
  1430. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  1431. }
  1432.  
  1433. function getCookie(cname) {
  1434. var name = cname + "=";
  1435. var decodedCookie = decodeURIComponent(document.cookie);
  1436. var ca = decodedCookie.split(';');
  1437. for (var i = 0; i < ca.length; i++) {
  1438. var c = ca[i];
  1439. while (c.charAt(0) == ' ') {
  1440. c = c.substring(1);
  1441. }
  1442. if (c.indexOf(name) == 0) {
  1443. return c.substring(name.length, c.length);
  1444. }
  1445. }
  1446. return "";
  1447. }
  1448.  
  1449.  
  1450. //--异步请求包装工具--start
  1451. async function PromiseRetryWrap(task,options,...values){
  1452. const {RetryTimes,ErrProcesser} = options||{};
  1453. let retryTimes = RetryTimes||5;
  1454. const usedErrProcesser = ErrProcesser || (err =>{throw err});
  1455. if(!task)return;
  1456. while(true){
  1457. try{
  1458. return await task(...values);
  1459. }catch(err){
  1460. if(!--retryTimes){
  1461. console.log(err);
  1462. return usedErrProcesser(err);
  1463. }
  1464. }
  1465. }
  1466. }
  1467.  
  1468. async function BaseTranslate(name,raw,options,processer){
  1469. const toDo = async ()=>{
  1470. var tmp;
  1471. try{
  1472. const data = await Request(options);
  1473. tmp = data.responseText;
  1474. const result = await processer(tmp);
  1475. if(result)sessionStorage.setItem(name+'-'+raw,result);
  1476. return result
  1477. }catch(err){
  1478. throw {
  1479. responseText: tmp,
  1480. err: err
  1481. }
  1482. }
  1483. }
  1484. return await PromiseRetryWrap(toDo,{RetryTimes:3,ErrProcesser:()=>"翻译出错"})
  1485. }
  1486.  
  1487. function Request(options){
  1488. return new Promise((reslove,reject)=>GM_xmlhttpRequest({...options,onload:reslove,onerror:reject}))
  1489. }
  1490.  
  1491. //--异步请求包装工具--end
  1492.  
  1493. // 随机数生成
  1494. function getRandomNumber(numDigits) {
  1495. let min = Math.pow(10, numDigits - 1);
  1496. let max = Math.pow(10, numDigits) - 1;
  1497. return Math.floor(Math.random() * (max - min + 1)) + min;
  1498. }