Codeforces Better!

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

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

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