@mytools-all/mytools-ocr 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MyTools Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # 图片 OCR
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 版本 0.2.0。使用独立运行的 Umi-OCR HTTP 服务,免登录、离线识别;仓库 mytools-ocr 与 npm 包名 @mytools-all/mytools-ocr 保持不变。已完整替换旧云端调用,不再读取旧版本云端凭据或发送云端识别请求。
4
+
5
+ ## 使用
6
+
7
+ 1. 下载并运行 Umi-OCR(本机已验证接口版本 2.1.5)。在全局设置开启 HTTP 服务,主机 127.0.0.1,默认端口 1224。
8
+ 2. 从 MyTools 打开“图片 OCR”,在“设置 → 本机服务”检查连接。端口有变化时保存新地址,只接受本机 HTTP 地址。
9
+ 3. 选择、拖入或粘贴 JPG / PNG / BMP 图片(最多 3 MB),默认自动开始本地识别,关闭自动识别后点击“开始本地识别”。也接受面板传入的图片上下文。
10
+ 4. 结果可编辑、合并行、复制或导出 TXT。最近 30 次识别文字保存在本机,关闭后仍保留;总量最多 1 MiB,不保存原图。历史页支持确认清空和失败重试。
11
+
12
+ Umi-OCR 需保持运行;插件不硬编码程序安装路径、不自动修改开机启动项。自动识别默认开启:仅插件页面打开时,通过声明并授权的 clipboard.read 读取新复制的图片,经宿主 net.fetch 发给本机;从面板截图、选择、拖入或粘贴图片也自动识别。在设置中关闭后可手动识别。关闭插件后停止监听,不后台识别。请求串行执行;模型首次加载或大图可能超过宿主 15 秒请求超时,稍后可重试,超时不会自动重复提交。表格还原、公式和文档 PDF 不在本插件当前范围内。
13
+
14
+ ## 安装与开发
15
+
16
+ 执行 npm install --ignore-scripts、npm test、npm pack,通过 MyTools 安装生成的插件包。修改源码不会自动更新已安装目录。在开发者页面也可安装 @mytools-all/mytools-ocr@0.2.0。
17
+
18
+ 使用公开 API:context.read、net.fetch、storage.get/set(键 umi.settings.v1)、clipboard.read/write、fs.exporttext。不直调 Tauri,不依赖主程序私有实现。Umi-OCR 是外部软件,本插件不捆绑其程序、模型或运行环境。
19
+
20
+ ## 许可
21
+
22
+ 插件代码 MIT。外部 Umi-OCR 的许可与发行说明见 https://github.com/hiroi-sora/Umi-OCR 。
23
+
24
+ 本版本需配合提供 clipboard.read 图片类型和面板截图入口的新宿主。新增设置 autoRecognize 与旧地址配置兼容,旧版仅会话保存的记录无法自动恢复。
25
+
26
+ 0.2.0 将识别历史置于设置前。连接被拒绝或网络不可达时提示下载安装 Umi-OCR,默认聚焦“否,我不安装”;Esc 可关闭,同一轮连续失败只提示一次。确认安装仅打开官方发布页,不自动执行安装程序。权限拒绝、识别超时与普通识别错误不当作未安装处理。
package/THIRD_PARTY.md ADDED
@@ -0,0 +1,3 @@
1
+ # 第三方说明
2
+
3
+ 本插件不携带第三方运行库或模型,不再使用 MD5 签名库。通过本机 HTTP 接口与用户独立安装的 Umi-OCR 通信,不复制或分发其实现。Umi-OCR 的软件、引擎和模型许可见其官方仓库:https://github.com/hiroi-sora/Umi-OCR 。插件自身代码遵循本仓库 MIT LICENSE。
package/app.mjs ADDED
@@ -0,0 +1,94 @@
1
+ import {DEFAULT_ENDPOINT,endpoint,imageBase64,responseJson,resultText,friendlyError,isConnectionFailure,UMI_DOWNLOAD_URL} from './umi.mjs';
2
+ import {readHistory,appendHistory,historyPayload} from './history.mjs';
3
+ export function createOcr(doc,api) {
4
+ const $=id=>doc.getElementById(id),win=doc.defaultView;
5
+ let installPrompted=false,openingDownload=false;
6
+ let image='',fileName='',history=[],busy=false,loaded=false,started=false,disposed=false,revision=0;
7
+ let beforeMerge='',mergedValue='',auto=true,lastSequence,lastSeen='',pending=null,polling=false,timer,pollStopped=false,historyWritable=true,historyDirty=false;
8
+ const status=(text,error=false)=>{if(!disposed){$('status').textContent=text;$('status').dataset.error=String(error);}};
9
+ const call=async(id,args={})=>{if(!api)throw Error('请从 MyTools 打开图片 OCR');return api.call(id,args);};
10
+ const action=fn=>async(...args)=>{try{return await fn(...args);}catch(e){status(friendlyError(e),true);}};
11
+
12
+ function offerInstall(){
13
+ if(disposed||installPrompted)return;
14
+ installPrompted=true;
15
+ $('install-dialog').showModal();
16
+ $('install-no').focus();
17
+ }
18
+ async function requestUmi(args){
19
+ try{const response=await call('net.fetch',args);installPrompted=false;return response;}
20
+ catch(error){if(isConnectionFailure(error))offerInstall();throw error;}
21
+ }
22
+ $('install-dialog').oncancel=()=>{$('install-dialog').close();};
23
+ $('install-no').onclick=()=>{$('install-dialog').close();};
24
+ $('install-yes').onclick=action(async()=>{
25
+ if(openingDownload)return;openingDownload=true;$('install-yes').disabled=true;
26
+ try{await call('shell.open',{url:UMI_DOWNLOAD_URL});$('install-dialog').close();status('已打开 Umi-OCR 官方下载页,下载安装并运行后,请返回检查连接');}
27
+ finally{openingDownload=false;$('install-yes').disabled=false;}
28
+ });
29
+ function tab(id){for(const name of ['recognize','settings','history']){$(name).classList.toggle('hidden',name!==id);$(name+'-tab').classList.toggle('active',name===id);}if(id==='history')renderHistory();}
30
+ function lock(value){busy=value;doc.querySelectorAll('[data-lock]').forEach(n=>n.disabled=value||!loaded);}
31
+ async function task(fn){if(busy||disposed)return;lock(true);try{await fn();}finally{lock(false);if(pending&&!disposed){const next=pending;pending=null;queueMicrotask(()=>action(()=>acceptImage(next.image,next.name))());}}}
32
+ function showText(text){beforeMerge=text;mergedValue=text.replace(/\r?\n/g,'');$('result').value=$('merge').checked?mergedValue:text;}
33
+ function setImage(value,name){imageBase64(value);image=value;fileName=name;lastSeen=value;revision++;$('image').src=value;$('image').hidden=false;showText('');tab('recognize');status(name+' · '+(auto?'即将本地识别':'点击识别发送到本机 Umi-OCR'));}
34
+ async function acceptImage(value,name){if(disposed)return;if(busy){pending={image:value,name};return;}setImage(value,name);if(auto)await run();}
35
+ async function loadFile(file){
36
+ if(!file)return;if(busy)throw Error('请等待当前操作完成');
37
+ if(!['image/png','image/jpeg','image/bmp'].includes(file.type))throw Error('仅支持 JPG / PNG / BMP 图片');
38
+ if(file.size>3*1024*1024)throw Error('图片不能超过 3 MB');
39
+ let value;await task(async()=>{value=await new Promise((resolve,reject)=>{const reader=new win.FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=()=>reject(Error('图片读取失败'));reader.readAsDataURL(file);});});
40
+ if(value)await acceptImage(value,file.name||'粘贴的图片');
41
+ }
42
+ async function saveHistory(){if(!historyWritable)throw Error('原历史数据读取失败,未覆盖;可在历史页重试读取');await call('storage.set',{key:'umi.history.v1',value:historyPayload(history)});historyDirty=false;$('retry-history').hidden=true;}
43
+ async function run(){return task(async()=>{
44
+ if(!image)throw Error('请先选择、拖入或粘贴图片');
45
+ const base=endpoint($('endpoint').value.trim()),base64=imageBase64(image),name=fileName;status('正在本机识别…首次识别需加载模型');
46
+ const data=responseJson(await requestUmi({url:base+'/api/ocr',method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({base64,options:{'data.format':'text','tbpu.parser':'multi_para'}})}));
47
+ if(disposed)return;const text=resultText(data);pollStopped=false;showText(text);
48
+ if(!text.trim()){status('未识别到文字,请检查图片清晰度');return;}
49
+ try{history=appendHistory(history,{name,time:Date.now(),text});historyDirty=true;await saveHistory();status('本机识别完成 · '+text.length+' 字符 · 已保存历史');}
50
+ catch(error){$('retry-history').hidden=false;status('识别成功;'+friendlyError(error),true);}
51
+ });}
52
+ for(const name of ['recognize','settings','history'])$(name+'-tab').onclick=()=>tab(name);
53
+ $('endpoint').value=DEFAULT_ENDPOINT;$('auto-recognize').checked=true;
54
+ $('choose').onclick=()=>{if(!busy)$('file').click();};$('file').onchange=action(()=>{const file=$('file').files[0];$('file').value='';return loadFile(file);});
55
+ $('drop').ondragover=e=>{e.preventDefault();$('drop').classList.add('over');};$('drop').ondragleave=()=>$('drop').classList.remove('over');$('drop').ondrop=action(e=>{e.preventDefault();$('drop').classList.remove('over');return loadFile(e.dataTransfer.files[0]);});
56
+ doc.addEventListener('paste',action(e=>{const item=[...(e.clipboardData?.items||[])].find(i=>i.type.startsWith('image/'));if(item){e.preventDefault();return loadFile(item.getAsFile());}}));
57
+ async function persistSettings(){const base=endpoint($('endpoint').value.trim()),wanted=$('auto-recognize').checked;await call('storage.set',{key:'umi.settings.v1',value:{endpoint:base,autoRecognize:wanted}});auto=wanted;if(!auto)pending=null;pollStopped=false;$('endpoint').value=base;restartPolling();status('设置已保存');}
58
+ $('save').onclick=action(()=>task(persistSettings));
59
+ $('auto-recognize').onchange=action(async()=>{try{await task(persistSettings);}catch(error){$('auto-recognize').checked=auto;throw error;}});
60
+ $('test').onclick=action(()=>task(async()=>{installPrompted=false;const base=endpoint($('endpoint').value.trim());status('正在检查本机 Umi-OCR…');const data=responseJson(await requestUmi({url:base+'/api/ocr/get_options',method:'GET'}));if(!data||typeof data!=='object'||!data['data.format']||!data['tbpu.parser'])throw Error('该地址不是兼容的 Umi-OCR 服务');status('Umi-OCR 连接成功,可以开始识别');}));
61
+ $('run').onclick=action(()=>{if(!busy)installPrompted=false;return run();});
62
+ $('merge').onchange=()=>{if($('merge').checked){beforeMerge=$('result').value;mergedValue=beforeMerge.replace(/\r?\n/g,'');$('result').value=mergedValue;}else if($('result').value===mergedValue)$('result').value=beforeMerge;};
63
+ $('copy').onclick=action(async()=>{if(!$('result').value)throw Error('没有可复制的识别文字');await call('clipboard.write',{text:$('result').value});status('文字已复制');});
64
+ $('export').onclick=action(async()=>{if(!$('result').value)throw Error('没有可导出的识别文字');const result=await call('fs.exporttext',{name:'图片OCR-识别结果.txt',content:$('result').value});status(result?.cancelled?'已取消导出':'识别文字已导出');});
65
+ function renderHistory(){const list=$('history-list');list.replaceChildren();$('history-count').textContent=history.length+' 条本地历史(最多 30 条)';$('retry-history').hidden=!historyDirty&&historyWritable;if(!history.length){list.textContent='暂无识别历史,成功识别后会保存到本机。';return;}for(const entry of history){const b=doc.createElement('button');b.className='history-entry';b.textContent=entry.name+' · '+new Date(entry.time).toLocaleString()+'\n'+entry.text.slice(0,100);b.onclick=()=>{if(busy)return;showText(entry.text);tab('recognize');};list.append(b);}}
66
+ $('clear-history').onclick=action(()=>task(async()=>{if(!$('confirm-clear-history').checked)throw Error('请先勾选确认清空历史');if(!historyWritable)throw Error('历史数据异常,已停止覆盖');await call('storage.set',{key:'umi.history.v1',value:historyPayload([])});history=[];historyDirty=false;$('confirm-clear-history').checked=false;renderHistory();status('识别历史已清空');}));
67
+ $('retry-history').onclick=action(()=>task(async()=>{if(!historyWritable){history=readHistory(await call('storage.get',{key:'umi.history.v1'}));historyWritable=true;}else await saveHistory();renderHistory();status('历史记录已恢复');}));
68
+ async function pollClipboard(){
69
+ if(!loaded||!auto||disposed||polling||pollStopped)return;polling=true;const token=revision;
70
+ try{const data=await call('clipboard.read',{types:['image'],...(lastSequence===undefined?{}:{sequence:lastSequence})});
71
+ lastSequence=data?.sequence??undefined;if(disposed||!auto||data?.unchanged||!data?.image?.dataUrl)return;
72
+ const value=data.image.dataUrl;imageBase64(value);if(value===lastSeen)return;if(token!==revision&&!busy)return;
73
+ lastSeen=value;if(busy)pending={image:value,name:'新复制的图片'};else await acceptImage(value,'新复制的图片');
74
+ }catch(error){if(!disposed){pollStopped=true;status('自动识别已暂停:'+friendlyError(error)+';可在设置中重新开启',true);}}
75
+ finally{polling=false;}
76
+ }
77
+ function restartPolling(){if(timer)win.clearInterval(timer);timer=undefined;if(auto&&api&&!disposed){timer=win.setInterval(()=>void pollClipboard(),1000);void pollClipboard();}}
78
+ async function init(env){if(started)return;started=true;
79
+ try{const config=await call('storage.get',{key:'umi.settings.v1'});if(config?.autoRecognize!==undefined&&typeof config.autoRecognize!=='boolean')throw Error('自动识别设置格式无效');if(config?.endpoint)$('endpoint').value=endpoint(config.endpoint);auto=config?.autoRecognize!==false;$('auto-recognize').checked=auto;}catch(e){auto=false;$('auto-recognize').checked=false;status('设置读取失败,自动识别暂时关闭,请重新保存设置:'+friendlyError(e),true);}
80
+ try{history=readHistory(await call('storage.get',{key:'umi.history.v1'}));}catch(e){historyWritable=false;status(friendlyError(e),true);}
81
+ loaded=true;lock(false);renderHistory();
82
+ let contextImage;
83
+ if(env?.launchContext)try{const context=await call('context.read',{types:['image']});contextImage=context?.image?.dataUrl;}catch(e){status(friendlyError(e),true);}
84
+ if(contextImage)await action(()=>acceptImage(contextImage,'面板传入的截图'))();else if(historyWritable)status('就绪 · '+(auto?'自动识别已开启,仅在插件打开时监听图片':'自动识别已关闭,可手动开始识别'));
85
+ restartPolling();
86
+ }
87
+ function dispose(){disposed=true;pending=null;if(timer)win.clearInterval(timer);timer=undefined;}
88
+ win.addEventListener('pagehide',dispose);win.addEventListener('beforeunload',dispose);
89
+ $('theme').onclick=()=>{const theme=doc.documentElement.dataset.theme==='dark'?'light':'dark';doc.documentElement.dataset.theme=theme;try{win.localStorage.setItem('tool-theme',theme);}catch{}};
90
+ try{doc.documentElement.dataset.theme=win.localStorage.getItem('tool-theme')||(win.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light');}catch{}
91
+ lock(false);if(api)api.onPluginReady(action(init));else status('预览模式:识别需从 MyTools 打开');
92
+ return {loadFile,init,pollClipboard,dispose,get busy(){return busy;}};
93
+ }
94
+ if(typeof document!=='undefined')createOcr(document,window.mytools);
package/history.mjs ADDED
@@ -0,0 +1,13 @@
1
+ const MAX_BYTES=1024*1024;
2
+ export function readHistory(value){
3
+ if(value===null||value===undefined)return [];
4
+ if(value.version!==1||!Array.isArray(value.entries)||value.entries.length>30||value.entries.some(e=>!e||typeof e.name!=='string'||e.name.length>256||!Number.isFinite(e.time)||typeof e.text!=='string'||!e.text.trim())||new TextEncoder().encode(JSON.stringify(value)).length>MAX_BYTES)throw Error('历史数据格式不支持,已停止覆盖,请先备份原数据');
5
+ return structuredClone(value.entries);
6
+ }
7
+ export function historyPayload(entries){return {version:1,entries};}
8
+ export function appendHistory(entries,entry){
9
+ const next=[{...entry,name:entry.name.slice(0,256)},...entries].slice(0,30);
10
+ while(next.length>1&&new TextEncoder().encode(JSON.stringify(historyPayload(next))).length>MAX_BYTES)next.pop();
11
+ if(new TextEncoder().encode(JSON.stringify(historyPayload(next))).length>MAX_BYTES)throw Error('识别结果过长,未保存到历史,仍可复制或导出');
12
+ return next;
13
+ }
package/index.html ADDED
@@ -0,0 +1,5 @@
1
+ <!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>图片 OCR</title><link rel="stylesheet" href="tool.css"><style>#drop{border:2px dashed var(--border);text-align:center;padding:24px}#drop.over{border-color:var(--accent);background:var(--soft)}.history-entry{display:block;width:100%;text-align:left;margin-bottom:8px;white-space:pre-wrap}.endpoint-input{width:min(100%,420px)}#install-dialog{width:min(440px,90vw);color:var(--fg);background:var(--bg);border:1px solid var(--border);border-radius:12px;padding:22px}#install-dialog::backdrop{background:#0007}#install-dialog h2{font-size:17px}#install-dialog p{line-height:1.7}.install-actions{display:flex;justify-content:flex-end;gap:10px}#install-no{border:2px solid var(--accent)}</style></head><body><main>
2
+ <div class="toolbar"><strong>图片 OCR</strong><div class="tabs"><button id="recognize-tab" class="active">文字识别</button><button id="history-tab">识别历史</button><button id="settings-tab">设置</button></div><span class="spacer"></span><button id="theme">◐</button></div>
3
+ <section id="recognize" style="display:flex;flex-direction:column;flex:1;min-height:0"><div class="split"><div class="content stack"><div id="drop" class="panel" tabindex="0"><p>拖拽图片到这里,或 Ctrl+V 粘贴图片</p><button id="choose" data-lock>选择图片</button><input id="file" type="file" accept="image/png,image/jpeg,image/bmp" hidden data-lock><p class="muted">JPG / PNG / BMP · 最大 3 MB</p><img id="image" style="max-width:100%;max-height:230px" hidden></div><button id="run" class="primary" data-lock>开始本地识别</button><p class="muted">由本机 Umi-OCR 处理,无需登录。</p></div><textarea id="result" data-lock class="editor" placeholder="识别结果将在这里显示,可直接编辑…" aria-label="OCR 识别结果"></textarea></div><div class="toolbar"><label><input id="merge" type="checkbox" data-lock>合并行</label><span class="spacer"></span><button id="copy">复制文字</button><button id="export">导出 TXT</button></div></section>
4
+ <section id="settings" class="content stack hidden"><strong>识别设置</strong><label><input id="auto-recognize" type="checkbox" checked data-lock>复制或载入图片后立即识别</label><p class="muted">默认开启;仅插件打开时监听。关闭插件后不再自动读取或识别图片。</p><h3>本机服务</h3><p class="muted">请先运行 Umi-OCR。在其全局设置中开启 HTTP 服务,主机选择 127.0.0.1。插件仅连接本机地址。</p><label>服务地址 <input id="endpoint" class="endpoint-input" aria-label="Umi-OCR 本机服务地址" placeholder="http://127.0.0.1:1224" data-lock></label><div class="row"><button id="test" data-lock>检查连接</button><button id="save" class="primary" data-lock>保存地址</button></div><p class="muted">默认端口 1224;修改 Umi-OCR 端口后,请同步修改此处。首次识别需加载模型,超时后可重试。</p></section>
5
+ <section id="history" class="content hidden"><p id="history-count"></p><p class="muted">历史保存在本机,仅保存文字,不保存原图。</p><button id="retry-history" hidden data-lock>重试读取 / 保存</button><div id="history-list"></div><label><input id="confirm-clear-history" type="checkbox" data-lock>确认清空所有识别历史</label><button id="clear-history" data-lock>清空历史</button></section><footer id="status" class="status" role="status" aria-live="polite"></footer></main><dialog id="install-dialog" aria-labelledby="install-title"><h2 id="install-title">未检测到 Umi-OCR,是否下载安装?</h2><p>可能尚未安装、未启动,或服务地址不正确。已安装的用户可先启动 Umi-OCR 并检查 HTTP 服务。</p><p>选择安装将打开官方发布页,下载后解压运行即可。</p><div class="install-actions"><button id="install-yes" type="button">是,我要安装</button><button id="install-no" type="button" autofocus>否,我不安装</button></div></dialog><script type="module" src="app.mjs"></script></body></html>
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@mytools-all/mytools-ocr",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "通过本机 Umi-OCR 离线识别图片文字,无需登录",
5
+ "type": "module",
6
+ "main": "index.html",
7
+ "license": "MIT",
8
+ "author": "MyTools Contributors",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/mytools-all/mytools-ocr.git"
12
+ },
13
+ "homepage": "https://github.com/mytools-all/mytools-ocr#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/mytools-all/mytools-ocr/issues"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public",
19
+ "registry": "https://registry.npmjs.org/"
20
+ },
21
+ "files": [
22
+ "plugin.json",
23
+ "index.html",
24
+ "app.mjs",
25
+ "umi.mjs",
26
+ "tool.css",
27
+ "LICENSE",
28
+ "THIRD_PARTY.md",
29
+ "README.md",
30
+ "history.mjs"
31
+ ],
32
+ "devDependencies": {
33
+ "happy-dom": "21.0.4"
34
+ },
35
+ "scripts": {
36
+ "test": "node --test"
37
+ }
6
38
  }
