Greasy Fork 还支持 简体中文。

Codeforces Better!

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

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

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