Codeforces Better!

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

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

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