package/plugin.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "mytools-ocr",
3
+ "description": "通过本机 Umi-OCR 离线识别图片文字,无需登录",
4
+ "apiVersion": 1,
5
+ "main": "index.html",
6
+ "pluginName": "图片 OCR",
7
+ "version": "0.2.0",
8
+ "capabilities": [
9
+ "context.read",
10
+ "net.fetch",
11
+ "storage.get",
12
+ "storage.set",
13
+ "clipboard.write",
14
+ "fs.exporttext",
15
+ "clipboard.read",
16
+ "shell.open"
17
+ ],
18
+ "features": [
19
+ {
20
+ "code": "ocr",
21
+ "explain": "打开图片 OCR",
22
+ "cmds": [
23
+ "图片OCR",
24
+ "图片 OCR",
25
+ "OCR",
26
+ "文字识别",
27
+ "图片文字",
28
+ "本地OCR",
29
+ "Umi-OCR"
30
+ ]
31
+ }
32
+ ]
33
+ }
package/tool.css ADDED
@@ -0,0 +1,295 @@
1
+ :root {
2
+ font:
3
+ 13px/1.6 "Segoe UI",
4
+ "Microsoft YaHei",
5
+ sans-serif;
6
+ color-scheme: light;
7
+ --bg: #fff;
8
+ --surface: #f6f7f9;
9
+ --fg: #333b48;
10
+ --muted: #89919e;
11
+ --border: #e8ebf0;
12
+ --accent: #377cf6;
13
+ --soft: #edf3ff;
14
+ --danger: #db4552;
15
+ }
16
+ * {
17
+ box-sizing: border-box;
18
+ }
19
+ body {
20
+ margin: 0;
21
+ color: var(--fg);
22
+ background: var(--bg);
23
+ height: 100vh;
24
+ overflow: hidden;
25
+ }
26
+ button,
27
+ input,
28
+ textarea,
29
+ select {
30
+ font: inherit;
31
+ color: inherit;
32
+ }
33
+ button {
34
+ border: 1px solid var(--border);
35
+ border-radius: 5px;
36
+ background: var(--bg);
37
+ padding: 5px 12px;
38
+ cursor: pointer;
39
+ white-space: nowrap;
40
+ }
41
+ button:hover {
42
+ border-color: var(--accent);
43
+ color: var(--accent);
44
+ }
45
+ button:disabled {
46
+ opacity: 0.45;
47
+ cursor: default;
48
+ }
49
+ .primary {
50
+ background: var(--accent);
51
+ border-color: var(--accent);
52
+ color: white;
53
+ }
54
+ .primary:hover {
55
+ color: white;
56
+ filter: brightness(1.06);
57
+ }
58
+ input,
59
+ textarea,
60
+ select {
61
+ border: 1px solid var(--border);
62
+ border-radius: 4px;
63
+ padding: 7px 9px;
64
+ background: var(--bg);
65
+ min-width: 0;
66
+ }
67
+ textarea {
68
+ resize: none;
69
+ line-height: 1.7;
70
+ tab-size: 2;
71
+ font-family: Consolas, "Microsoft YaHei", monospace;
72
+ }
73
+ input:focus,
74
+ textarea:focus,
75
+ select:focus {
76
+ outline: 1px solid var(--accent);
77
+ }
78
+ button:focus-visible {
79
+ outline: 2px solid var(--accent);
80
+ outline-offset: 2px;
81
+ }
82
+ main {
83
+ display: flex;
84
+ flex-direction: column;
85
+ height: 100%;
86
+ min-height: 0;
87
+ }
88
+ .toolbar {
89
+ display: flex;
90
+ align-items: center;
91
+ gap: 8px;
92
+ padding: 10px 14px;
93
+ border-bottom: 1px solid var(--border);
94
+ flex-wrap: wrap;
95
+ }
96
+ .toolbar strong {
97
+ font-size: 14px;
98
+ margin-right: 10px;
99
+ }
100
+ .spacer {
101
+ flex: 1;
102
+ }
103
+ .content {
104
+ flex: 1;
105
+ min-height: 0;
106
+ overflow: auto;
107
+ padding: 16px;
108
+ }
109
+ .split {
110
+ display: grid;
111
+ grid-template-columns: 1fr 1fr;
112
+ flex: 1;
113
+ min-height: 0;
114
+ }
115
+ .split > * {
116
+ min-width: 0;
117
+ overflow: auto;
118
+ }
119
+ .split > :first-child {
120
+ border-right: 1px solid var(--border);
121
+ }
122
+ .editor {
123
+ width: 100%;
124
+ height: 100%;
125
+ border: 0;
126
+ border-radius: 0;
127
+ padding: 16px;
128
+ outline: none !important;
129
+ background: var(--bg);
130
+ }
131
+ .muted,
132
+ small {
133
+ color: var(--muted);
134
+ }
135
+ .status {
136
+ font-size: 12px;
137
+ min-height: 26px;
138
+ border-top: 1px solid var(--border);
139
+ padding: 3px 14px;
140
+ color: var(--muted);
141
+ }
142
+ .status[data-error="true"] {
143
+ color: var(--danger);
144
+ }
145
+ .tabs {
146
+ display: flex;
147
+ gap: 5px;
148
+ align-items: center;
149
+ }
150
+ .tabs button {
151
+ border: 0;
152
+ background: transparent;
153
+ }
154
+ .tabs .active {
155
+ color: var(--accent);
156
+ background: var(--soft);
157
+ }
158
+ .empty {
159
+ padding: 48px 16px;
160
+ text-align: center;
161
+ color: var(--muted);
162
+ }
163
+ table {
164
+ border-collapse: collapse;
165
+ width: 100%;
166
+ text-align: left;
167
+ }
168
+ th {
169
+ font-size: 12px;
170
+ color: var(--muted);
171
+ font-weight: 400;
172
+ background: var(--surface);
173
+ position: sticky;
174
+ top: 0;
175
+ }
176
+ th,
177
+ td {
178
+ padding: 9px 12px;
179
+ border-bottom: 1px solid var(--border);
180
+ }
181
+ tr.selected {
182
+ background: var(--soft);
183
+ }
184
+ pre {
185
+ white-space: pre-wrap;
186
+ overflow-wrap: anywhere;
187
+ margin: 0;
188
+ }
189
+ label {
190
+ display: flex;
191
+ gap: 8px;
192
+ align-items: center;
193
+ }
194
+ .stack {
195
+ display: flex;
196
+ flex-direction: column;
197
+ gap: 12px;
198
+ }
199
+ .row {
200
+ display: flex;
201
+ gap: 8px;
202
+ align-items: center;
203
+ }
204
+ .panel {
205
+ border: 1px solid var(--border);
206
+ border-radius: 6px;
207
+ padding: 14px;
208
+ }
209
+ .badge {
210
+ font-size: 11px;
211
+ padding: 1px 7px;
212
+ border-radius: 4px;
213
+ background: var(--surface);
214
+ color: var(--muted);
215
+ }
216
+ .danger {
217
+ color: var(--danger);
218
+ }
219
+ .hidden {
220
+ display: none !important;
221
+ }
222
+ #theme {
223
+ padding: 3px 8px;
224
+ }
225
+ .sidebar {
226
+ width: 155px;
227
+ background: var(--surface);
228
+ padding: 14px 10px;
229
+ border-right: 1px solid var(--border);
230
+ overflow: auto;
231
+ }
232
+ .sidebar button {
233
+ display: block;
234
+ width: 100%;
235
+ text-align: left;
236
+ border: 0;
237
+ background: transparent;
238
+ margin-bottom: 4px;
239
+ }
240
+ .sidebar .active {
241
+ background: var(--soft);
242
+ color: var(--accent);
243
+ }
244
+ .workspace {
245
+ display: flex;
246
+ flex: 1;
247
+ min-height: 0;
248
+ }
249
+ .workspace > .content {
250
+ flex: 1;
251
+ }
252
+ details {
253
+ border-bottom: 1px solid var(--border);
254
+ padding: 7px 0;
255
+ }
256
+ summary {
257
+ cursor: pointer;
258
+ }
259
+ ::-webkit-scrollbar {
260
+ width: 6px;
261
+ height: 6px;
262
+ }
263
+ ::-webkit-scrollbar-thumb {
264
+ background: #b9c0cb60;
265
+ border-radius: 8px;
266
+ }
267
+ html[data-theme="dark"] {
268
+ color-scheme: dark;
269
+ --bg: #1b1e24;
270
+ --surface: #222731;
271
+ --fg: #dce1eb;
272
+ --muted: #8894a8;
273
+ --border: #333a47;
274
+ --accent: #6ca7ff;
275
+ --soft: #27364c;
276
+ --danger: #ff8490;
277
+ }
278
+ @media (max-width: 560px) {
279
+ .sidebar {
280
+ width: 115px;
281
+ }
282
+ .toolbar {
283
+ padding: 8px;
284
+ gap: 5px;
285
+ }
286
+ button {
287
+ padding: 5px 8px;
288
+ }
289
+ }
290
+ @media (prefers-reduced-motion: reduce) {
291
+ * {
292
+ scroll-behavior: auto !important;
293
+ animation: none !important;
294
+ }
295
+ }
package/umi.mjs ADDED
@@ -0,0 +1,34 @@
1
+ export const DEFAULT_ENDPOINT = 'http://127.0.0.1:1224';
2
+ export function endpoint(value = DEFAULT_ENDPOINT) {
3
+ let url;
4
+ try { url = new URL(value); } catch { throw Error('请输入本机服务地址,例如 http://127.0.0.1:1224'); }
5
+ if (url.protocol !== 'http:' || !['127.0.0.1','localhost','[::1]'].includes(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw Error('仅允许本机 HTTP 地址,不支持外部服务器或额外路径');
6
+ return url.origin;
7
+ }
8
+ export function imageBase64(value) {
9
+ const match = /^data:image\/(?:png|jpeg|bmp);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(value);
10
+ if (!match || match[1].length % 4 || match[1].length > 4*1024*1024) throw Error('请选择不超过 3 MB 的 JPG / PNG / BMP 图片');
11
+ return match[1];
12
+ }
13
+ export function responseJson(response) {
14
+ if (response?.status !== 200) throw Error('Umi-OCR 返回 HTTP '+(response?.status ?? '未知'));
15
+ try { return JSON.parse(response.body); } catch { throw Error('Umi-OCR 返回的内容不是有效 JSON,请核对本机服务地址'); }
16
+ }
17
+ export function resultText(result) {
18
+ if (result?.code === 101) return '';
19
+ if (result?.code !== 100) throw Error('Umi-OCR 识别失败:'+(typeof result?.data === 'string' ? result.data : '返回码 '+result?.code));
20
+ if (typeof result.data === 'string') return result.data;
21
+ if (Array.isArray(result.data) && result.data.every(item => typeof item?.text === 'string')) return result.data.map(item=>item.text).join('\n');
22
+ throw Error('Umi-OCR 识别结果格式无效');
23
+ }
24
+ export function friendlyError(error) {
25
+ const text=error?.message || String(error);
26
+ if (/connect|connection|timed? ?out|timeout|10061|拒绝连接|连接失败/i.test(text)) return '无法连接或识别超时:请确认 Umi-OCR 正在运行,并在全局设置开启 HTTP 服务(默认 127.0.0.1:1224);首次识别需加载模型,稍后可重试。';
27
+ return text;
28
+ }
29
+ export const UMI_DOWNLOAD_URL = 'https://github.com/hiroi-sora/Umi-OCR/releases';
30
+ export function isConnectionFailure(error) {
31
+ const text=error?.message||String(error);
32
+ if(/permission|denied|授权|权限|timeout|timed? ?out|超时/i.test(text))return false;
33
+ return /ECONNREFUSED|10061|refused|failed to connect|connect.*fail|connection.*fail|network error|拒绝连接|连接失败|无法连接/i.test(text);
34
+ }