Codeforces Better!

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

目前為 2023-05-12 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.08
  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. // @license MIT
  18. // ==/UserScript==
  19. // 样式
  20. function loadCssCode(code){
  21. var style = document.createElement('style');
  22. style.type = 'text/css';
  23. style.rel = 'stylesheet';
  24. style.appendChild(document.createTextNode(code));
  25. var head = document.getElementsByTagName('head')[0];
  26. head.appendChild(style);
  27. }
  28. loadCssCode(`
  29. span.mdViewContent {
  30. white-space: pre-wrap;
  31. }
  32. .translate-problem-statement {
  33. white-space: pre-wrap;
  34. border: 1px dashed #00aeeccc;
  35. border-radius: 0.3rem;
  36. padding: 5px;
  37. margin: 5px 0px;
  38. }
  39. .html2md-panel {
  40. display: flex;
  41. justify-content: flex-end;
  42. }
  43. button.html2mdButton {
  44. height: 3vh;
  45. width: 3vh;
  46. }
  47. button.html2mdButton {
  48. cursor: pointer;
  49. background-color: #e6e6e6;
  50. color: #727378;
  51. height: 3vh;
  52. width: auto;
  53. font-size: 1.3vh;
  54. border-radius: 0.3rem;
  55. border: none;
  56. padding: 1px 5px;
  57. margin: 5px;
  58. box-shadow: 0 0 1px #0000004d;
  59. }
  60. button.html2mdButton.copied {
  61. background-color: #07e65196;
  62. color: #104f2b;
  63. }
  64. button.html2mdButton.mdViewed {
  65. background-color: #ff980057;
  66. color: #5a3a0c;
  67. }
  68. button.translated {
  69. cursor: not-allowed;
  70. background-color: #2a6dc296;
  71. color: #fffdfd;
  72. }
  73. /*设置面板*/
  74. #CFBetter_setting_menu {
  75. z-index: 9999;
  76. border-radius: 0.5rem;
  77. box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  78. display: grid;
  79. position: fixed;
  80. top: 50%;
  81. left: 50%;
  82. width: 270px;
  83. transform: translate(-50%, -50%);
  84. border-radius: 16px;
  85. background-color: #ecf0ff;
  86. border: 6px solid #ffffff;
  87. color: #697e91;
  88. padding: 10px 20px 20px 20px;
  89. }
  90.  
  91. #CFBetter_setting_menu .tool-box {
  92. position: absolute;
  93. display: flex;
  94. align-items: center;
  95. justify-content: center;
  96. width: 2.5rem;
  97. height: 2.5rem;
  98. top: 3px;
  99. right: 3px;
  100. }
  101.  
  102. #CFBetter_setting_menu .btn-close {
  103. display: flex;
  104. align-items: center;
  105. justify-content: center;
  106. text-align: center;
  107. width: 2rem;
  108. height: 2rem;
  109. color: transparent;
  110. font-size: 0;
  111. cursor: pointer;
  112. background-color: #ff000080;
  113. border: none;
  114. border-radius: 10px;
  115. transition: .2s ease all;
  116. }
  117.  
  118. #CFBetter_setting_menu .btn-close:hover {
  119. width: 2rem;
  120. height: 2rem;
  121. font-size: 1rem;
  122. color: #ffffff;
  123. background-color: #ff0000cc;
  124. box-shadow: 0 5px 5px 0 #00000026;
  125. }
  126.  
  127. #CFBetter_setting_menu .btn-close:active {
  128. width: .9rem;
  129. height: .9rem;
  130. font-size: .9rem;
  131. color: #ffffffde;
  132. --shadow-btn-close: 0 3px 3px 0 #00000026;
  133. box-shadow: var(--shadow-btn-close);
  134. }
  135.  
  136. #CFBetter_setting_menu>label {
  137. display: flex;
  138. list-style-type: none;
  139. padding-inline-start: 0px;
  140. overflow-x: auto;
  141. max-width: 100%;
  142. margin: 0px;
  143. align-items: center;
  144. margin: 3px 0px;
  145. }
  146.  
  147. .CFBetter_setting_menu_label_text {
  148. border: 1px dashed #00aeeccc;
  149. display: block;
  150. height: 20px;
  151. width: 100%;
  152. color: gray;
  153. font-weight: 300;
  154. font-size: 14px;
  155. letter-spacing: 2px;
  156. padding: 7px;
  157. }
  158.  
  159. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  160. background: #41e49930;
  161. border: 1px solid green;
  162. color: green;
  163. font-weight: 500;
  164. }
  165.  
  166. #CFBetter_setting_menu>label input[type="radio"] {
  167. -webkit-appearance: none;
  168. appearance: none;
  169. list-style: none;
  170. margin: 0px;
  171. }
  172.  
  173. #CFBetter_setting_menu input[type="text"] {
  174. display: block;
  175. height: 25px;
  176. background-color: #ffffff;
  177. color: #727378;
  178. font-size: 1.3vh;
  179. border-radius: 0.3rem;
  180. padding: 1px 5px;
  181. margin: 5px 0px 5px 0px;
  182. border: 1px solid #00aeeccc;
  183. box-shadow: 0 0 1px #0000004d;
  184. }
  185.  
  186. .CFBetter_setting_menu_input {
  187. width: 100%;
  188. display: grid;
  189. justify-content: start;
  190. }
  191.  
  192. #CFBetter_setting_menu #save {
  193. cursor: pointer;
  194. display: inline-flex;
  195. padding: 0.5rem 1rem;
  196. background-color: #1aa06d;
  197. color: #ffffff;
  198. font-size: 1rem;
  199. line-height: 1.5rem;
  200. font-weight: 500;
  201. justify-content: center;
  202. width: 100%;
  203. border-radius: 0.375rem;
  204. border: none;
  205. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  206. }
  207.  
  208. button.html2mdButton.CFBetter_setting {
  209. float: right;
  210. background: #60a5fa;
  211. color: white;
  212. box-shadow: 0px 0px 1px 1px #0000004d;
  213. margin: 10px;
  214. }
  215. #CFBetter_setting_menu span.tip {
  216. color: red;
  217. font-size: 2px;
  218. font-weight: 500;
  219. padding: 0px 0px 10px 0px;
  220. }
  221. /*更新检查*/
  222. div#update_panel {
  223. position: fixed;
  224. top: 50%;
  225. left: 50%;
  226. width: 240px;
  227. transform: translate(-50%, -50%);
  228. background-color: #fdfdfd;
  229. border: 1px solid #00aeeccc;
  230. border-radius: 5px;
  231. box-shadow: 2px 2px 3px 1px #0000004d;
  232. padding: 10px 20px 20px 20px;
  233. color: #444242;
  234. background-color: #ecf0ff;
  235. border: 6px solid #ffffff;
  236. border-radius: 16px;
  237. }
  238. div#update_panel #updating {
  239. cursor: pointer;
  240. display: inline-flex;
  241. padding: 0.5rem 1rem;
  242. background-color: #1aa06d;
  243. color: #ffffff;
  244. font-size: 1rem;
  245. line-height: 1.5rem;
  246. font-weight: 500;
  247. justify-content: center;
  248. width: 100%;
  249. border-radius: 0.375rem;
  250. border: none;
  251. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  252. }
  253. div#update_panel #updating a {
  254. text-decoration: none;
  255. color: white;
  256. }
  257. `);
  258.  
  259. // 更新检查
  260. (function checkScriptVersion() {
  261. function compareVersions(version1 = "0", version2 = "0") {
  262. const v1Array = String(version1).split(".");
  263. const v2Array = String(version2).split(".");
  264. const minLength = Math.min(v1Array.length, v2Array.length);
  265. let result = 0;
  266. for (let i = 0; i < minLength; i++) {
  267. const curV1 = Number(v1Array[i]);
  268. const curV2 = Number(v2Array[i]);
  269. if (curV1 > curV2) {
  270. result = 1;
  271. break;
  272. } else if (curV1 < curV2) {
  273. result = -1;
  274. break;
  275. }
  276. }
  277. if (result === 0 && v1Array.length !== v2Array.length) {
  278. const v1IsBigger = v1Array.length > v2Array.length;
  279. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  280. for (let i = minLength; i < maxLenArray.length; i++) {
  281. const curVersion = Number(maxLenArray[i]);
  282. if (curVersion > 0) {
  283. v1IsBigger ? result = 1 : result = -1;
  284. break;
  285. }
  286. }
  287. }
  288. return result;
  289. }
  290.  
  291. GM_xmlhttpRequest({
  292. method: "GET",
  293. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  294. timeout: 10 * 1e3,
  295. onload: function(response) {
  296. const scriptData = JSON.parse(response.responseText);
  297. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  298. $("body").append(`
  299. <div id='update_panel'>
  300. <h3>${GM_info.script.name}有新版本!</h3>
  301. <hr>
  302. <div class='update_panel_menu'>
  303. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  304. </div>
  305. <br>
  306. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  307. </div>
  308. `);
  309. }
  310. }
  311. });
  312. })();
  313.  
  314. // 汉化替换
  315. (function() {
  316. // 设置语言为zh
  317. var htmlTag = document.getElementsByTagName("html")[0];
  318. htmlTag.setAttribute("lang", "zh-CN");
  319.  
  320. // 定义classData,存放元素的class名和对应的替换规则
  321. const classData = {
  322. '.menu-list.main-menu-list': [
  323. { match: 'Help', replace: '帮助' },
  324. { match: 'Calendar', replace: '日历' },
  325. { match: 'Edu', replace: '培训' },
  326. { match: 'Rating', replace: '积分榜' },
  327. { match: 'Groups', replace: '团体' },
  328. { match: 'Problemset', replace: '题单' },
  329. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  330. { match: 'Contests', replace: '比赛' },
  331. { match: 'Catalog', replace: '指南目录' },
  332. { match: 'Top', replace: '热门' },
  333. { match: 'Home', replace: '主页' },
  334. ],
  335. '.caption.titled': [
  336. { match: 'Pay attention', replace: '注意' },
  337. { match: 'Top rated', replace: '积分排行' },
  338. { match: 'Top contributors', replace: '贡献者排行' },
  339. { match: 'Find user', replace: '查找用户' },
  340. { match: 'Recent actions', replace: '最近热帖' },
  341. { match: 'Training filter', replace: '过滤筛选' },
  342. { match: 'Find training', replace: '搜索比赛/问题' },
  343. { match: 'Virtual participation', replace: '什么是虚拟参赛' },
  344. { match: 'Contest materials', replace: '比赛相关资料' },
  345. { match: 'Settings', replace: '设置' },
  346. { match: 'Clone Contest to Mashup', replace: 'Clone比赛到组合混搭' },
  347. { match: 'Submit', replace: '提交' },
  348. ],
  349. '.personal-sidebar ': [
  350. { match: 'Contribution', replace: '贡献' },
  351. { match: 'Settings', replace: '设置' },
  352. { match: 'Blog', replace: '博客' },
  353. { match: 'Teams', replace: '队伍' },
  354. { match: 'Submissions', replace: '提交' },
  355. { match: 'Talks', replace: '私信' },
  356. { match: 'Contests', replace: '比赛' },
  357. ],
  358. '.contest-state-phase': [
  359. { match: 'Before contest', replace: '即将进行的比赛' },
  360. ],
  361. '.act-item': [
  362. { match: 'Add to favourites', replace: '添加到收藏' },
  363. { match: 'Submit', replace: '提交' },
  364. ],
  365. '.datatable': [
  366. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  367. { match: 'Enter', replace: '进入' },
  368. { match: 'Final standings', replace: '榜单' },
  369. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  370. { match: 'Official School Contest', replace: '学校官方比赛' },
  371. { match: 'Training Contest', replace: '训练赛' },
  372. { match: 'Training Camp Contest', replace: '训练营比赛' },
  373. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  374. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  375. { match: 'China', replace: '中国' },
  376. { match: 'Statements', replace: '题目描述' },
  377. { match: 'in Chinese', replace: '中文' },
  378. { match: 'Trainings', replace: '训练' },
  379. { match: 'Prepared by', replace: '编写人' },
  380. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  381. { match: 'Past contests', replace: '过去的比赛' },
  382. { match: 'Exclusions', replace: '排除' },
  383. { match: 'Before start', replace: '还有' },
  384. { match: 'Before registration', replace: '报名还有' },
  385. { match: 'Until closing ', replace: '结束报名' },
  386. { match: 'Register', replace: '报名' },
  387. { match: 'Registration completed', replace: '已报名' },
  388. { match: 'Questions about problems', replace: '关于题目的提问' },
  389. ],
  390. '.ask-question-link': [
  391. { match: 'Ask a question', replace: '提一个问题' },
  392. ],
  393. '.contests-table': [
  394. { match: 'Contest history', replace: '比赛历史' },
  395. ],
  396. '.roundbox.sidebox.borderTopRound ': [
  397. { match: 'Season:', replace: '时间范围(年度)' },
  398. { match: 'Contest type', replace: '比赛类型' },
  399. { match: 'ICPC region', replace: 'ICPC地区' },
  400. { match: 'Contest format', replace: '比赛形式' },
  401. { match: 'Duration, hours', replace: '持续时间(小时)' },
  402. { match: 'Order by', replace: '排序方式' },
  403. { match: 'Secondary order by', replace: '次要排序方式' },
  404. { match: 'Hide, if participated', replace: '隐藏我参与过的' },
  405. { match: 'Hide excluded gyms', replace: '隐藏排除的比赛' },
  406. { match: 'Register now', replace: '现在报名' },
  407. { match: 'Show tags for unsolved problems', replace: '显示未解决问题的标签' },
  408. { match: 'Hide solved problems', replace: '隐藏已解决的问题' },
  409. ],
  410. '.icon-eye-close.icon-large': [
  411. { match: 'Add to exclusions', replace: '添加到排除列表' },
  412. ],
  413. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  414. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  415. ],
  416. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  417. { match: 'Announcement', replace: '公告' },
  418. { match: 'Statements', replace: '统计报表' },
  419. { match: 'Tutorial', replace: '题解' },
  420. ],
  421. '.second-level-menu ': [
  422. { match: 'Problems', replace: '问题' },
  423. { match: 'Submit Code', replace: '提交代码' },
  424. { match: 'My Submissions', replace: '我的提交' },
  425. { match: 'Status', replace: '状态' },
  426. { match: 'Standings', replace: '榜单' },
  427. { match: 'Custom Invocation', replace: '自定义调试' },
  428. { match: 'Common standings', replace: '全部排行' },
  429. { match: 'Friends standings', replace: '只看朋友' },
  430. { match: 'Submit', replace: '提交' },
  431. { match: 'Custom test', replace: '自定义测试' },
  432. { match: 'Blog', replace: '博客' },
  433. { match: 'Teams', replace: '队伍' },
  434. { match: 'Submissions', replace: '提交' },
  435. { match: 'Groups', replace: '团体' },
  436. { match: 'Contests', replace: '比赛' },
  437. { match: '问题etting', replace: '参与编写的问题' },
  438. { match: 'Gym', replace: '训练营' },
  439. { match: 'Mashups', replace: '组合混搭' },
  440. { match: 'Posts', replace: '帖子' },
  441. { match: 'Comments', replace: '回复' },
  442. { match: 'Main', replace: '主要' },
  443. { match: 'Settings', replace: '设置' },
  444. { match: 'Lists', replace: '列表' },
  445. ],
  446. '.topic-toggle-collapse': [
  447. { match: 'Expand', replace: '展开' },
  448. ],
  449. '.topic-read-more': [
  450. { match: 'Full text and comments', replace: '阅读全文/评论' },
  451. ],
  452. '.toggleEditorCheckboxLabel': [
  453. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  454. ],
  455. '.content-with-sidebar': [
  456. { match: 'Notice', replace: '注意' },
  457. { match: 'virtual participation', replace: '虚拟参与' },
  458. { match: 'Registration for the contest', replace: '比赛报名' },
  459. { match: 'Terms of agreement', replace: '协议条款' },
  460. { match: 'Take part', replace: '参与' },
  461. { match: 'as individual participant', replace: '作为个人参与者' },
  462. { match: 'as a team member', replace: '作为团队成员' },
  463. { match: 'Virtual start time', replace: '虚拟开始时间' },
  464. { match: 'Complete problemset', replace: '完整的问题集' },
  465. ],
  466. '.submit': [
  467. { match: 'Registration for the contest', replace: '比赛报名' },
  468. ],
  469. '.table-form': [
  470. { match: 'Problem', replace: '题目' },
  471. { match: 'Language', replace: '语言' },
  472. { match: 'Source code', replace: '源代码' },
  473. { match: 'Or choose file', replace: '或者选择文件' },
  474. { match: 'Choose file', replace: '选择文件' },
  475. ],
  476. };
  477.  
  478. // 将所有 class 名与之符合的元素的 text 中包含的匹配的文字均替换为对应的文字
  479. for (const className in classData) {
  480. const elements = document.querySelectorAll(className);
  481. elements.forEach((element) => {
  482. let html = element.outerHTML; // 获取元素的 html 代码
  483. const parent = element.parentNode;
  484. const childIndex = Array.from(parent.children).indexOf(element);
  485. let matched = false; // 标记该元素是否匹配了规则
  486. classData[className].forEach((rule) => {
  487. if (html.match(new RegExp(rule.match, 'g'))) {
  488. // 如果匹配成功,则将 matched 设置为 true
  489. matched = true;
  490. html = html.replace(new RegExp(rule.match, 'g'), rule.replace); // 将其中匹配的文字替换为对应的文字
  491. const temp = document.createElement('div'); // 创建临时元素
  492. temp.innerHTML = html.trim();
  493. const newElement = element.cloneNode(true);
  494. newElement.innerHTML = temp.firstChild.innerHTML;
  495. parent.replaceChild(newElement, parent.children[childIndex]); // 替换元素
  496. }
  497. });
  498. });
  499. }
  500. })();
  501.  
  502. // 设置面板
  503. $("div[class='lang-chooser']").each(function() {
  504. $(this).before(
  505. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  506. );
  507. });
  508. $(document).ready(function () {
  509. $(".CFBetter_setting").click(function () {
  510. $(".CFBetter_setting").attr("disabled", true);
  511. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  512. $(".CFBetter_setting").css("color", "#727378");
  513. $(".CFBetter_setting").css("cursor", "not-allowed");
  514. $("body").append(`
  515. <div id='CFBetter_setting_menu'>
  516. <div class="tool-box">
  517. <button class="btn-close">×</button>
  518. </div>
  519. <h3>翻译设置</h3>
  520. <hr>
  521. <label>
  522. <input type='radio' name='translation' value='deepl'>
  523. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  524. </label>
  525. <label>
  526. <input type='radio' name='translation' value='youdao'>
  527. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  528. </label>
  529. <label>
  530. <input type='radio' name='translation' value='openai'>
  531. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  532. </label>
  533. <label>
  534. <input type='radio' name='translation' value='api2d'>
  535. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  536. </label><br>
  537. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  538. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  539. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  540. </div>
  541. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  542. <span class ='tip'>提示:<br>使用ChatGPT-3.5,脚本的所有请求均在本地完成,<br>请确保你能够正常访问OpenAIapi</span>
  543. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  544. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  545. </div>
  546. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  547. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  548. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  549. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  550. </div>
  551. <br>
  552. <button id='save'>保存</button>
  553. </div>
  554. `);
  555. var translation = getCookie("translation");
  556. if (translation === 'undefined' || translation === '') {
  557. setCookie("translation", "deepl", 3650);
  558. $("input[name='translation'][value='deepl']").prop("checked", true);
  559. } else {
  560. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  561. $("input[name='translation']").css("color", "gray");
  562. if (translation == "baidu") {
  563. $("#baidu").show();
  564. $("#baidu_uid").val(getCookie("baidu_uid"));
  565. $("#baidu_key").val(getCookie("baidu_key"));
  566. $("#baidu_uid").css("color", "gray");
  567. $("#baidu_key").css("color", "gray");
  568. } else if (translation == "openai") {
  569. $("#openai").show();
  570. $("#openai_key").val(getCookie("openai_key"));
  571. $("#openai_key").css("color", "gray");
  572. } else if (translation == "api2d") {
  573. $("#api2d").show();
  574. $("#api2d_key").val(getCookie("api2d_key"));
  575. $("#api2d_key").css("color", "gray");
  576. }
  577. }
  578.  
  579. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  580. $("input[name='translation']").change(function () {
  581. var selected = $(this).val(); // 获取当前选中的值
  582. if (selected === 'baidu') {
  583. $("#baidu").show();
  584. $("#baidu_uid").val(getCookie("baidu_uid"));
  585. $("#baidu_key").val(getCookie("baidu_key"));
  586. $("#openai, #api2d").hide();
  587. } else if (selected === 'openai') {
  588. $("#openai").show();
  589. $("#openai_key").val(getCookie("openai_key"));
  590. $("#baidu, #api2d").hide();
  591. } else if (selected === 'api2d') {
  592. $("#api2d").show();
  593. $("#api2d_key").val(getCookie("api2d_key"));
  594. $("#baidu, #openai").hide();
  595. } else {
  596. $("#baidu, #openai, #api2d").hide();
  597. }
  598. });
  599.  
  600. $("#save").click(function () {
  601. var translation = $("input[name='translation']:checked").val();
  602. var baidu_uid = $("#baidu_uid").val();
  603. var baidu_key = $("#baidu_key").val();
  604. var openai_key = $("#openai_key").val();
  605. var api2d_key = $("#api2d_key").val();
  606. setCookie("translation", translation, 3650);
  607. if (translation == "baidu") {
  608. setCookie("baidu_uid", baidu_uid, 3650);
  609. setCookie("baidu_key", baidu_key, 3650);
  610. } else if (translation == "openai") {
  611. setCookie("openai_key", openai_key, 3650);
  612. } else if (translation == "api2d") {
  613. setCookie("api2d_key", api2d_key, 3650);
  614. }
  615. location.reload();
  616. });
  617. // 关闭
  618. $("#CFBetter_setting_menu .btn-close").click(function () {
  619. $("#CFBetter_setting_menu").remove();
  620. $(".CFBetter_setting").attr("disabled", false);
  621. $(".CFBetter_setting").css("background-color", "#60a5fa");
  622. $(".CFBetter_setting").css("color", "white");
  623. $(".CFBetter_setting").css("cursor", "pointer");
  624. });
  625. });
  626. });
  627.  
  628. // 题目markdown转换/翻译面板
  629. window.onload = function() {
  630. let turndownService = new TurndownService();
  631.  
  632. turndownService.keep(['del']);
  633.  
  634. // **处理规则**
  635. // 忽略sample-tests
  636. turndownService.addRule('ignore-sample-tests', {
  637. filter: function(node) {
  638. return node.classList.contains('sample-tests')|| node.classList.contains('header');
  639. },
  640. replacement: function (content, node) {
  641. return "";
  642. }
  643. });
  644.  
  645. // remove <script> math
  646. turndownService.addRule('remove-script', {
  647. filter: function (node, options) {
  648. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  649. },
  650. replacement: function (content, node) {
  651. return "";
  652. }
  653. });
  654.  
  655. // inline math
  656. turndownService.addRule('inline-math', {
  657. filter: function (node, options) {
  658. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  659. },
  660. replacement: function (content, node) {
  661. return "$ " + $(node).next().text() + " $";
  662. }
  663. });
  664.  
  665. // block math
  666. turndownService.addRule('block-math', {
  667. filter: function (node, options) {
  668. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  669. },
  670. replacement: function (content, node) {
  671. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  672. }
  673. });
  674.  
  675. // **题干**
  676. // 添加按钮
  677. $("div[class='problem-statement']").each(function() {
  678. $(this).children(':eq(1)').before(
  679. "<div class='html2md-panel'> <button class='html2mdButton html2md-view1'>MarkDown视图</button> <button class='html2mdButton html2md-cb1'>Copy</button> <button class='html2mdButton translateButton1'>翻译</button> </div>"
  680. );
  681. });
  682.  
  683.  
  684. $(".html2md-cb1").click(function() {
  685. let target = $(this).parent().next().get(0);
  686. if (!target.markdown){
  687. target.markdown = turndownService.turndown($(target).html());
  688. }
  689. const textarea = document.createElement('textarea');
  690. textarea.value = target.markdown;
  691. document.body.appendChild(textarea);
  692. textarea.select();
  693. document.execCommand('copy');
  694. document.body.removeChild(textarea);
  695. $(this).addClass("copied");
  696. $(this).text("Copied");
  697. // 更新复制按钮文本
  698. setTimeout(() => {
  699. $(this).removeClass("copied");
  700. $(this).text("Copy");
  701. }, 2000);
  702. });
  703.  
  704. $(".html2md-view1").click(function() {
  705. let target = $(this).parent().next().get(0);
  706. if (target.viewmd) {
  707. target.viewmd = false;
  708. $(this).text("MarkDown视图");
  709. $(this).removeClass("mdViewed");
  710. $(target).html(target.original_html);
  711. } else {
  712. target.viewmd = true;
  713. if (!target.original_html)
  714. target.original_html = $(target).html();
  715. if (!target.markdown)
  716. target.markdown = turndownService.turndown($(target).html());
  717. $(this).text("原始内容");
  718. $(this).addClass("mdViewed");
  719. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;"> ${target.markdown} </span>`);
  720. }
  721. });
  722. $(".translateButton1").click(async function() {
  723. let target = $(this).parent().next().get(0);
  724. if (!target.markdown){
  725. target.markdown = turndownService.turndown($(target).html());
  726. }
  727. const textarea = document.createElement('textarea');
  728. textarea.value = target.markdown;
  729. // 翻译处理
  730. $(this).text("翻译中");
  731. $(this).css("cursor", "not-allowed");
  732. var element_node = $("div.problem-statement").children(':eq(2)').get(0);
  733. await translateProblemStatement(textarea.value, element_node);
  734. //
  735. $(this).addClass("translated");
  736. $(this).text("已翻译");
  737. $(this).prop("disabled",true);
  738. });
  739. // **Input**
  740. // 添加按钮
  741. $("div[class='input-specification']").each(function() {
  742. $(this).children(':eq(1)').before(
  743. "<div class='html2md-panel'> <button class='html2mdButton html2md-view2'>MarkDown视图</button> <button class='html2mdButton html2md-cb2'>Copy</button> <button class='html2mdButton translateButton2'>翻译</button> </div>"
  744. );
  745. });
  746.  
  747.  
  748. $(".html2md-cb2").click(function() {
  749. let RelTarget = $(this).parent().parent().get(0);
  750. let target = $(RelTarget).clone(); // 创建副本
  751. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  752. $(target).children(':first').remove();
  753. if (!target.markdown){
  754. target.markdown = turndownService.turndown($(target).html());
  755. }
  756. const textarea = document.createElement('textarea');
  757. textarea.value = target.markdown;
  758. document.body.appendChild(textarea);
  759. textarea.select();
  760. document.execCommand('copy');
  761. document.body.removeChild(textarea);
  762. $(this).addClass("copied");
  763. $(this).text("Copied");
  764. // 更新复制按钮文本
  765. setTimeout(() => {
  766. $(this).removeClass("copied");
  767. $(this).text("Copy");
  768. }, 2000);
  769. $(target).remove();
  770. });
  771.  
  772. $(".html2md-view2").click(function() {
  773. let target = $(this).parent().parent().get(0);
  774. // 临时删除前两个子元素(标题和按钮面板)
  775. var removedChildren = $(this).parent().parent().children().eq(0).add($(this).parent().parent().children().eq(1)).detach();
  776. //
  777. if (target.viewmd) {
  778. target.viewmd = false;
  779. $(this).text("MarkDown视图");
  780. $(this).removeClass("mdViewed");
  781. $(target).html(target.original_html);
  782. } else {
  783. target.viewmd = true;
  784. if (!target.original_html)
  785. target.original_html = $(target).html();
  786. if (!target.markdown)
  787. target.markdown = turndownService.turndown($(target).html());
  788. $(this).text("原始内容");
  789. $(this).addClass("mdViewed");
  790. $(target).html(`<span class="mdViewContent oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;"> ${target.markdown} </span>`);
  791. }
  792. // 恢复删除的元素
  793. $(".input-specification").prepend(removedChildren);
  794. });
  795. $(".translateButton2").click(async function() {
  796. let RelTarget = $(this).parent().parent().get(0);
  797. let target = $(RelTarget).clone(); // 创建副本
  798. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  799. $(target).children(':first').remove();
  800. if (!target.markdown){
  801. target.markdown = turndownService.turndown($(target).html());
  802. }
  803. const textarea = document.createElement('textarea');
  804. textarea.value = target.markdown;
  805. // 翻译处理
  806. $(this).text("翻译中");
  807. $(this).css("cursor", "not-allowed");
  808. var element_node = $("div.input-specification").get(0);
  809. await translateProblemStatement(textarea.value, element_node);
  810. //
  811. $(this).addClass("translated");
  812. $(this).text("已翻译");
  813. $(this).prop("disabled",true);
  814. $(target).remove();
  815. });
  816. // **Output**
  817. // 添加按钮
  818. $("div[class='output-specification']").each(function() {
  819. $(this).children(':eq(1)').before(
  820. "<div class='html2md-panel'> <button class='html2mdButton html2md-view3'>MarkDown视图</button> <button class='html2mdButton html2md-cb3'>Copy</button> <button class='html2mdButton translateButton3'>翻译</button> </div>"
  821. );
  822. });
  823.  
  824.  
  825. $(".html2md-cb3").click(function() {
  826. let RelTarget = $(this).parent().parent().get(0);
  827. let target = $(RelTarget).clone(); // 创建副本
  828. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  829. $(target).children(':first').remove();
  830. if (!target.markdown){
  831. target.markdown = turndownService.turndown($(target).html());
  832. }
  833. const textarea = document.createElement('textarea');
  834. textarea.value = target.markdown;
  835. document.body.appendChild(textarea);
  836. textarea.select();
  837. document.execCommand('copy');
  838. document.body.removeChild(textarea);
  839. $(this).addClass("copied");
  840. $(this).text("Copied");
  841. // 更新复制按钮文本
  842. setTimeout(() => {
  843. $(this).removeClass("copied");
  844. $(this).text("Copy");
  845. }, 2000);
  846. $(target).remove();
  847. });
  848.  
  849. $(".html2md-view3").click(function() {
  850. let target = $(this).parent().parent().get(0);
  851. // 临时删除前两个子元素(标题和按钮面板)
  852. var removedChildren = $(this).parent().parent().children().eq(0).add($(this).parent().parent().children().eq(1)).detach();
  853. //
  854. if (target.viewmd) {
  855. target.viewmd = false;
  856. $(this).text("MarkDown视图");
  857. $(this).removeClass("mdViewed");
  858. $(target).html(target.original_html);
  859. } else {
  860. target.viewmd = true;
  861. if (!target.original_html)
  862. target.original_html = $(target).html();
  863. if (!target.markdown)
  864. target.markdown = turndownService.turndown($(target).html());
  865. $(this).text("原始内容");
  866. $(this).addClass("mdViewed");
  867. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;"> ${target.markdown} </span>`);
  868. }
  869. // 恢复删除的元素
  870. $(".output-specification").prepend(removedChildren);
  871. });
  872. $(".translateButton3").click(async function() {
  873. let RelTarget = $(this).parent().parent().get(0);
  874. let target = $(RelTarget).clone(); // 创建副本
  875. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  876. $(target).children(':first').remove();
  877. if (!target.markdown){
  878. target.markdown = turndownService.turndown($(target).html());
  879. }
  880. const textarea = document.createElement('textarea');
  881. textarea.value = target.markdown;
  882. // 翻译处理
  883. $(this).text("翻译中");
  884. $(this).css("cursor", "not-allowed");
  885. var element_node = $("div.output-specification").get(0);
  886. await translateProblemStatement(textarea.value, element_node);
  887. //
  888. $(this).addClass("translated");
  889. $(this).text("已翻译");
  890. $(this).prop("disabled",true);
  891. $(target).remove();
  892. });
  893. };
  894.  
  895. // **翻译框/翻译处理器**
  896. var translatedText = "";
  897. async function translateProblemStatement(text, element_node){
  898. let id = Math.floor(Date.now() / 1000);
  899. let matches;
  900. let replacements;
  901. // 创建元素并放在element_node的后面
  902. const translateDiv = document.createElement('div');
  903. translateDiv.setAttribute('id', id);
  904. translateDiv.classList.add('translate-problem-statement');
  905. const spanElement = document.createElement('span');
  906. translateDiv.appendChild(spanElement);
  907. element_node.insertAdjacentElement('afterend', translateDiv);
  908. // 替换latex公式
  909. if(getCookie("translation")!= "api2d"&&getCookie("translation")!= "openai"){
  910. matches = text.match(/\$(.*?)\$/g);
  911. replacements = {};
  912. try{
  913. for (let i = 0; i < matches.length; i++) {
  914. let match = matches[i];
  915. text = text.replace(match, `【${i + 1}】`);
  916. replacements[`【${i + 1}】`] = match;
  917. }
  918. }catch(e){}
  919. text = text.replace(/\\/g, "");
  920. }
  921. // 翻译
  922. var translation = getCookie("translation");
  923. if(translation == "deepl") {
  924. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  925. translatedText = await translate_deepl(text);
  926. }else if (translation == "youdao" ){
  927. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  928. translatedText = await translate_youdao_mobile(text);
  929. }else if (translation == "baidu") {
  930. var baidu_appid = getCookie("baidu_uid");
  931. var baidu_key = getCookie("baidu_key");
  932. } else if (translation == "openai") {
  933. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  934. translatedText = await translate_openai(text);
  935. } else if (translation == "api2d") {
  936. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  937. translatedText = await translate_api2d(text);
  938. }
  939. // 还原latex公式
  940. if(getCookie("translation")!= "api2d"&&getCookie("translation")!= "openai"){
  941. try{
  942. for (let i = 0; i < matches.length; i++) {
  943. let match = matches[i];
  944. let replacement = replacements[`【${i + 1}】`];
  945. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  946. }
  947. }catch(e){}
  948. }
  949. // 使符合mathjx的转换语法
  950. translatedText = translatedText.replace(/\$/g, "$$$$$$");
  951. //
  952. // 更新
  953. translateDiv.textContent = translatedText;
  954. // 渲染Latex
  955. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  956. }
  957.  
  958. // ChatGPT
  959. async function translate_openai(raw) {
  960. var openai_key = getCookie("openai_key");
  961. var openai_retext = "";
  962. const data = {
  963. prompt: "(You:请帮我翻译将下面的文本翻译为中文,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n"+ raw + ")",
  964. max_tokens: 2048,
  965. model: "text-davinci-003",
  966. }
  967. return new Promise(function(resolve, reject) {
  968. GM_xmlhttpRequest({
  969. method: 'POST',
  970. url: 'https://api.openai.com/v1/completions',
  971. data: JSON.stringify(data),
  972. headers: {
  973. 'Content-Type': 'application/json',
  974. 'Authorization': 'Bearer ' + getCookie("openai_key") + ''
  975. },
  976. responseType: 'json',
  977. onload: function (res) {
  978. if (res.status === 200) {
  979. openai_retext = res.response.choices[0].text;
  980. openai_retext = openai_retext.replace(/^\s+/, '');
  981. resolve(openai_retext);
  982. }
  983. else {
  984. console.error(res.statusText);
  985. reject(res.statusText);
  986. }
  987. }
  988. });
  989. });
  990. }
  991.  
  992. // api2d
  993. async function translate_api2d(raw) {
  994. var api2d_key = getCookie("api2d_key");
  995. var api2d_retext = "";
  996. const postData = JSON.stringify({
  997. model: 'gpt-3.5-turbo',
  998. messages: [{ role: 'user', content: '请帮我翻译将下面的文本翻译为中文,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n'+ raw }],
  999. });
  1000.  
  1001. const options = {
  1002. method: 'POST',
  1003. headers: {
  1004. 'Content-Type': 'application/json',
  1005. Authorization: 'Bearer '+api2d_key,
  1006. },
  1007. data: postData,
  1008. };
  1009.  
  1010. return new Promise(function(resolve, reject) {
  1011. GM_xmlhttpRequest({
  1012. method: options.method,
  1013. url: `https://openai.api2d.net/v1/chat/completions`,
  1014. headers: options.headers,
  1015. data: options.data,
  1016. responseType: 'json',
  1017. onload: function (response) {
  1018. api2d_retext = response.response.choices[0].message.content;
  1019. resolve(api2d_retext);
  1020. },
  1021. onerror: function (response) {
  1022. console.error(response.statusText);
  1023. reject(response.statusText);
  1024. },
  1025. });
  1026. });
  1027. }
  1028. //
  1029.  
  1030. //--有道翻译m--start
  1031. async function translate_youdao_mobile(raw){
  1032. const options = {
  1033. method:"POST",
  1034. url:'http://m.youdao.com/translate',
  1035. data:"inputtext="+encodeURIComponent(raw)+"&type=AUTO",
  1036. anonymous:true,
  1037. headers: {
  1038. "Content-Type": "application/x-www-form-urlencoded"
  1039. }
  1040. }
  1041. return await BaseTranslate('有道翻译mobile',raw,options,res=>/id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1042. }
  1043. //--有道翻译m--end
  1044.  
  1045. //--Deepl翻译--start
  1046. function getTimeStamp(iCount) {
  1047. const ts = Date.now();
  1048. if (iCount !== 0) {
  1049. iCount = iCount + 1;
  1050. return ts - (ts % iCount) + iCount;
  1051. } else {
  1052. return ts;
  1053. }
  1054. }
  1055.  
  1056. async function translate_deepl(raw) {
  1057. const id = (Math.floor(Math.random() * 99999) + 100000)* 1000;
  1058. const data = {
  1059. jsonrpc: '2.0',
  1060. method: 'LMT_handle_texts',
  1061. id,
  1062. params: {
  1063. splitting: 'newlines',
  1064. lang: {
  1065. source_lang_user_selected: 'auto',
  1066. target_lang: 'ZH',
  1067. },
  1068. texts: [{
  1069. text: raw,
  1070. requestAlternatives:3
  1071. }],
  1072. timestamp: getTimeStamp(raw.split('i').length - 1)
  1073. }
  1074. }
  1075. let postData = JSON.stringify(data);
  1076. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1077. postData = postData.replace('"method":"', '"method" : "');
  1078. } else {
  1079. postData = postData.replace('"method":"', '"method": "');
  1080. }
  1081. const options = {
  1082. method: 'POST',
  1083. url: 'https://www2.deepl.com/jsonrpc',
  1084. data: postData,
  1085. headers: {
  1086. 'Content-Type': 'application/json',
  1087. 'Host': 'www.deepl.com',
  1088. 'Origin': 'https://www.deepl.com',
  1089. 'Referer': 'https://www.deepl.com/'
  1090. },
  1091. anonymous:true,
  1092. nocache:true,
  1093. }
  1094. return await BaseTranslate('Deepl翻译',raw,options,res=>JSON.parse(res).result.texts[0].text)
  1095. }
  1096.  
  1097. //--Deepl翻译--end
  1098.  
  1099. // **Cookie Get/Set**
  1100. function setCookie(cname, cvalue, exdays) {
  1101. var d = new Date();
  1102. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  1103. var expires = "expires=" + d.toUTCString();
  1104. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  1105. }
  1106.  
  1107. function getCookie(cname) {
  1108. var name = cname + "=";
  1109. var decodedCookie = decodeURIComponent(document.cookie);
  1110. var ca = decodedCookie.split(';');
  1111. for (var i = 0; i < ca.length; i++) {
  1112. var c = ca[i];
  1113. while (c.charAt(0) == ' ') {
  1114. c = c.substring(1);
  1115. }
  1116. if (c.indexOf(name) == 0) {
  1117. return c.substring(name.length, c.length);
  1118. }
  1119. }
  1120. return "";
  1121. }
  1122.  
  1123.  
  1124. //--异步请求包装工具--start
  1125. async function PromiseRetryWrap(task,options,...values){
  1126. const {RetryTimes,ErrProcesser} = options||{};
  1127. let retryTimes = RetryTimes||5;
  1128. const usedErrProcesser = ErrProcesser || (err =>{throw err});
  1129. if(!task)return;
  1130. while(true){
  1131. try{
  1132. return await task(...values);
  1133. }catch(err){
  1134. if(!--retryTimes){
  1135. console.log(err);
  1136. return usedErrProcesser(err);
  1137. }
  1138. }
  1139. }
  1140. }
  1141.  
  1142. async function BaseTranslate(name,raw,options,processer){
  1143. const toDo = async ()=>{
  1144. var tmp;
  1145. try{
  1146. const data = await Request(options);
  1147. tmp = data.responseText;
  1148. const result = await processer(tmp);
  1149. if(result)sessionStorage.setItem(name+'-'+raw,result);
  1150. return result
  1151. }catch(err){
  1152. throw {
  1153. responseText: tmp,
  1154. err: err
  1155. }
  1156. }
  1157. }
  1158. return await PromiseRetryWrap(toDo,{RetryTimes:3,ErrProcesser:()=>"翻译出错"})
  1159. }
  1160.  
  1161. function Request(options){
  1162. return new Promise((reslove,reject)=>GM_xmlhttpRequest({...options,onload:reslove,onerror:reject}))
  1163. }
  1164.  
  1165. //--异步请求包装工具--end