// ==UserScript== // @name 雨课堂 OCR 文字识别助手 // @namespace rainclassroom-ocr-helper // @version 1.0.0 // @description 框选雨课堂页面可见文字,中文OCR识别并编辑复制 // @match *://*.yuketang.cn/* // @match *://yuketang.cn/* // @match *://*.xuetangx.com/* // @match *://xuetangx.com/* // @run-at document-idle // @grant none // @require https://cdn.jsdelivr.net/npm/tesseract.js@5.1.1/dist/tesseract.min.js // @license MIT // ==/UserScript== (function () { 'use strict'; if (window.__rainOCRInstalled) return; window.__rainOCRInstalled = true; const state = { stream: null, video: null, worker: null, overlay: null, modal: null, textarea: null, status: null, lastCanvas: null }; // ========================= // 页面样式 // ========================= const style = document.createElement('style'); style.textContent = ` #rain-ocr-button { position: fixed; right: 22px; bottom: 24px; z-index: 2147483646; border: none; border-radius: 24px; padding: 13px 21px; background: #2563eb; color: white; font-size: 14px; font-weight: bold; cursor: pointer; box-shadow: 0 4px 15px #0004; } #rain-ocr-button:hover { background: #1d4ed8; } #rain-ocr-overlay { position: fixed; inset: 0; z-index: 2147483647; background: rgba(0,0,0,.20); cursor: crosshair; touch-action: none; } #rain-ocr-hint { position: absolute; top: 20px; left: 50%; transform: translateX(-50%); padding: 12px 20px; border-radius: 10px; background: #172554; color: white; font-size: 14px; pointer-events: none; white-space: nowrap; } #rain-ocr-selection { position: absolute; border: 2px dashed #2563eb; background: rgba(37,99,235,.12); pointer-events: none; } #rain-ocr-modal { position: fixed; inset: 0; z-index: 2147483647; background: rgba(0,0,0,.55); display: flex; justify-content: center; align-items: center; padding: 15px; box-sizing: border-box; } #rain-ocr-dialog { width: min(850px, 96vw); max-height: 90vh; background: white; color: #222; border-radius: 14px; padding: 20px; box-sizing: border-box; display: flex; flex-direction: column; gap: 12px; box-shadow: 0 10px 40px #0005; } #rain-ocr-dialog h3 { margin: 0; font-size: 19px; } #rain-ocr-status { font-size: 13px; color: #2563eb; } #rain-ocr-text { width: 100%; height: 300px; min-height: 160px; resize: vertical; box-sizing: border-box; border: 1px solid #cbd5e1; border-radius: 8px; padding: 12px; font-size: 15px; line-height: 1.8; color: #222; background: white; outline: none; } #rain-ocr-text:focus { border-color: #2563eb; } #rain-ocr-preview { max-height: 150px; max-width: 100%; object-fit: contain; align-self: flex-start; border: 1px solid #ddd; } .rain-ocr-actions { display: flex; flex-wrap: wrap; gap: 9px; } .rain-ocr-actions button { border: none; border-radius: 7px; padding: 10px 17px; cursor: pointer; font-size: 14px; } #rain-ocr-copy { background: #2563eb; color: white; } #rain-ocr-again { background: #e2e8f0; color: #222; } #rain-ocr-close { background: #fee2e2; color: #991b1b; } .rain-ocr-tip { font-size: 12px; color: #64748b; } `; document.head.appendChild(style); // ========================= // 悬浮按钮 // ========================= const button = document.createElement('button'); button.id = 'rain-ocr-button'; button.textContent = '识别页面文字'; document.body.appendChild(button); button.addEventListener('click', startCapture); // ========================= // 开始屏幕捕获 // ========================= async function startCapture() { try { if (!navigator.mediaDevices?.getDisplayMedia) { throw new Error('当前浏览器不支持屏幕捕获,请使用新版 Chrome 或 Edge。'); } button.disabled = true; button.textContent = '等待选择页面...'; // 优先提示浏览器选择当前标签页 const stream = await navigator.mediaDevices.getDisplayMedia({ video: { frameRate: 15 }, audio: false, preferCurrentTab: true }); state.stream = stream; const track = stream.getVideoTracks()[0]; const settings = track.getSettings(); // 防止误选整个显示器或其他窗口 if (settings.displaySurface && settings.displaySurface !== 'browser') { stopCapture(); alert('请重新操作,并在分享窗口中选择雨课堂当前浏览器标签页。'); return; } const video = document.createElement('video'); video.muted = true; video.playsInline = true; video.style.cssText = 'position:fixed;left:-9999px;width:1px;height:1px;opacity:0;'; document.body.appendChild(video); video.srcObject = stream; if (video.readyState < 1) { await new Promise(resolve => { video.onloadedmetadata = resolve; }); } await video.play(); state.video = video; track.addEventListener('ended', () => { if (state.stream === stream) stopCapture(); }, { once: true }); button.textContent = '正在选择区域...'; beginSelection(); } catch (error) { console.error('[RainOCR]', error); alert('启动失败:' + (error.message || error)); stopCapture(); } finally { button.disabled = false; button.textContent = '识别页面文字'; } } // ========================= // 鼠标框选区域 // ========================= function beginSelection() { if (!state.stream || !state.video) return; const overlay = document.createElement('div'); overlay.id = 'rain-ocr-overlay'; const hint = document.createElement('div'); hint.id = 'rain-ocr-hint'; hint.textContent = '按住鼠标左键,拖动框选要识别的文字区域'; const box = document.createElement('div'); box.id = 'rain-ocr-selection'; overlay.append(hint, box); document.body.appendChild(overlay); state.overlay = overlay; let startX = 0; let startY = 0; let dragging = false; function updateBox(x, y) { const left = Math.min(startX, x); const top = Math.min(startY, y); const width = Math.abs(x - startX); const height = Math.abs(y - startY); box.style.left = left + 'px'; box.style.top = top + 'px'; box.style.width = width + 'px'; box.style.height = height + 'px'; } overlay.addEventListener('pointerdown', event => { if (event.button !== 0) return; event.preventDefault(); startX = event.clientX; startY = event.clientY; dragging = true; overlay.setPointerCapture(event.pointerId); updateBox(startX, startY); }); overlay.addEventListener('pointermove', event => { if (!dragging) return; updateBox(event.clientX, event.clientY); }); overlay.addEventListener('pointerup', async event => { if (!dragging) return; dragging = false; const endX = event.clientX; const endY = event.clientY; const rect = { left: Math.min(startX, endX), top: Math.min(startY, endY), width: Math.abs(endX - startX), height: Math.abs(endY - startY) }; if (rect.width < 12 || rect.height < 12) { hint.textContent = '区域太小,请重新框选文字'; return; } overlay.remove(); state.overlay = null; await new Promise(resolve => setTimeout(resolve, 250)); captureRegion(rect); }); overlay.addEventListener('contextmenu', event => { event.preventDefault(); overlay.remove(); state.overlay = null; stopCapture(); }); } // ========================= // 截取框选区域 // ========================= function captureRegion(rect) { const video = state.video; if (!video || !video.videoWidth) { alert('没有获取到页面画面,请重新操作。'); stopCapture(); return; } const scaleX = video.videoWidth / window.innerWidth; const scaleY = video.videoHeight / window.innerHeight; const sx = Math.round(rect.left * scaleX); const sy = Math.round(rect.top * scaleY); const sw = Math.round(rect.width * scaleX); const sh = Math.round(rect.height * scaleY); const canvas = document.createElement('canvas'); canvas.width = Math.max(1, sw); canvas.height = Math.max(1, sh); const ctx = canvas.getContext('2d'); ctx.drawImage( video, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height ); state.lastCanvas = canvas; showEditor(canvas); recognize(canvas); } // ========================= // 识别结果编辑窗口 // ========================= function showEditor(canvas) { if (state.modal) state.modal.remove(); const modal = document.createElement('div'); modal.id = 'rain-ocr-modal'; modal.innerHTML = `

