execute-py.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. /**
  2. * 执行 Python 相关操作模块(通用功能)
  3. * 负责图像匹配、OCR识别等通用功能(通过调用 Python/JS 实现)
  4. * 注意:聊天记录提取等业务相关功能在 read-and-write.js 中
  5. */
  6. import { ipcMain } from 'electron';
  7. import { writeFile, mkdir, rm, readdir, stat, readFile } from 'fs/promises';
  8. import fs, { existsSync } from 'fs';
  9. import { join, dirname, isAbsolute } from 'path';
  10. import { fileURLToPath } from 'url';
  11. import { exec } from 'child_process';
  12. import { promisify } from 'util';
  13. import { captureScreenshot } from './adb/screenshot.js';
  14. import { getDeviceResolution } from './adb/device-info.js';
  15. import { matchImage } from './func/image-center-location.js';
  16. import { findTextLocation } from './func/string-reg-location.js';
  17. import { ocrFullScreen as ocrFullScreenFromFunc, getLastMessage as getLastMessageFromFunc } from './func/ocr-chat.js';
  18. const execAsync = promisify(exec);
  19. const __filename = fileURLToPath(import.meta.url);
  20. const __dirname = dirname(__filename);
  21. /**
  22. * 确保 pyvenv.cfg 文件使用当前系统的 Python 路径
  23. * @param {string} projectRoot - 项目根目录
  24. * @returns {Promise<void>}
  25. */
  26. async function ensurePyvenvConfig(projectRoot) {
  27. const pyvenvCfgPath = join(projectRoot, 'py', 'venv', 'pyvenv.cfg');
  28. if (!existsSync(pyvenvCfgPath)) {
  29. return; // 如果文件不存在,跳过
  30. }
  31. try {
  32. // 读取现有配置
  33. const currentContent = await readFile(pyvenvCfgPath, 'utf8');
  34. // 尝试从现有配置中提取系统 Python 路径
  35. const homeMatch = currentContent.match(/^home\s*=\s*(.+)$/m);
  36. const executableMatch = currentContent.match(/^executable\s*=\s*(.+)$/m);
  37. // 如果配置文件中已经有路径,检查路径是否存在
  38. if (homeMatch && executableMatch) {
  39. const existingHome = homeMatch[1].trim();
  40. const existingExecutable = executableMatch[1].trim();
  41. // 检查系统 Python 是否存在
  42. if (existsSync(existingExecutable)) {
  43. // 路径存在,不需要更新
  44. return;
  45. }
  46. }
  47. // 如果配置文件中的路径不存在,使用系统 Python 检测
  48. // 使用系统 Python(不是虚拟环境中的),因为我们需要检测系统 Python 路径
  49. const { stdout } = await execAsync('python -c "import sys; import os; print(os.path.dirname(sys.executable))"', {
  50. encoding: 'utf8',
  51. timeout: 5000,
  52. cwd: projectRoot
  53. });
  54. const pythonHome = stdout.trim();
  55. if (!pythonHome) {
  56. return; // 如果无法检测,跳过
  57. }
  58. const pythonExe = join(pythonHome, 'python.exe');
  59. // 检查系统 Python 是否存在
  60. if (!existsSync(pythonExe)) {
  61. return; // 系统 Python 不存在,跳过
  62. }
  63. // 检测 Python 版本(使用系统 Python)
  64. const { stdout: versionOutput } = await execAsync('python -c "import sys; print(\"{}.{}.{}\".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro))"', {
  65. encoding: 'utf8',
  66. timeout: 5000,
  67. cwd: projectRoot
  68. });
  69. const pythonVersion = versionOutput.trim();
  70. // 更新配置
  71. const newContent = `home = ${pythonHome}
  72. include-system-site-packages = false
  73. version = ${pythonVersion}
  74. executable = ${pythonExe}
  75. command = ${pythonExe} -m venv py/venv
  76. `;
  77. await writeFile(pyvenvCfgPath, newContent, 'utf8');
  78. } catch (error) {
  79. // 静默失败,不影响主流程
  80. console.warn('无法更新 pyvenv.cfg:', error.message);
  81. }
  82. }
  83. /**
  84. * 递归计算目录大小
  85. * @param {string} dirPath - 目录路径
  86. * @returns {Promise<number>} 目录总大小(字节)
  87. */
  88. async function calculateDirSize(dirPath) {
  89. let totalSize = 0;
  90. try {
  91. const entries = await readdir(dirPath, { withFileTypes: true });
  92. for (const entry of entries) {
  93. const entryPath = join(dirPath, entry.name);
  94. try {
  95. if (entry.isFile()) {
  96. const stats = await stat(entryPath);
  97. totalSize += stats.size;
  98. } else if (entry.isDirectory()) {
  99. totalSize += await calculateDirSize(entryPath);
  100. }
  101. } catch (e) {
  102. // 忽略无法访问的文件/目录
  103. }
  104. }
  105. } catch (e) {
  106. // 忽略无法读取的目录
  107. }
  108. return totalSize;
  109. }
  110. /**
  111. * 执行图像匹配:截图、调用 Python 脚本、返回坐标
  112. * @param {string} ipPort - 设备 ID/IP:Port
  113. * @param {string} templateImagePath - 模板图片路径
  114. * @returns {Promise<{success: boolean, error?: string, coordinate?: Object, clickPosition?: Object}>}
  115. */
  116. export async function matchImageAndGetCoordinate(ipPort, templateImagePath) {
  117. try {
  118. if (!ipPort) {
  119. return { success: false, error: '缺少设备 ID' };
  120. }
  121. if (!templateImagePath) {
  122. return { success: false, error: '缺少模板图片路径' };
  123. }
  124. // 将相对路径转换为绝对路径
  125. let absoluteTemplatePath = templateImagePath;
  126. if (!isAbsolute(templateImagePath)) {
  127. absoluteTemplatePath = join(__dirname, '..', templateImagePath);
  128. }
  129. // 1. 获取设备分辨率
  130. const resolutionResult = await getDeviceResolution(ipPort);
  131. if (!resolutionResult.success) {
  132. return { success: false, error: '获取设备分辨率失败' };
  133. }
  134. const { width, height } = resolutionResult;
  135. // 2. 获取屏幕截图
  136. const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
  137. if (!screenshotResult.success || !screenshotResult.data) {
  138. return { success: false, error: '获取屏幕截图失败' };
  139. }
  140. // 3. 保存截图到临时文件
  141. const tempDir = join(__dirname, '..');
  142. const screenshotPath = join(tempDir, 'temp_screenshot.png');
  143. const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
  144. await writeFile(screenshotPath, screenshotBuffer);
  145. // 4. 调用 JS 函数进行图像匹配
  146. const matchResult = await matchImage(screenshotPath, absoluteTemplatePath, width, height);
  147. if (!matchResult.success) {
  148. return { success: false, error: matchResult.error || '图像匹配失败' };
  149. }
  150. // 5. 返回匹配结果
  151. if (matchResult.success && matchResult.x !== undefined) {
  152. const { x, y, width: w, height: h } = matchResult;
  153. // 计算点击位置(中心点)
  154. const clickX = Math.round(x + w / 2);
  155. const clickY = Math.round(y + h / 2);
  156. return {
  157. success: true,
  158. coordinate: { x, y, width: w, height: h },
  159. clickPosition: { x: clickX, y: clickY }
  160. };
  161. } else {
  162. return {
  163. success: false,
  164. error: matchResult.error || '图像匹配失败'
  165. };
  166. }
  167. } catch (error) {
  168. return { success: false, error: error.message };
  169. }
  170. }
  171. /**
  172. * 图像区域定位:在完整截图中查找区域截图的位置,返回四个顶点坐标
  173. * @param {string} screenshotPath - 完整截图路径
  174. * @param {string} regionPath - 区域截图路径
  175. * @param {string} device - 设备 ID(可选,用于获取分辨率)
  176. * @returns {Promise<{success: boolean, error?: string, corners?: Object}>}
  177. */
  178. export async function matchImageRegionLocation(screenshotPath, regionPath, device = null) {
  179. try {
  180. if (!regionPath) {
  181. return { success: false, error: '缺少区域截图路径' };
  182. }
  183. // 使用相对路径(相对于项目根目录)
  184. const projectRoot = join(__dirname, '..');
  185. // 确保 pyvenv.cfg 使用当前系统的 Python 路径
  186. await ensurePyvenvConfig(projectRoot);
  187. // 如果 screenshotPath 为 '__AUTO_SCREENSHOT__' 或 null,自动从设备获取截图
  188. let relativeScreenshotPath = screenshotPath;
  189. if (!screenshotPath || screenshotPath === '__AUTO_SCREENSHOT__' || screenshotPath === null) {
  190. if (!device) {
  191. return { success: false, error: '缺少完整截图路径,且无法自动获取设备截图(缺少设备ID)' };
  192. }
  193. // 自动获取设备截图
  194. const resolutionResult = await getDeviceResolution(device);
  195. if (!resolutionResult.success) {
  196. return { success: false, error: '获取设备分辨率失败' };
  197. }
  198. const screenshotResult = await captureScreenshot(device, { format: 'png' });
  199. if (!screenshotResult.success || !screenshotResult.data) {
  200. return { success: false, error: '自动获取设备截图失败' };
  201. }
  202. // 保存截图到临时文件(使用相对路径)
  203. relativeScreenshotPath = 'temp_screenshot.png';
  204. const tempScreenshotAbsolutePath = join(projectRoot, relativeScreenshotPath);
  205. const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
  206. await writeFile(tempScreenshotAbsolutePath, screenshotBuffer);
  207. } else {
  208. // 如果传入的是绝对路径,转换为相对路径
  209. if (isAbsolute(screenshotPath)) {
  210. try {
  211. relativeScreenshotPath = require('path').relative(projectRoot, screenshotPath).replace(/\\/g, '/');
  212. } catch (e) {
  213. relativeScreenshotPath = screenshotPath.replace(/\\/g, '/');
  214. }
  215. } else {
  216. relativeScreenshotPath = screenshotPath.replace(/\\/g, '/');
  217. }
  218. }
  219. // 如果传入的是绝对路径,转换为相对路径
  220. let relativeRegionPath = regionPath;
  221. if (isAbsolute(regionPath)) {
  222. try {
  223. relativeRegionPath = require('path').relative(projectRoot, regionPath).replace(/\\/g, '/');
  224. } catch (e) {
  225. relativeRegionPath = regionPath.replace(/\\/g, '/');
  226. }
  227. } else {
  228. relativeRegionPath = regionPath.replace(/\\/g, '/');
  229. }
  230. // 可选:如果提供了设备ID,获取设备分辨率用于缩放
  231. let width = null;
  232. let height = null;
  233. if (device) {
  234. const resolutionResult = await getDeviceResolution(device);
  235. if (resolutionResult.success) {
  236. width = resolutionResult.width;
  237. height = resolutionResult.height;
  238. }
  239. }
  240. // 调用图像匹配函数(使用相对路径)
  241. const matchResult = await matchImage(relativeScreenshotPath, relativeRegionPath, width, height);
  242. if (!matchResult.success) {
  243. return { success: false, error: matchResult.error || '图像匹配失败' };
  244. }
  245. // 获取匹配结果
  246. const { x, y, width: w, height: h } = matchResult;
  247. // 计算四个顶点坐标
  248. const corners = {
  249. topLeft: { x, y },
  250. topRight: { x: x + w, y },
  251. bottomLeft: { x, y: y + h },
  252. bottomRight: { x: x + w, y: y + h }
  253. };
  254. // 如果提供了保存路径,裁剪并保存区域图片
  255. // 这个功能会在 executeImageRegionLocation 中调用时传入 savePath
  256. // 但为了保持API简洁,我们在这里不处理,而是在 executeImageRegionLocation 中处理
  257. return {
  258. success: true,
  259. x,
  260. y,
  261. width: w,
  262. height: h,
  263. corners: corners,
  264. similarity: matchResult.similarity,
  265. screenshotPath: relativeScreenshotPath // 返回截图路径(相对路径),用于后续裁剪
  266. };
  267. } catch (error) {
  268. // 图像区域定位失败
  269. return { success: false, error: error.message };
  270. }
  271. }
  272. /**
  273. * 裁剪并保存图片区域
  274. * @param {string} imagePath - 原图片路径
  275. * @param {number} x - 裁剪区域左上角x坐标
  276. * @param {number} y - 裁剪区域左上角y坐标
  277. * @param {number} width - 裁剪区域宽度
  278. * @param {number} height - 裁剪区域高度
  279. * @param {string} savePath - 保存路径
  280. * @returns {Promise<{success: boolean, error?: string}>}
  281. */
  282. export async function cropAndSaveImage(imagePath, x, y, width, height, savePath) {
  283. try {
  284. // 使用相对路径(相对于项目根目录)
  285. const projectRoot = join(__dirname, '..');
  286. // 如果传入的是绝对路径,转换为相对路径
  287. let relativeImagePath = imagePath;
  288. if (isAbsolute(imagePath)) {
  289. try {
  290. relativeImagePath = require('path').relative(projectRoot, imagePath).replace(/\\/g, '/');
  291. } catch (e) {
  292. relativeImagePath = imagePath.replace(/\\/g, '/');
  293. }
  294. } else {
  295. relativeImagePath = imagePath.replace(/\\/g, '/');
  296. }
  297. let relativeSavePath = savePath;
  298. if (isAbsolute(savePath)) {
  299. try {
  300. relativeSavePath = require('path').relative(projectRoot, savePath).replace(/\\/g, '/');
  301. } catch (e) {
  302. relativeSavePath = savePath.replace(/\\/g, '/');
  303. }
  304. } else {
  305. relativeSavePath = savePath.replace(/\\/g, '/');
  306. }
  307. // 构建Python脚本代码
  308. // 使用 pathlib.Path 来处理路径,确保中文路径正确
  309. // 使用相对路径
  310. const normalizedImagePath = relativeImagePath;
  311. const normalizedSavePath = relativeSavePath;
  312. // 转义路径中的特殊字符,确保 Python 字符串正确
  313. const escapedImagePath = normalizedImagePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  314. const escapedSavePath = normalizedSavePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  315. const pythonCode = `
  316. # -*- coding: utf-8 -*-
  317. import sys
  318. import cv2
  319. import os
  320. from pathlib import Path
  321. # 立即输出,确认脚本开始执行
  322. print("Python脚本开始执行", file=sys.stderr)
  323. sys.stderr.flush()
  324. # 使用 Path 对象来处理路径,确保中文路径正确
  325. try:
  326. image_path_obj = Path(r"${escapedImagePath}")
  327. save_path_obj = Path(r"${escapedSavePath}")
  328. print(f"Path对象创建成功", file=sys.stderr)
  329. sys.stderr.flush()
  330. except Exception as e:
  331. print(f"创建Path对象失败: {e}", file=sys.stderr)
  332. sys.stderr.flush()
  333. sys.exit(1)
  334. # 转换为字符串(Path 会自动处理编码)
  335. image_path = str(image_path_obj)
  336. save_path = str(save_path_obj)
  337. x = ${x}
  338. y = ${y}
  339. w = ${width}
  340. h = ${height}
  341. print(f"图片路径: {image_path}", file=sys.stderr)
  342. sys.stderr.flush()
  343. print(f"保存路径: {save_path}", file=sys.stderr)
  344. sys.stderr.flush()
  345. print(f"裁剪参数: x={x}, y={y}, w={w}, h={h}", file=sys.stderr)
  346. sys.stderr.flush()
  347. try:
  348. # 检查图片文件是否存在
  349. print(f"检查图片文件: {image_path_obj}", file=sys.stderr)
  350. sys.stderr.flush()
  351. print(f"图片文件是否存在: {image_path_obj.exists()}", file=sys.stderr)
  352. sys.stderr.flush()
  353. if not image_path_obj.exists():
  354. print(f"错误: 图片文件不存在: {image_path}", file=sys.stderr)
  355. sys.stderr.flush()
  356. # 检查父目录是否存在
  357. parent = image_path_obj.parent
  358. print(f"父目录: {parent}", file=sys.stderr)
  359. sys.stderr.flush()
  360. print(f"父目录是否存在: {parent.exists()}", file=sys.stderr)
  361. sys.stderr.flush()
  362. if parent.exists():
  363. try:
  364. files = list(parent.iterdir())
  365. print(f"父目录中的文件: {[str(f.name) for f in files]}", file=sys.stderr)
  366. sys.stderr.flush()
  367. except Exception as e:
  368. print(f"列出父目录内容失败: {e}", file=sys.stderr)
  369. sys.stderr.flush()
  370. sys.exit(1)
  371. # 读取图片
  372. print(f"开始读取图片: {image_path}", file=sys.stderr)
  373. img = cv2.imread(image_path)
  374. if img is None:
  375. print(f"错误: 无法读取图片 {image_path}", file=sys.stderr)
  376. print(f"cv2.imread 返回 None,可能是文件格式不支持或文件损坏", file=sys.stderr)
  377. sys.exit(1)
  378. print(f"图片读取成功,尺寸: {img.shape}", file=sys.stderr)
  379. # 验证坐标是否在图片范围内
  380. img_height, img_width = img.shape[:2]
  381. if x < 0 or y < 0 or x + w > img_width or y + h > img_height:
  382. print(f"错误: 裁剪区域超出图片范围。图片尺寸: {img_width}x{img_height}, 裁剪区域: x={x}, y={y}, w={w}, h={h}", file=sys.stderr)
  383. sys.exit(1)
  384. # 裁剪区域
  385. cropped = img[y:y+h, x:x+w]
  386. print(f"裁剪成功,裁剪后尺寸: {cropped.shape}", file=sys.stderr)
  387. # 确保保存目录存在
  388. save_dir = save_path_obj.parent
  389. save_dir.mkdir(parents=True, exist_ok=True)
  390. print(f"保存目录已创建/存在: {save_dir}", file=sys.stderr)
  391. # 保存裁剪后的图片
  392. success = cv2.imwrite(str(save_path), cropped)
  393. print(f"cv2.imwrite 返回值: {success}", file=sys.stderr)
  394. if not success:
  395. print(f"错误: cv2.imwrite 返回 False,保存失败", file=sys.stderr)
  396. print(f"尝试保存到: {save_path}", file=sys.stderr)
  397. print(f"保存路径类型: {type(save_path)}", file=sys.stderr)
  398. sys.exit(1)
  399. # 验证文件是否真的保存了
  400. print(f"检查文件是否存在: {save_path_obj}", file=sys.stderr)
  401. print(f"文件是否存在: {save_path_obj.exists()}", file=sys.stderr)
  402. if save_path_obj.exists():
  403. file_size = save_path_obj.stat().st_size
  404. print(f"成功保存区域截图到: {save_path} (文件大小: {file_size} 字节)", file=sys.stderr)
  405. else:
  406. print(f"错误: 文件保存后不存在: {save_path}", file=sys.stderr)
  407. print(f"保存目录是否存在: {save_dir.exists()}", file=sys.stderr)
  408. print(f"保存目录路径: {save_dir}", file=sys.stderr)
  409. # 尝试列出目录内容
  410. try:
  411. if save_dir.exists():
  412. files = list(save_dir.iterdir())
  413. print(f"目录中的文件: {[str(f) for f in files]}", file=sys.stderr)
  414. except Exception as e:
  415. print(f"列出目录内容失败: {e}", file=sys.stderr)
  416. sys.exit(1)
  417. except Exception as e:
  418. print(f"裁剪图片失败: {e}", file=sys.stderr)
  419. import traceback
  420. traceback.print_exc(file=sys.stderr)
  421. sys.exit(1)
  422. `;
  423. // 优先使用项目下的便携版 Python
  424. let pythonExeAbsolutePath = join(projectRoot, 'python', 'python.exe');
  425. let isPortablePython = false;
  426. // 如果便携版 Python 不存在,回退到虚拟环境
  427. if (!existsSync(pythonExeAbsolutePath)) {
  428. isPortablePython = false;
  429. pythonExeAbsolutePath = join(projectRoot, 'py', 'venv', 'Scripts', 'python.exe');
  430. } else {
  431. isPortablePython = true;
  432. }
  433. // 虚拟环境路径(用于设置环境变量)
  434. const venvAbsolutePath = isPortablePython ? join(projectRoot, 'python') : join(projectRoot, 'py', 'venv');
  435. const venvScriptsAbsolutePath = isPortablePython ? join(projectRoot, 'python', 'Scripts') : join(projectRoot, 'py', 'venv', 'Scripts');
  436. // 使用绝对路径执行 Python 命令(确保路径正确)
  437. const pythonCommand = pythonExeAbsolutePath;
  438. // 执行Python脚本
  439. try {
  440. const env = {
  441. ...process.env,
  442. // 设置虚拟环境相关环境变量
  443. VIRTUAL_ENV: venvAbsolutePath,
  444. // 将虚拟环境的 Scripts 目录添加到 PATH 前面,确保使用虚拟环境中的工具
  445. PATH: `${venvScriptsAbsolutePath};${process.env.PATH}`
  446. };
  447. // 使用绝对路径的 Python 命令(用引号包裹,确保路径中的空格被正确处理)
  448. const { stdout, stderr } = await execAsync(`"${pythonCommand}" -c "${pythonCode.replace(/"/g, '\\"')}"`, {
  449. cwd: projectRoot, // 设置工作目录为项目根目录,这样相对路径才能正确解析
  450. maxBuffer: 10 * 1024 * 1024,
  451. encoding: 'utf8',
  452. env: env
  453. });
  454. // 检查是否有错误(Python脚本通过 sys.exit(1) 退出时,execAsync 会抛出错误)
  455. // 但如果脚本正常退出,stderr 可能包含我们的调试信息
  456. if (stderr && !stderr.includes('成功') && !stderr.includes('图片路径') && !stderr.includes('保存路径') && !stderr.includes('裁剪参数') && !stderr.includes('图片读取成功') && !stderr.includes('裁剪成功') && !stderr.includes('保存目录')) {
  457. // 如果 stderr 包含错误信息(不是我们的调试信息),可能是错误
  458. if (!stderr.includes('成功保存')) {
  459. // 不抛出错误,让后续验证文件是否存在
  460. }
  461. }
  462. // 验证文件是否真的保存了
  463. // 检查截图文件是否存在(使用绝对路径进行文件系统检查)
  464. const absoluteImagePath = join(projectRoot, relativeImagePath);
  465. const absoluteSavePath = join(projectRoot, relativeSavePath);
  466. const screenshotExists = fs.existsSync(absoluteImagePath);
  467. if (fs.existsSync(absoluteSavePath)) {
  468. return { success: true };
  469. } else {
  470. // 检查父目录是否存在
  471. const parentDir = dirname(absoluteSavePath);
  472. const parentExists = fs.existsSync(parentDir);
  473. // 构建详细的错误信息(显示相对路径)
  474. let errorMsg = `文件保存失败,文件不存在: ${relativeSavePath}`;
  475. if (!screenshotExists) {
  476. errorMsg += `\n截图文件不存在: ${relativeImagePath}`;
  477. }
  478. if (!parentExists) {
  479. errorMsg += `\n保存目录不存在: ${parentDir}`;
  480. }
  481. if (stderr) {
  482. errorMsg += `\nPython stderr: ${stderr}`;
  483. } else {
  484. errorMsg += `\nPython stderr: (空) - 可能Python脚本未执行或执行失败`;
  485. }
  486. if (stdout) {
  487. errorMsg += `\nPython stdout: ${stdout}`;
  488. }
  489. return { success: false, error: errorMsg };
  490. }
  491. } catch (execError) {
  492. // execAsync 执行失败(Python脚本返回非0退出码)
  493. return { success: false, error: execError.stderr || execError.message || 'Python脚本执行失败' };
  494. }
  495. } catch (error) {
  496. return { success: false, error: error.message };
  497. }
  498. }
  499. /**
  500. * 执行文字识别:截图、调用 Python 脚本、返回坐标
  501. * @param {string} ipPort - 设备 ID/IP:Port
  502. * @param {string} targetText - 目标文字
  503. * @returns {Promise<{success: boolean, error?: string, coordinate?: Object, clickPosition?: Object}>}
  504. */
  505. export async function findTextAndGetCoordinate(ipPort, targetText) {
  506. try {
  507. if (!ipPort) {
  508. return { success: false, error: '缺少设备 ID' };
  509. }
  510. if (!targetText) {
  511. return { success: false, error: '缺少目标文字' };
  512. }
  513. // 1. 获取设备分辨率
  514. const resolutionResult = await getDeviceResolution(ipPort);
  515. if (!resolutionResult.success) {
  516. return { success: false, error: '获取设备分辨率失败' };
  517. }
  518. const { width, height } = resolutionResult;
  519. // 2. 获取屏幕截图
  520. const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
  521. if (!screenshotResult.success || !screenshotResult.data) {
  522. return { success: false, error: '获取屏幕截图失败' };
  523. }
  524. // 3. 保存截图到临时文件
  525. const tempDir = join(__dirname, '..');
  526. const screenshotPath = join(tempDir, 'temp_screenshot.png');
  527. const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
  528. await writeFile(screenshotPath, screenshotBuffer);
  529. // 4. 调用 JS 函数进行文字识别
  530. const textResult = await findTextLocation(screenshotPath, targetText, width, height);
  531. if (!textResult.success || !textResult.found) {
  532. return { success: false, error: textResult.error || `未找到文字: ${targetText}` };
  533. }
  534. // 5. 返回识别结果
  535. const { x, y, width: w, height: h } = textResult;
  536. // 计算点击位置(中心点)
  537. const clickX = Math.round(x + w / 2);
  538. const clickY = Math.round(y + h / 2);
  539. return {
  540. success: true,
  541. coordinate: { x, y, width: w, height: h },
  542. clickPosition: { x: clickX, y: clickY }
  543. };
  544. } catch (error) {
  545. // 如果是超时错误,提供更友好的提示
  546. if (error.message && error.message.includes('timeout')) {
  547. return { success: false, error: '文字识别超时,请检查网络连接或稍后重试' };
  548. }
  549. return { success: false, error: error.message };
  550. }
  551. }
  552. /**
  553. * 全屏OCR识别(通用功能)
  554. * @param {string} ipPort - 设备 ID/IP:Port
  555. * @param {string} folderPath - 工作流文件夹路径(可选,用于保存临时文件)
  556. * @returns {Promise<{success: boolean, error?: string, text?: string}>}
  557. */
  558. export async function ocrFullScreen(ipPort, folderPath = null) {
  559. try {
  560. if (!ipPort) {
  561. return { success: false, error: '缺少设备 ID' };
  562. }
  563. // 1. 获取设备分辨率
  564. const resolutionResult = await getDeviceResolution(ipPort);
  565. if (!resolutionResult.success) {
  566. return { success: false, error: '获取设备分辨率失败' };
  567. }
  568. const { width, height } = resolutionResult;
  569. // 2. 获取屏幕截图
  570. const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
  571. if (!screenshotResult.success || !screenshotResult.data) {
  572. return { success: false, error: '获取屏幕截图失败' };
  573. }
  574. // 3. 保存截图到临时文件(如果提供了工作流文件夹,保存到 tmp/时间戳 目录)
  575. let screenshotPath;
  576. let tmpDir = null; // 用于跟踪需要删除的临时目录
  577. if (folderPath) {
  578. // 确保 folderPath 是绝对路径
  579. let absoluteFolderPath = folderPath;
  580. if (!isAbsolute(folderPath)) {
  581. // 如果已经是 static/processing/xxx 格式,去掉开头的 static/processing 再拼接
  582. if (folderPath.startsWith('static/processing/')) {
  583. const folderName = folderPath.replace('static/processing/', '');
  584. absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
  585. } else if (folderPath.startsWith('static\\processing\\')) {
  586. const folderName = folderPath.replace('static\\processing\\', '');
  587. absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
  588. } else {
  589. // 如果只是文件夹名,需要加上 static/processing
  590. absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderPath);
  591. }
  592. }
  593. const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19).replace('T', '_');
  594. tmpDir = join(absoluteFolderPath, 'tmp', timestamp);
  595. await mkdir(tmpDir, { recursive: true });
  596. screenshotPath = join(tmpDir, 'screenshot_ocr.png');
  597. } else {
  598. const tempDir = join(__dirname, '..');
  599. screenshotPath = join(tempDir, 'temp_screenshot_ocr.png');
  600. }
  601. const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
  602. await writeFile(screenshotPath, screenshotBuffer);
  603. try {
  604. // 4. 调用 JS 实现进行全屏OCR识别
  605. const normalizedScreenshotPath = screenshotPath.replace(/\\/g, '/');
  606. const result = await ocrFullScreenFromFunc(normalizedScreenshotPath, width, height);
  607. if (result.success) {
  608. return {
  609. success: true,
  610. text: result.text || ''
  611. };
  612. } else {
  613. return { success: false, error: result.error || 'OCR识别失败' };
  614. }
  615. } finally {
  616. // 5. 使用完后,先判断 tmp 目录总大小是否超过 20MB,再决定是否删除临时目录
  617. if (tmpDir) {
  618. try {
  619. // 获取 tmp 目录的父目录(工作流目录下的 tmp 文件夹)
  620. const tmpParentDir = dirname(tmpDir);
  621. // 检查 tmp 目录下所有文件和子目录的总大小
  622. let totalSize = 0;
  623. const dirsToDelete = [];
  624. try {
  625. const entries = await readdir(tmpParentDir, { withFileTypes: true });
  626. for (const entry of entries) {
  627. const entryPath = join(tmpParentDir, entry.name);
  628. try {
  629. if (entry.isFile()) {
  630. const stats = await stat(entryPath);
  631. totalSize += stats.size;
  632. } else if (entry.isDirectory()) {
  633. // 递归计算子目录大小
  634. const dirSize = await calculateDirSize(entryPath);
  635. totalSize += dirSize;
  636. const dirStats = await stat(entryPath);
  637. dirsToDelete.push({ path: entryPath, size: dirSize, mtime: dirStats.mtime });
  638. }
  639. } catch (e) {
  640. // 忽略无法访问的文件
  641. }
  642. }
  643. } catch (e) {
  644. // 如果无法读取目录,直接删除临时目录
  645. await rm(tmpDir, { recursive: true, force: true });
  646. return;
  647. }
  648. const maxSize = 20 * 1024 * 1024; // 20MB
  649. // 如果总大小超过 20MB,删除时间最早的目录
  650. if (totalSize > maxSize) {
  651. // 按修改时间排序(最早的在前)
  652. dirsToDelete.sort((a, b) => a.mtime - b.mtime);
  653. // 删除最早的目录直到总大小小于 20MB
  654. for (const dirInfo of dirsToDelete) {
  655. if (totalSize <= maxSize) {
  656. break;
  657. }
  658. try {
  659. await rm(dirInfo.path, { recursive: true, force: true });
  660. totalSize -= dirInfo.size;
  661. } catch (e) {
  662. // 忽略删除失败
  663. }
  664. }
  665. }
  666. // 如果临时目录仍然存在且总大小未超过限制,也删除它(保持原有行为)
  667. try {
  668. const tmpDirExists = await stat(tmpDir).then(() => true).catch(() => false);
  669. if (tmpDirExists) {
  670. await rm(tmpDir, { recursive: true, force: true });
  671. }
  672. } catch (rmError) {
  673. // 忽略删除失败
  674. }
  675. } catch (error) {
  676. // 清理失败不影响主流程
  677. }
  678. }
  679. }
  680. } catch (error) {
  681. if (error.message && error.message.includes('timeout')) {
  682. return { success: false, error: 'OCR识别超时,请检查网络连接或稍后重试' };
  683. }
  684. return { success: false, error: error.message };
  685. }
  686. }
  687. /**
  688. * OCR识别最后一条消息(兼容旧API)
  689. * @param {string} ipPort - 设备 ID/IP:Port
  690. * @param {string} method - 识别方法 ('full-screen' | 'by-avatar')
  691. * @param {string} avatarPath - 头像路径(by-avatar 时使用)
  692. * @param {string} area - 区域(未使用,保留兼容性)
  693. * @param {string} folderPath - 工作流文件夹路径(可选)
  694. * @returns {Promise<{success: boolean, error?: string, text?: string, position?: Object}>}
  695. */
  696. export async function ocrLastMessage(ipPort, method, avatarPath, area, folderPath = null) {
  697. try {
  698. if (!ipPort) {
  699. return { success: false, error: '缺少设备 ID' };
  700. }
  701. // 1. 获取设备分辨率
  702. const resolutionResult = await getDeviceResolution(ipPort);
  703. if (!resolutionResult.success) {
  704. return { success: false, error: '获取设备分辨率失败' };
  705. }
  706. const { width, height } = resolutionResult;
  707. // 2. 获取屏幕截图
  708. const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
  709. if (!screenshotResult.success || !screenshotResult.data) {
  710. return { success: false, error: '获取屏幕截图失败' };
  711. }
  712. // 3. 保存截图到临时文件(如果提供了工作流文件夹,保存到 tmp/时间戳 目录)
  713. let screenshotPath;
  714. let tmpDir = null; // 用于跟踪需要删除的临时目录
  715. if (folderPath) {
  716. // 确保 folderPath 是绝对路径
  717. let absoluteFolderPath = folderPath;
  718. if (!isAbsolute(folderPath)) {
  719. // 如果已经是 static/processing/xxx 格式,去掉开头的 static/processing 再拼接
  720. if (folderPath.startsWith('static/processing/')) {
  721. const folderName = folderPath.replace('static/processing/', '');
  722. absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
  723. } else if (folderPath.startsWith('static\\processing\\')) {
  724. const folderName = folderPath.replace('static\\processing\\', '');
  725. absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
  726. } else {
  727. // 如果只是文件夹名,需要加上 static/processing
  728. absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderPath);
  729. }
  730. }
  731. const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19).replace('T', '_');
  732. tmpDir = join(absoluteFolderPath, 'tmp', timestamp);
  733. await mkdir(tmpDir, { recursive: true });
  734. screenshotPath = join(tmpDir, 'screenshot_ocr.png');
  735. } else {
  736. const tempDir = join(__dirname, '..');
  737. screenshotPath = join(tempDir, 'temp_screenshot_ocr.png');
  738. }
  739. const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
  740. await writeFile(screenshotPath, screenshotBuffer);
  741. try {
  742. // 4. 调用 JS 实现进行OCR识别
  743. const normalizedScreenshotPath = screenshotPath.replace(/\\/g, '/');
  744. let result;
  745. if (method === 'full-screen') {
  746. // 全屏OCR识别
  747. result = await ocrFullScreenFromFunc(normalizedScreenshotPath, width, height);
  748. } else if (method === 'by-avatar' && avatarPath) {
  749. // 通过头像定位最后一条消息
  750. let friendAvatarArg = null;
  751. let myAvatarArg = null;
  752. if (isAbsolute(avatarPath)) {
  753. friendAvatarArg = avatarPath;
  754. myAvatarArg = avatarPath;
  755. } else {
  756. const folderName = avatarPath.split(/[/\\]/)[0];
  757. const avatarName = avatarPath.split(/[/\\]/).slice(1).join('/');
  758. friendAvatarArg = join(__dirname, '..', 'static', 'processing', folderName, avatarName);
  759. myAvatarArg = friendAvatarArg;
  760. }
  761. const normalizedFriendAvatar = friendAvatarArg.replace(/\\/g, '/');
  762. const normalizedMyAvatar = myAvatarArg.replace(/\\/g, '/');
  763. result = await getLastMessageFromFunc(normalizedScreenshotPath, normalizedFriendAvatar, normalizedMyAvatar, width, height);
  764. } else {
  765. // 默认使用全屏OCR
  766. result = await ocrFullScreenFromFunc(normalizedScreenshotPath, width, height);
  767. }
  768. if (result.success) {
  769. // 返回兼容旧API的格式
  770. return {
  771. success: true,
  772. text: result.text || '',
  773. position: result.position || null
  774. };
  775. } else {
  776. return { success: false, error: result.error || 'OCR识别失败' };
  777. }
  778. } finally {
  779. // 5. 使用完后,先判断 tmp 目录总大小是否超过 20MB,再决定是否删除临时目录
  780. if (tmpDir) {
  781. try {
  782. // 获取 tmp 目录的父目录(工作流目录下的 tmp 文件夹)
  783. const tmpParentDir = dirname(tmpDir);
  784. // 检查 tmp 目录下所有文件和子目录的总大小
  785. let totalSize = 0;
  786. const dirsToDelete = [];
  787. try {
  788. const entries = await readdir(tmpParentDir, { withFileTypes: true });
  789. for (const entry of entries) {
  790. const entryPath = join(tmpParentDir, entry.name);
  791. try {
  792. if (entry.isFile()) {
  793. const stats = await stat(entryPath);
  794. totalSize += stats.size;
  795. } else if (entry.isDirectory()) {
  796. // 递归计算子目录大小
  797. const dirSize = await calculateDirSize(entryPath);
  798. totalSize += dirSize;
  799. const dirStats = await stat(entryPath);
  800. dirsToDelete.push({ path: entryPath, size: dirSize, mtime: dirStats.mtime });
  801. }
  802. } catch (e) {
  803. // 忽略无法访问的文件
  804. }
  805. }
  806. } catch (e) {
  807. // 如果无法读取目录,直接删除临时目录
  808. await rm(tmpDir, { recursive: true, force: true });
  809. return;
  810. }
  811. const maxSize = 20 * 1024 * 1024; // 20MB
  812. // 如果总大小超过 20MB,删除时间最早的目录
  813. if (totalSize > maxSize) {
  814. // 按修改时间排序(最早的在前)
  815. dirsToDelete.sort((a, b) => a.mtime - b.mtime);
  816. // 删除最早的目录直到总大小小于 20MB
  817. for (const dirInfo of dirsToDelete) {
  818. if (totalSize <= maxSize) {
  819. break;
  820. }
  821. try {
  822. await rm(dirInfo.path, { recursive: true, force: true });
  823. totalSize -= dirInfo.size;
  824. } catch (e) {
  825. // 忽略删除失败
  826. }
  827. }
  828. }
  829. // 如果临时目录仍然存在且总大小未超过限制,也删除它(保持原有行为)
  830. try {
  831. const tmpDirExists = await stat(tmpDir).then(() => true).catch(() => false);
  832. if (tmpDirExists) {
  833. await rm(tmpDir, { recursive: true, force: true });
  834. }
  835. } catch (rmError) {
  836. // 忽略删除失败
  837. }
  838. } catch (error) {
  839. // 清理失败不影响主流程
  840. }
  841. }
  842. }
  843. } catch (error) {
  844. if (error.message && error.message.includes('timeout')) {
  845. return { success: false, error: 'OCR识别超时,请检查网络连接或稍后重试' };
  846. }
  847. return { success: false, error: error.message };
  848. }
  849. }
  850. /**
  851. * 检测虚拟环境的 Python 是否安装正确
  852. * @returns {Promise<{success: boolean, details: Object, error?: string}>}
  853. */
  854. export async function checkPythonEnvironment() {
  855. try {
  856. // 获取项目根目录
  857. const projectRoot = join(__dirname, '..');
  858. // 优先使用项目下的便携版 Python
  859. let pythonExePath = join(projectRoot, 'python', 'python.exe');
  860. let isPortablePython = false;
  861. // 如果便携版 Python 不存在,回退到虚拟环境
  862. if (!existsSync(pythonExePath)) {
  863. pythonExePath = join(projectRoot, 'py', 'venv', 'Scripts', 'python.exe');
  864. isPortablePython = false;
  865. } else {
  866. isPortablePython = true;
  867. }
  868. const details = {
  869. projectRoot,
  870. pythonExePath,
  871. isPortablePython,
  872. pythonExists: false,
  873. pythonVersion: null,
  874. pythonVersionRaw: null,
  875. packages: {},
  876. pyvenvCfg: null,
  877. errors: []
  878. };
  879. // 1. 检查 Python 可执行文件是否存在
  880. if (!existsSync(pythonExePath)) {
  881. details.errors.push(`Python 可执行文件不存在: ${pythonExePath}`);
  882. return { success: false, details, error: `Python 可执行文件不存在。尝试的路径:\n1. ${join(projectRoot, 'python', 'python.exe')}\n2. ${pythonExePath}` };
  883. }
  884. details.pythonExists = true;
  885. // 2. 检查 pyvenv.cfg 配置(仅当使用虚拟环境时)
  886. if (!isPortablePython) {
  887. const pyvenvCfgPath = join(projectRoot, 'py', 'venv', 'pyvenv.cfg');
  888. if (existsSync(pyvenvCfgPath)) {
  889. try {
  890. const cfgContent = await readFile(pyvenvCfgPath, 'utf8');
  891. details.pyvenvCfg = cfgContent;
  892. } catch (e) {
  893. details.errors.push(`无法读取 pyvenv.cfg: ${e.message}`);
  894. }
  895. } else {
  896. details.errors.push('pyvenv.cfg 文件不存在');
  897. }
  898. } else {
  899. // 便携版 Python 不需要 pyvenv.cfg
  900. details.pyvenvCfg = '使用便携版 Python,无需 pyvenv.cfg';
  901. }
  902. // 3. 检查 Python 版本
  903. try {
  904. const { stdout: versionOutput } = await execAsync(`"${pythonExePath}" --version`, {
  905. encoding: 'utf8',
  906. timeout: 5000,
  907. cwd: projectRoot
  908. });
  909. details.pythonVersionRaw = versionOutput.trim();
  910. // 提取版本号
  911. const versionMatch = versionOutput.match(/Python (\d+\.\d+\.\d+)/);
  912. if (versionMatch) {
  913. details.pythonVersion = versionMatch[1];
  914. }
  915. } catch (e) {
  916. details.errors.push(`无法获取 Python 版本: ${e.message}`);
  917. }
  918. // 4. 检查必要的 Python 包
  919. const requiredPackages = [
  920. { name: 'cv2', importName: 'cv2', displayName: 'OpenCV' },
  921. { name: 'numpy', importName: 'numpy', displayName: 'NumPy' },
  922. { name: 'onnxocr', importName: 'onnxocr', displayName: 'OnnxOCR' }
  923. ];
  924. for (const pkg of requiredPackages) {
  925. try {
  926. const { stdout } = await execAsync(`"${pythonExePath}" -c "import ${pkg.importName}; print(${pkg.importName}.__version__ if hasattr(${pkg.importName}, '__version__') else 'installed')"`, {
  927. encoding: 'utf8',
  928. timeout: 5000,
  929. cwd: projectRoot,
  930. env: {
  931. ...process.env,
  932. PYTHONIOENCODING: 'utf-8',
  933. PYTHONUTF8: '1'
  934. }
  935. });
  936. details.packages[pkg.name] = {
  937. installed: true,
  938. version: stdout.trim() || 'installed',
  939. displayName: pkg.displayName
  940. };
  941. } catch (e) {
  942. details.packages[pkg.name] = {
  943. installed: false,
  944. error: e.message,
  945. displayName: pkg.displayName
  946. };
  947. details.errors.push(`${pkg.displayName} (${pkg.name}) 未安装或无法导入: ${e.message}`);
  948. }
  949. }
  950. // 5. 检查 Python 环境结构
  951. if (isPortablePython) {
  952. // 便携版 Python 的结构
  953. const pythonDirs = {
  954. Scripts: join(projectRoot, 'python', 'Scripts'),
  955. Lib: join(projectRoot, 'python', 'Lib'),
  956. 'site-packages': join(projectRoot, 'python', 'Lib', 'site-packages')
  957. };
  958. details.venvStructure = {};
  959. for (const [name, path] of Object.entries(pythonDirs)) {
  960. details.venvStructure[name] = {
  961. exists: existsSync(path),
  962. path
  963. };
  964. if (!existsSync(path) && name !== 'site-packages') {
  965. details.errors.push(`Python 目录不存在: ${name} (${path})`);
  966. }
  967. }
  968. } else {
  969. // 虚拟环境的结构
  970. const venvDirs = {
  971. Scripts: join(projectRoot, 'py', 'venv', 'Scripts'),
  972. Lib: join(projectRoot, 'py', 'venv', 'Lib'),
  973. 'site-packages': join(projectRoot, 'py', 'venv', 'Lib', 'site-packages')
  974. };
  975. details.venvStructure = {};
  976. for (const [name, path] of Object.entries(venvDirs)) {
  977. details.venvStructure[name] = {
  978. exists: existsSync(path),
  979. path
  980. };
  981. if (!existsSync(path)) {
  982. details.errors.push(`虚拟环境目录不存在: ${name} (${path})`);
  983. }
  984. }
  985. }
  986. // 判断整体是否成功
  987. const hasCriticalErrors = details.errors.length > 0 && (
  988. !details.pythonExists ||
  989. !details.pythonVersion ||
  990. !details.packages.cv2?.installed ||
  991. !details.packages.numpy?.installed
  992. );
  993. return {
  994. success: !hasCriticalErrors,
  995. details,
  996. error: hasCriticalErrors ? `检测到关键问题: ${details.errors.slice(0, 3).join('; ')}` : null
  997. };
  998. } catch (error) {
  999. return {
  1000. success: false,
  1001. details: { error: error.message },
  1002. error: `检测 Python 环境时出错: ${error.message}`
  1003. };
  1004. }
  1005. }
  1006. /**
  1007. * 注册 IPC 处理器(Python 执行相关)
  1008. */
  1009. export function registerIpcHandlers() {
  1010. // 图像匹配
  1011. ipcMain.handle('match-image-and-get-coordinate', async (event, ipPort, templateImagePath) => {
  1012. return await matchImageAndGetCoordinate(ipPort, templateImagePath);
  1013. });
  1014. // 图像区域定位
  1015. ipcMain.handle('match-image-region-location', async (event, screenshotPath, regionPath, device) => {
  1016. return await matchImageRegionLocation(screenshotPath, regionPath, device);
  1017. });
  1018. ipcMain.handle('crop-and-save-image', async (event, imagePath, x, y, width, height, savePath) => {
  1019. const result = await cropAndSaveImage(imagePath, x, y, width, height, savePath);
  1020. return result;
  1021. });
  1022. // 文字识别
  1023. ipcMain.handle('find-text-and-get-coordinate', async (event, ipPort, targetText) => {
  1024. return await findTextAndGetCoordinate(ipPort, targetText);
  1025. });
  1026. // OCR识别最后一条消息(兼容旧API)
  1027. ipcMain.handle('ocr-last-message', async (event, ipPort, method, avatarPath, area, folderPath) => {
  1028. return await ocrLastMessage(ipPort, method, avatarPath, area, folderPath);
  1029. });
  1030. // 检测 Python 环境
  1031. ipcMain.handle('check-python-environment', async () => {
  1032. return await checkPythonEnvironment();
  1033. });
  1034. }