Codeforces Better!

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

目前为 2023-05-12 提交的版本。查看 最新版本

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