雨课堂文字识别结果

正在准备中文识别引擎...
识别区域预览
OCR 可能存在错别字,请检查后再复制。 按 ESC 可以关闭窗口并结束捕获。
`; document.body.appendChild(modal); state.modal = modal; state.textarea = modal.querySelector('#rain-ocr-text'); state.status = modal.querySelector('#rain-ocr-status'); modal.querySelector('#rain-ocr-preview').src = canvas.toDataURL('image/png'); modal.querySelector('#rain-ocr-copy') .addEventListener('click', copyResult); modal.querySelector('#rain-ocr-again') .addEventListener('click', () => { modal.remove(); state.modal = null; beginSelection(); }); modal.querySelector('#rain-ocr-close') .addEventListener('click', stopCapture); } // ========================= // 中文 OCR 识别 // ========================= async function recognize(canvas) { try { if (!window.Tesseract) { throw new Error('OCR 引擎加载失败,请检查网络和脚本猫 @require 设置。'); } state.status.textContent = '正在加载中文识别引擎,请稍候...'; if (!state.worker) { state.worker = await Tesseract.createWorker( 'chi_sim+eng', 1, { logger: message => { if (!state.status) return; if (message.status) { const percent = message.progress ? Math.round(message.progress * 100) + '%' : ''; state.status.textContent = message.status + ' ' + percent; } } } ); await state.worker.setParameters({ preserve_interword_spaces: '1' }); } state.status.textContent = '正在识别文字...'; const result = await state.worker.recognize(canvas); const text = result.data.text || ''; state.textarea.value = text.trim(); const confidence = Math.round( result.data.confidence || 0 ); state.status.textContent = '识别完成!参考置信度:' + confidence + '%。请检查文字。'; state.textarea.focus(); } catch (error) { console.error('[RainOCR]', error); if (state.status) { state.status.textContent = '识别失败:' + (error.message || error); } } } // ========================= // 复制结果 // ========================= async function copyResult() { const text = state.textarea?.value || ''; if (!text.trim()) { alert('当前没有识别结果。'); return; } try { await navigator.clipboard.writeText(text); } catch (error) { state.textarea.focus(); state.textarea.select(); const success = document.execCommand('copy'); if (!success) { alert('自动复制失败,请手动 Ctrl+C。'); return; } } state.status.textContent = '已复制,可以粘贴到 Word!'; } // ========================= // 结束与清理 // ========================= function stopCapture() { if (state.overlay) { state.overlay.remove(); state.overlay = null; } if (state.modal) { state.modal.remove(); state.modal = null; } if (state.video) { state.video.pause(); state.video.srcObject = null; state.video.remove(); state.video = null; } if (state.stream) { state.stream.getTracks().forEach(track => track.stop()); state.stream = null; } state.textarea = null; state.status = null; state.lastCanvas = null; } document.addEventListener('keydown', event => { if (event.key === 'Escape' && state.stream) { stopCapture(); } }); window.addEventListener('beforeunload', () => { if (state.stream) { state.stream.getTracks().forEach(track => track.stop()); } if (state.worker) { state.worker.terminate(); } }); console.log('[RainOCR] 雨课堂 OCR 助手已启动'); })();