xmind-mcp-server 0.1.0__py3-none-any.whl
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.
- xmind_mcp/__init__.py +3 -0
- xmind_mcp/__main__.py +9 -0
- xmind_mcp/cli.py +158 -0
- xmind_mcp/config.py +60 -0
- xmind_mcp/hardware/__init__.py +14 -0
- xmind_mcp/hardware/detector.py +211 -0
- xmind_mcp/hardware/installer.py +119 -0
- xmind_mcp/ocr/__init__.py +6 -0
- xmind_mcp/ocr/base.py +43 -0
- xmind_mcp/ocr/manager.py +143 -0
- xmind_mcp/ocr/paddleocr_backend.py +90 -0
- xmind_mcp/ocr/rapidocr_backend.py +100 -0
- xmind_mcp/server.py +67 -0
- xmind_mcp/tools.py +584 -0
- xmind_mcp/xmind_parser.py +310 -0
- xmind_mcp/xmind_writer.py +208 -0
- xmind_mcp_server-0.1.0.dist-info/METADATA +324 -0
- xmind_mcp_server-0.1.0.dist-info/RECORD +22 -0
- xmind_mcp_server-0.1.0.dist-info/WHEEL +5 -0
- xmind_mcp_server-0.1.0.dist-info/entry_points.txt +2 -0
- xmind_mcp_server-0.1.0.dist-info/licenses/LICENSE +21 -0
- xmind_mcp_server-0.1.0.dist-info/top_level.txt +1 -0
xmind_mcp/__init__.py
ADDED
xmind_mcp/__main__.py
ADDED
xmind_mcp/cli.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""命令行入口。
|
|
2
|
+
|
|
3
|
+
用法:
|
|
4
|
+
xmind-mcp # 启动 MCP Server(首次自动检测+安装)
|
|
5
|
+
xmind-mcp --setup # 重新检测硬件并配置
|
|
6
|
+
xmind-mcp --info # 打印当前硬件和配置信息
|
|
7
|
+
xmind-mcp --engine paddleocr # 切换 OCR 引擎
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import asyncio
|
|
14
|
+
import sys
|
|
15
|
+
from dataclasses import asdict
|
|
16
|
+
|
|
17
|
+
from .config import Config, CONFIG_FILE
|
|
18
|
+
from .hardware import (
|
|
19
|
+
detect_hardware,
|
|
20
|
+
choose_packages,
|
|
21
|
+
install_packages,
|
|
22
|
+
verify_installed,
|
|
23
|
+
cleanup_onnxruntime_conflicts,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main() -> int:
|
|
28
|
+
parser = argparse.ArgumentParser(
|
|
29
|
+
prog="xmind-mcp",
|
|
30
|
+
description="XMind MCP Server — 让大模型读写 XMind 文件",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument("--setup", action="store_true", help="重新检测硬件并配置 OCR")
|
|
33
|
+
parser.add_argument("--info", action="store_true", help="打印当前硬件和配置信息")
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"--engine",
|
|
36
|
+
choices=["rapidocr", "paddleocr"],
|
|
37
|
+
help="指定 OCR 引擎(默认 rapidocr)",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--device",
|
|
41
|
+
choices=["cuda", "directml", "openvino", "rocm", "cpu"],
|
|
42
|
+
help="强制指定推理设备(默认自动检测)",
|
|
43
|
+
)
|
|
44
|
+
args = parser.parse_args()
|
|
45
|
+
|
|
46
|
+
config = Config.load()
|
|
47
|
+
|
|
48
|
+
# --info:只打印信息,不启动
|
|
49
|
+
if args.info:
|
|
50
|
+
return print_info(config)
|
|
51
|
+
|
|
52
|
+
# --setup 或未初始化:走安装流程
|
|
53
|
+
if args.setup or not config.is_ready:
|
|
54
|
+
engine = args.engine or "rapidocr"
|
|
55
|
+
if not run_setup(config, engine=engine, force_device=args.device):
|
|
56
|
+
return 1
|
|
57
|
+
|
|
58
|
+
# 验证安装
|
|
59
|
+
ok, msg = verify_installed(config.ocr_engine, config.device)
|
|
60
|
+
if not ok:
|
|
61
|
+
print(f"⚠️ OCR 引擎验证失败: {msg}", file=sys.stderr)
|
|
62
|
+
print("请运行 xmind-mcp --setup 重新配置。", file=sys.stderr)
|
|
63
|
+
return 1
|
|
64
|
+
print(f"✅ OCR 就绪: {msg}", file=sys.stderr)
|
|
65
|
+
|
|
66
|
+
# 启动 MCP Server
|
|
67
|
+
from .server import run_server
|
|
68
|
+
try:
|
|
69
|
+
asyncio.run(run_server(config))
|
|
70
|
+
except KeyboardInterrupt:
|
|
71
|
+
print("\n服务已停止。", file=sys.stderr)
|
|
72
|
+
return 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def run_setup(config: Config, engine: str = "rapidocr", force_device: str = None) -> bool:
|
|
76
|
+
"""首次配置:检测硬件 → 选包 → 安装 → 写配置。"""
|
|
77
|
+
print("🔍 正在检测硬件...", file=sys.stderr)
|
|
78
|
+
hw = detect_hardware()
|
|
79
|
+
|
|
80
|
+
print(f" 操作系统: {hw.os}", file=sys.stderr)
|
|
81
|
+
print(f" CPU 核心: {hw.cpu_count}", file=sys.stderr)
|
|
82
|
+
print(f" 内存: {hw.ram_gb} GB", file=sys.stderr)
|
|
83
|
+
for g in hw.gpus:
|
|
84
|
+
vram_str = f", 显存: {g.vram_mb}MB" if g.vram_mb else ""
|
|
85
|
+
print(f" 显卡: {g.name} ({g.vendor}{vram_str})", file=sys.stderr)
|
|
86
|
+
|
|
87
|
+
# 选择包
|
|
88
|
+
device, packages = choose_packages(hw, engine=engine)
|
|
89
|
+
if force_device:
|
|
90
|
+
device = force_device
|
|
91
|
+
# 根据 device 调整 packages
|
|
92
|
+
if engine == "rapidocr":
|
|
93
|
+
ort_pkg = {
|
|
94
|
+
"cuda": "onnxruntime-gpu",
|
|
95
|
+
"directml": "onnxruntime-directml",
|
|
96
|
+
"cpu": "onnxruntime",
|
|
97
|
+
}.get(device, "onnxruntime")
|
|
98
|
+
packages = ["rapidocr-onnxruntime", ort_pkg]
|
|
99
|
+
|
|
100
|
+
print(f"\n📦 OCR 引擎: {engine}", file=sys.stderr)
|
|
101
|
+
print(f" 推理设备: {device}", file=sys.stderr)
|
|
102
|
+
print(f" 待安装包: {', '.join(packages)}", file=sys.stderr)
|
|
103
|
+
|
|
104
|
+
# onnxruntime 互斥处理
|
|
105
|
+
if engine == "rapidocr":
|
|
106
|
+
cleanup_onnxruntime_conflicts(device)
|
|
107
|
+
|
|
108
|
+
# 安装
|
|
109
|
+
print("\n⬇️ 正在安装依赖(可能需要几分钟)...", file=sys.stderr)
|
|
110
|
+
if not install_packages(packages):
|
|
111
|
+
print("❌ 安装失败,请检查网络或手动安装。", file=sys.stderr)
|
|
112
|
+
print(f" 手动安装: pip install {' '.join(packages)}", file=sys.stderr)
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
# 验证
|
|
116
|
+
ok, msg = verify_installed(engine, device)
|
|
117
|
+
if not ok:
|
|
118
|
+
print(f"❌ 安装后验证失败: {msg}", file=sys.stderr)
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
# 写配置
|
|
122
|
+
config.ocr_engine = engine
|
|
123
|
+
config.device = device
|
|
124
|
+
config.gpus = [asdict(g) if hasattr(g, '__dataclass_fields__') else g.__dict__ for g in hw.gpus]
|
|
125
|
+
config.cpu_count = hw.cpu_count
|
|
126
|
+
config.ram_gb = hw.ram_gb
|
|
127
|
+
config.os = hw.os
|
|
128
|
+
config.model_cache_dir = str(__import__("pathlib").Path.home() / ".xmind-mcp" / "models")
|
|
129
|
+
config.initialized = True
|
|
130
|
+
config.installed_packages = packages
|
|
131
|
+
config.save()
|
|
132
|
+
|
|
133
|
+
print(f"\n✅ 配置完成!{msg}", file=sys.stderr)
|
|
134
|
+
print(f" 配置文件: {CONFIG_FILE}", file=sys.stderr)
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def print_info(config: Config) -> int:
|
|
139
|
+
"""打印当前配置信息。"""
|
|
140
|
+
if not config.is_ready:
|
|
141
|
+
print("⚠️ 尚未初始化,请先运行: xmind-mcp --setup")
|
|
142
|
+
return 1
|
|
143
|
+
|
|
144
|
+
print("=== XMind MCP Server 配置 ===")
|
|
145
|
+
print(f" 操作系统: {config.os}")
|
|
146
|
+
print(f" OCR 引擎: {config.ocr_engine}")
|
|
147
|
+
print(f" 推理设备: {config.device}")
|
|
148
|
+
print(f" CPU 核心: {config.cpu_count}")
|
|
149
|
+
print(f" 内存: {config.ram_gb} GB")
|
|
150
|
+
for g in config.gpus:
|
|
151
|
+
vram = f", 显存: {g.get('vram_mb', 0)}MB" if g.get("vram_mb") else ""
|
|
152
|
+
print(f" 显卡: {g.get('name', '?')} ({g.get('vendor', '?')}{vram})")
|
|
153
|
+
print(f" 配置文件: {CONFIG_FILE}")
|
|
154
|
+
print(f" 已安装包: {', '.join(config.installed_packages)}")
|
|
155
|
+
|
|
156
|
+
ok, msg = verify_installed(config.ocr_engine, config.device)
|
|
157
|
+
print(f" 验证状态: {'✅ ' + msg if ok else '❌ ' + msg}")
|
|
158
|
+
return 0 if ok else 1
|
xmind_mcp/config.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""配置管理:读写 ~/.xmind-mcp/config.json,记录硬件检测结果和用户选择。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
CONFIG_DIR = Path.home() / ".xmind-mcp"
|
|
12
|
+
CONFIG_FILE = CONFIG_DIR / "config.json"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Config:
|
|
17
|
+
"""首次启动后持久化的配置。"""
|
|
18
|
+
|
|
19
|
+
# OCR 引擎:rapidocr | paddleocr
|
|
20
|
+
ocr_engine: str = "rapidocr"
|
|
21
|
+
# 推理设备:cuda | directml | openvino | rocm | cpu
|
|
22
|
+
device: str = "cpu"
|
|
23
|
+
# 检测到的显卡信息(可能多张)
|
|
24
|
+
gpus: list[dict] = field(default_factory=list)
|
|
25
|
+
# CPU 逻辑核心数
|
|
26
|
+
cpu_count: int = 0
|
|
27
|
+
# 内存 GB
|
|
28
|
+
ram_gb: float = 0.0
|
|
29
|
+
# 操作系统:windows | linux | macos
|
|
30
|
+
os: str = ""
|
|
31
|
+
# OCR 模型缓存目录
|
|
32
|
+
model_cache_dir: str = ""
|
|
33
|
+
# 是否已完成首次安装
|
|
34
|
+
initialized: bool = False
|
|
35
|
+
# 安装时用的 pip 包列表(用于二次验证)
|
|
36
|
+
installed_packages: list[str] = field(default_factory=list)
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def load(cls) -> "Config":
|
|
40
|
+
"""读取配置文件,不存在则返回默认实例。"""
|
|
41
|
+
if not CONFIG_FILE.exists():
|
|
42
|
+
return cls()
|
|
43
|
+
try:
|
|
44
|
+
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
|
45
|
+
# 兼容字段缺失
|
|
46
|
+
return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
|
|
47
|
+
except (json.JSONDecodeError, TypeError):
|
|
48
|
+
return cls()
|
|
49
|
+
|
|
50
|
+
def save(self) -> None:
|
|
51
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
CONFIG_FILE.write_text(
|
|
53
|
+
json.dumps(asdict(self), indent=2, ensure_ascii=False),
|
|
54
|
+
encoding="utf-8",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def is_ready(self) -> bool:
|
|
59
|
+
"""配置是否完整且已初始化。"""
|
|
60
|
+
return self.initialized and bool(self.ocr_engine) and bool(self.device)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""硬件检测和依赖安装。"""
|
|
2
|
+
|
|
3
|
+
from .detector import HardwareInfo, GPUInfo, detect_hardware
|
|
4
|
+
from .installer import choose_packages, cleanup_onnxruntime_conflicts, install_packages, verify_installed
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"HardwareInfo",
|
|
8
|
+
"GPUInfo",
|
|
9
|
+
"detect_hardware",
|
|
10
|
+
"choose_packages",
|
|
11
|
+
"install_packages",
|
|
12
|
+
"verify_installed",
|
|
13
|
+
"cleanup_onnxruntime_conflicts",
|
|
14
|
+
]
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""跨平台硬件检测:GPU 厂商/显存、CPU、内存。
|
|
2
|
+
|
|
3
|
+
策略:
|
|
4
|
+
- GPU 名称:调系统命令列出显卡,按关键词匹配厂商
|
|
5
|
+
- NVIDIA 显存:优先用 nvidia-smi(最准)
|
|
6
|
+
- 其他显卡显存:Windows 用 wmic(不一定准),Linux/macOS 标记 unknown
|
|
7
|
+
- 不依赖额外包,只用标准库 + psutil
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import platform
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# ---------- 数据结构 ----------
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class GPUInfo:
|
|
23
|
+
vendor: str # nvidia | amd | intel | unknown
|
|
24
|
+
name: str
|
|
25
|
+
vram_mb: int = 0 # 0 表示未知(集成显卡或检测失败)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class HardwareInfo:
|
|
30
|
+
gpus: list[GPUInfo] = field(default_factory=list)
|
|
31
|
+
cpu_count: int = 0
|
|
32
|
+
ram_gb: float = 0.0
|
|
33
|
+
os: str = "" # windows | linux | macos
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------- 厂商识别 ----------
|
|
37
|
+
|
|
38
|
+
VENDOR_KEYWORDS = {
|
|
39
|
+
"nvidia": [r"nvidia", r"geforce", r"quadro", r"tesla", r"rtx", r"gtx"],
|
|
40
|
+
"amd": [r"amd", r"radeon", r"rx\s?\d", r"vega", r"instinct"],
|
|
41
|
+
"intel": [r"intel", r"arc", r"iris", r"uhd", r"hd\s?graphics"],
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _match_vendor(name: str) -> str:
|
|
46
|
+
name_lower = name.lower()
|
|
47
|
+
for vendor, patterns in VENDOR_KEYWORDS.items():
|
|
48
|
+
if any(re.search(p, name_lower) for p in patterns):
|
|
49
|
+
return vendor
|
|
50
|
+
return "unknown"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ---------- 系统命令封装 ----------
|
|
54
|
+
|
|
55
|
+
def _run(cmd: list[str], timeout: int = 10) -> str:
|
|
56
|
+
"""运行系统命令,返回 stdout,失败返回空串。"""
|
|
57
|
+
try:
|
|
58
|
+
r = subprocess.run(
|
|
59
|
+
cmd,
|
|
60
|
+
capture_output=True,
|
|
61
|
+
text=True,
|
|
62
|
+
timeout=timeout,
|
|
63
|
+
shell=False,
|
|
64
|
+
)
|
|
65
|
+
return r.stdout.strip()
|
|
66
|
+
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
|
|
67
|
+
return ""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _run_shell(cmd: str, timeout: int = 10) -> str:
|
|
71
|
+
"""用 shell 运行命令(用于管道操作)。"""
|
|
72
|
+
try:
|
|
73
|
+
r = subprocess.run(
|
|
74
|
+
cmd,
|
|
75
|
+
capture_output=True,
|
|
76
|
+
text=True,
|
|
77
|
+
timeout=timeout,
|
|
78
|
+
shell=True,
|
|
79
|
+
)
|
|
80
|
+
return r.stdout.strip()
|
|
81
|
+
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
|
|
82
|
+
return ""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ---------- GPU 名称检测 ----------
|
|
86
|
+
|
|
87
|
+
def _gpus_windows() -> list[str]:
|
|
88
|
+
"""Windows: 用 PowerShell 查显卡名称。"""
|
|
89
|
+
out = _run_shell(
|
|
90
|
+
'powershell -Command "Get-CimInstance Win32_VideoController '
|
|
91
|
+
'| Select-Object -ExpandProperty Name"'
|
|
92
|
+
)
|
|
93
|
+
return [line.strip() for line in out.splitlines() if line.strip()]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _gpus_linux() -> list[str]:
|
|
97
|
+
"""Linux: lspci 或 lshw。"""
|
|
98
|
+
# 先试 lspci
|
|
99
|
+
out = _run_shell("lspci 2>/dev/null | grep -iE 'vga|3d|display'")
|
|
100
|
+
names = []
|
|
101
|
+
for line in out.splitlines():
|
|
102
|
+
# 格式: "00:01.0 VGA compatible controller: Intel Corporation HD Graphics (rev 09)"
|
|
103
|
+
if ":" in line:
|
|
104
|
+
name = line.split(":", 1)[1].strip()
|
|
105
|
+
# 去掉厂商前缀后的设备描述
|
|
106
|
+
names.append(name)
|
|
107
|
+
if names:
|
|
108
|
+
return names
|
|
109
|
+
# 回退 lshw
|
|
110
|
+
out = _run_shell("lshw -C display 2>/dev/null | grep 'product:'")
|
|
111
|
+
return [line.split("product:", 1)[1].strip() for line in out.splitlines() if "product:" in line]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _gpus_macos() -> list[str]:
|
|
115
|
+
"""macOS: system_profiler。"""
|
|
116
|
+
out = _run_shell("system_profiler SPDisplaysDataType 2>/dev/null")
|
|
117
|
+
names = []
|
|
118
|
+
for line in out.splitlines():
|
|
119
|
+
line = line.strip()
|
|
120
|
+
if line.startswith("Chipset Model:") or line.startswith("Vendor:"):
|
|
121
|
+
val = line.split(":", 1)[1].strip()
|
|
122
|
+
if val:
|
|
123
|
+
names.append(val)
|
|
124
|
+
return names
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# ---------- NVIDIA 显存 ----------
|
|
128
|
+
|
|
129
|
+
def _nvidia_vram_smi() -> dict[str, int]:
|
|
130
|
+
"""用 nvidia-smi 查每张 NVIDIA 显卡的显存,返回 {显卡名: 显存MB}。"""
|
|
131
|
+
out = _run_shell(
|
|
132
|
+
'nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits 2>/dev/null'
|
|
133
|
+
)
|
|
134
|
+
result = {}
|
|
135
|
+
for line in out.splitlines():
|
|
136
|
+
parts = [p.strip() for p in line.split(",")]
|
|
137
|
+
if len(parts) == 2:
|
|
138
|
+
name, vram = parts
|
|
139
|
+
try:
|
|
140
|
+
result[name] = int(vram)
|
|
141
|
+
except ValueError:
|
|
142
|
+
pass
|
|
143
|
+
return result
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ---------- 主检测函数 ----------
|
|
147
|
+
|
|
148
|
+
def detect_hardware() -> HardwareInfo:
|
|
149
|
+
"""检测本机硬件,返回 HardwareInfo。"""
|
|
150
|
+
import psutil
|
|
151
|
+
|
|
152
|
+
system = platform.system().lower()
|
|
153
|
+
os_name = "windows" if system.startswith("win") else "linux" if system.startswith("linux") else "macos"
|
|
154
|
+
|
|
155
|
+
# 获取显卡名称列表
|
|
156
|
+
if os_name == "windows":
|
|
157
|
+
gpu_names = _gpus_windows()
|
|
158
|
+
elif os_name == "linux":
|
|
159
|
+
gpu_names = _gpus_linux()
|
|
160
|
+
else:
|
|
161
|
+
gpu_names = _gpus_macos()
|
|
162
|
+
|
|
163
|
+
# NVIDIA 显存(如果装了驱动)
|
|
164
|
+
nvidia_vram = _nvidia_vram_smi()
|
|
165
|
+
|
|
166
|
+
gpus: list[GPUInfo] = []
|
|
167
|
+
for name in gpu_names:
|
|
168
|
+
vendor = _match_vendor(name)
|
|
169
|
+
vram = 0
|
|
170
|
+
if vendor == "nvidia":
|
|
171
|
+
# 精确匹配 nvidia-smi 的名称,匹配不上就用模糊匹配
|
|
172
|
+
vram = nvidia_vram.get(name, 0)
|
|
173
|
+
if vram == 0:
|
|
174
|
+
for smi_name, mb in nvidia_vram.items():
|
|
175
|
+
if smi_name.lower() in name.lower() or name.lower() in smi_name.lower():
|
|
176
|
+
vram = mb
|
|
177
|
+
break
|
|
178
|
+
elif vendor in ("amd", "intel"):
|
|
179
|
+
# 独显一般 >=2GB,集成显卡 vram 标 0
|
|
180
|
+
if any(kw in name.lower() for kw in ["radeon rx", "arc a", "rtx", "instinct", "vega"]):
|
|
181
|
+
vram = 0 # 拿不到准确值,但标记为独显
|
|
182
|
+
gpus.append(GPUInfo(vendor=vendor, name=name, vram_mb=vram))
|
|
183
|
+
|
|
184
|
+
# 没检测到显卡就加一个 unknown
|
|
185
|
+
if not gpus:
|
|
186
|
+
gpus.append(GPUInfo(vendor="unknown", name="Unknown", vram_mb=0))
|
|
187
|
+
|
|
188
|
+
return HardwareInfo(
|
|
189
|
+
gpus=gpus,
|
|
190
|
+
cpu_count=psutil.cpu_count(logical=True) or 0,
|
|
191
|
+
ram_gb=round(psutil.virtual_memory().total / (1024**3), 1),
|
|
192
|
+
os=os_name,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def has_nvidia_gpu(hw: HardwareInfo) -> bool:
|
|
197
|
+
return any(g.vendor == "nvidia" for g in hw.gpus)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def has_discrete_gpu(hw: HardwareInfo) -> bool:
|
|
201
|
+
"""是否有独立显卡(NVIDIA 全算,AMD/Intel 看名字判断)。"""
|
|
202
|
+
for g in hw.gpus:
|
|
203
|
+
if g.vendor == "nvidia":
|
|
204
|
+
return True
|
|
205
|
+
if g.vendor in ("amd", "intel"):
|
|
206
|
+
name_lower = g.name.lower()
|
|
207
|
+
# 集成显卡关键词
|
|
208
|
+
integrated = ["integrated", "iris", "uhd graphics", "hd graphics", "radeon graphics"]
|
|
209
|
+
if not any(kw in name_lower for kw in integrated):
|
|
210
|
+
return True
|
|
211
|
+
return False
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""根据硬件检测结果选择并安装 OCR 依赖包。
|
|
2
|
+
|
|
3
|
+
策略(RapidOCR 为默认,PaddleOCR 可选):
|
|
4
|
+
|
|
5
|
+
engine=rapidocr:
|
|
6
|
+
NVIDIA → onnxruntime-gpu (CUDA)
|
|
7
|
+
AMD/Intel + Win → onnxruntime-directml (DirectML)
|
|
8
|
+
其他 → onnxruntime (CPU)
|
|
9
|
+
|
|
10
|
+
engine=paddleocr:
|
|
11
|
+
NVIDIA → paddlepaddle-gpu (CUDA)
|
|
12
|
+
其他 → paddlepaddle (CPU)
|
|
13
|
+
|
|
14
|
+
注意 onnxruntime / onnxruntime-gpu / onnxruntime-directml 三者互斥,
|
|
15
|
+
切换时需先卸载旧的。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Optional
|
|
23
|
+
|
|
24
|
+
from .detector import HardwareInfo, has_nvidia_gpu, has_discrete_gpu
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def choose_packages(
|
|
28
|
+
hw: HardwareInfo,
|
|
29
|
+
engine: str = "rapidocr",
|
|
30
|
+
) -> tuple[str, list[str]]:
|
|
31
|
+
"""根据硬件和引擎选择 pip 包。
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
(device, packages) — device 是推理设备标识,packages 是要 pip install 的列表
|
|
35
|
+
"""
|
|
36
|
+
nvidia = has_nvidia_gpu(hw)
|
|
37
|
+
discrete = has_discrete_gpu(hw)
|
|
38
|
+
|
|
39
|
+
if engine == "paddleocr":
|
|
40
|
+
if nvidia:
|
|
41
|
+
return "cuda", ["paddleocr", "paddlepaddle-gpu"]
|
|
42
|
+
return "cpu", ["paddleocr", "paddlepaddle"]
|
|
43
|
+
|
|
44
|
+
# 默认 rapidocr
|
|
45
|
+
if nvidia:
|
|
46
|
+
return "cuda", ["rapidocr-onnxruntime", "onnxruntime-gpu"]
|
|
47
|
+
if discrete and hw.os == "windows":
|
|
48
|
+
# AMD / Intel 独显 + Windows → DirectML
|
|
49
|
+
return "directml", ["rapidocr-onnxruntime", "onnxruntime-directml"]
|
|
50
|
+
# 兜底 CPU
|
|
51
|
+
return "cpu", ["rapidocr-onnxruntime", "onnxruntime"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def install_packages(packages: list[str]) -> bool:
|
|
55
|
+
"""pip install 指定包,返回是否成功。"""
|
|
56
|
+
if not packages:
|
|
57
|
+
return True
|
|
58
|
+
cmd = [sys.executable, "-m", "pip", "install", *packages]
|
|
59
|
+
try:
|
|
60
|
+
result = subprocess.run(cmd, capture_output=False, timeout=600)
|
|
61
|
+
return result.returncode == 0
|
|
62
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def uninstall_packages(packages: list[str]) -> bool:
|
|
67
|
+
"""卸载包(用于切换引擎/设备时清理冲突包)。"""
|
|
68
|
+
if not packages:
|
|
69
|
+
return True
|
|
70
|
+
cmd = [sys.executable, "-m", "pip", "uninstall", "-y", *packages]
|
|
71
|
+
try:
|
|
72
|
+
result = subprocess.run(cmd, capture_output=False, timeout=300)
|
|
73
|
+
return result.returncode == 0
|
|
74
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# onnxruntime 三个互斥包,切换设备时需卸载冲突项
|
|
79
|
+
_ONNXRUNTIME_VARIANTS = ["onnxruntime", "onnxruntime-gpu", "onnxruntime-directml"]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def cleanup_onnxruntime_conflicts(new_device: str) -> None:
|
|
83
|
+
"""安装新 onnxruntime 变体前,卸载冲突的旧变体。"""
|
|
84
|
+
keep = {
|
|
85
|
+
"cpu": "onnxruntime",
|
|
86
|
+
"cuda": "onnxruntime-gpu",
|
|
87
|
+
"directml": "onnxruntime-directml",
|
|
88
|
+
}.get(new_device, "onnxruntime")
|
|
89
|
+
|
|
90
|
+
conflicts = [p for p in _ONNXRUNTIME_VARIANTS if p != keep]
|
|
91
|
+
uninstall_packages(conflicts)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def verify_installed(engine: str, device: str) -> tuple[bool, str]:
|
|
95
|
+
"""验证 OCR 引擎是否可用,返回 (是否可用, 说明)。"""
|
|
96
|
+
if engine == "rapidocr":
|
|
97
|
+
try:
|
|
98
|
+
import rapidocr_onnxruntime # noqa: F401
|
|
99
|
+
import onnxruntime as ort # noqa: F401
|
|
100
|
+
providers = ort.get_available_providers()
|
|
101
|
+
# 检查目标 provider 是否在列表里
|
|
102
|
+
target = {
|
|
103
|
+
"cuda": "CUDAExecutionProvider",
|
|
104
|
+
"directml": "DmlExecutionProvider",
|
|
105
|
+
"cpu": "CPUExecutionProvider",
|
|
106
|
+
}.get(device, "CPUExecutionProvider")
|
|
107
|
+
if target in providers:
|
|
108
|
+
return True, f"rapidocr 可用,provider={target}"
|
|
109
|
+
return True, f"rapidocr 已装但 {target} 不可用,实际 providers={providers},将回退 CPU"
|
|
110
|
+
except ImportError as e:
|
|
111
|
+
return False, f"rapidocr 未安装: {e}"
|
|
112
|
+
elif engine == "paddleocr":
|
|
113
|
+
try:
|
|
114
|
+
import paddleocr # noqa: F401
|
|
115
|
+
import paddle # noqa: F401
|
|
116
|
+
return True, "paddleocr 可用"
|
|
117
|
+
except ImportError as e:
|
|
118
|
+
return False, f"paddleocr 未安装: {e}"
|
|
119
|
+
return False, f"未知引擎: {engine}"
|
xmind_mcp/ocr/base.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""OCR 后端抽象接口。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Union
|
|
8
|
+
|
|
9
|
+
from PIL import Image
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# 图片输入类型:PIL Image / 文件路径 / 二进制 bytes
|
|
13
|
+
ImageInput = Union[Image.Image, str, bytes]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class OcrResult:
|
|
18
|
+
"""单次 OCR 识别结果。"""
|
|
19
|
+
|
|
20
|
+
# 识别出的完整文本(多行用 \n 连接)
|
|
21
|
+
text: str
|
|
22
|
+
# 带位置和置信度的明细
|
|
23
|
+
lines: list[dict] # [{"text": "...", "confidence": 0.95, "box": [[x,y],...]}]
|
|
24
|
+
# 耗时秒
|
|
25
|
+
elapsed: float = 0.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OCRBackend(ABC):
|
|
29
|
+
"""OCR 引擎后端抽象基类。"""
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def recognize(self, image: ImageInput) -> OcrResult:
|
|
33
|
+
"""识别图片中的文字。"""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
@abstractmethod
|
|
37
|
+
def close(self) -> None:
|
|
38
|
+
"""释放模型占用的内存/显存资源。"""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
def recognize_text(self, image: ImageInput) -> str:
|
|
42
|
+
"""只返回纯文本,便捷方法。"""
|
|
43
|
+
return self.recognize(image).text
|