| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166 |
- /**
- * 执行 Python 相关操作模块(通用功能)
- * 负责图像匹配、OCR识别等通用功能(通过调用 Python/JS 实现)
- * 注意:聊天记录提取等业务相关功能在 read-and-write.js 中
- */
- import { ipcMain } from 'electron';
- import { writeFile, mkdir, rm, readdir, stat, readFile } from 'fs/promises';
- import fs, { existsSync } from 'fs';
- import { join, dirname, isAbsolute } from 'path';
- import { fileURLToPath } from 'url';
- import { exec } from 'child_process';
- import { promisify } from 'util';
- import { captureScreenshot } from './adb/screenshot.js';
- import { getDeviceResolution } from './adb/device-info.js';
- import { matchImage } from './func/image-center-location.js';
- import { findTextLocation } from './func/string-reg-location.js';
- import { ocrFullScreen as ocrFullScreenFromFunc, getLastMessage as getLastMessageFromFunc } from './func/ocr-chat.js';
- const execAsync = promisify(exec);
- const __filename = fileURLToPath(import.meta.url);
- const __dirname = dirname(__filename);
- /**
- * 确保 pyvenv.cfg 文件使用当前系统的 Python 路径
- * @param {string} projectRoot - 项目根目录
- * @returns {Promise<void>}
- */
- async function ensurePyvenvConfig(projectRoot) {
- const pyvenvCfgPath = join(projectRoot, 'py', 'venv', 'pyvenv.cfg');
-
- if (!existsSync(pyvenvCfgPath)) {
- return; // 如果文件不存在,跳过
- }
-
- try {
- // 读取现有配置
- const currentContent = await readFile(pyvenvCfgPath, 'utf8');
-
- // 尝试从现有配置中提取系统 Python 路径
- const homeMatch = currentContent.match(/^home\s*=\s*(.+)$/m);
- const executableMatch = currentContent.match(/^executable\s*=\s*(.+)$/m);
-
- // 如果配置文件中已经有路径,检查路径是否存在
- if (homeMatch && executableMatch) {
- const existingHome = homeMatch[1].trim();
- const existingExecutable = executableMatch[1].trim();
-
- // 检查系统 Python 是否存在
- if (existsSync(existingExecutable)) {
- // 路径存在,不需要更新
- return;
- }
- }
-
- // 如果配置文件中的路径不存在,使用系统 Python 检测
- // 使用系统 Python(不是虚拟环境中的),因为我们需要检测系统 Python 路径
- const { stdout } = await execAsync('python -c "import sys; import os; print(os.path.dirname(sys.executable))"', {
- encoding: 'utf8',
- timeout: 5000,
- cwd: projectRoot
- });
- const pythonHome = stdout.trim();
-
- if (!pythonHome) {
- return; // 如果无法检测,跳过
- }
-
- const pythonExe = join(pythonHome, 'python.exe');
-
- // 检查系统 Python 是否存在
- if (!existsSync(pythonExe)) {
- return; // 系统 Python 不存在,跳过
- }
-
- // 检测 Python 版本(使用系统 Python)
- const { stdout: versionOutput } = await execAsync('python -c "import sys; print(\"{}.{}.{}\".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro))"', {
- encoding: 'utf8',
- timeout: 5000,
- cwd: projectRoot
- });
- const pythonVersion = versionOutput.trim();
-
- // 更新配置
- const newContent = `home = ${pythonHome}
- include-system-site-packages = false
- version = ${pythonVersion}
- executable = ${pythonExe}
- command = ${pythonExe} -m venv py/venv
- `;
-
- await writeFile(pyvenvCfgPath, newContent, 'utf8');
- } catch (error) {
- // 静默失败,不影响主流程
- console.warn('无法更新 pyvenv.cfg:', error.message);
- }
- }
- /**
- * 递归计算目录大小
- * @param {string} dirPath - 目录路径
- * @returns {Promise<number>} 目录总大小(字节)
- */
- async function calculateDirSize(dirPath) {
- let totalSize = 0;
- try {
- const entries = await readdir(dirPath, { withFileTypes: true });
- for (const entry of entries) {
- const entryPath = join(dirPath, entry.name);
- try {
- if (entry.isFile()) {
- const stats = await stat(entryPath);
- totalSize += stats.size;
- } else if (entry.isDirectory()) {
- totalSize += await calculateDirSize(entryPath);
- }
- } catch (e) {
- // 忽略无法访问的文件/目录
- }
- }
- } catch (e) {
- // 忽略无法读取的目录
- }
- return totalSize;
- }
- /**
- * 执行图像匹配:截图、调用 Python 脚本、返回坐标
- * @param {string} ipPort - 设备 ID/IP:Port
- * @param {string} templateImagePath - 模板图片路径
- * @returns {Promise<{success: boolean, error?: string, coordinate?: Object, clickPosition?: Object}>}
- */
- export async function matchImageAndGetCoordinate(ipPort, templateImagePath) {
- try {
- if (!ipPort) {
- return { success: false, error: '缺少设备 ID' };
- }
- if (!templateImagePath) {
- return { success: false, error: '缺少模板图片路径' };
- }
- // 将相对路径转换为绝对路径
- let absoluteTemplatePath = templateImagePath;
- if (!isAbsolute(templateImagePath)) {
- absoluteTemplatePath = join(__dirname, '..', templateImagePath);
- }
- // 1. 获取设备分辨率
- const resolutionResult = await getDeviceResolution(ipPort);
- if (!resolutionResult.success) {
- return { success: false, error: '获取设备分辨率失败' };
- }
- const { width, height } = resolutionResult;
- // 2. 获取屏幕截图
- const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
- if (!screenshotResult.success || !screenshotResult.data) {
- return { success: false, error: '获取屏幕截图失败' };
- }
- // 3. 保存截图到临时文件
- const tempDir = join(__dirname, '..');
- const screenshotPath = join(tempDir, 'temp_screenshot.png');
- const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
- await writeFile(screenshotPath, screenshotBuffer);
- // 4. 调用 JS 函数进行图像匹配
- const matchResult = await matchImage(screenshotPath, absoluteTemplatePath, width, height);
-
- if (!matchResult.success) {
- return { success: false, error: matchResult.error || '图像匹配失败' };
- }
- // 5. 返回匹配结果
- if (matchResult.success && matchResult.x !== undefined) {
- const { x, y, width: w, height: h } = matchResult;
-
- // 计算点击位置(中心点)
- const clickX = Math.round(x + w / 2);
- const clickY = Math.round(y + h / 2);
- return {
- success: true,
- coordinate: { x, y, width: w, height: h },
- clickPosition: { x: clickX, y: clickY }
- };
- } else {
- return {
- success: false,
- error: matchResult.error || '图像匹配失败'
- };
- }
- } catch (error) {
- return { success: false, error: error.message };
- }
- }
- /**
- * 图像区域定位:在完整截图中查找区域截图的位置,返回四个顶点坐标
- * @param {string} screenshotPath - 完整截图路径
- * @param {string} regionPath - 区域截图路径
- * @param {string} device - 设备 ID(可选,用于获取分辨率)
- * @returns {Promise<{success: boolean, error?: string, corners?: Object}>}
- */
- export async function matchImageRegionLocation(screenshotPath, regionPath, device = null) {
- try {
- if (!regionPath) {
- return { success: false, error: '缺少区域截图路径' };
- }
- // 使用相对路径(相对于项目根目录)
- const projectRoot = join(__dirname, '..');
-
- // 确保 pyvenv.cfg 使用当前系统的 Python 路径
- await ensurePyvenvConfig(projectRoot);
-
- // 如果 screenshotPath 为 '__AUTO_SCREENSHOT__' 或 null,自动从设备获取截图
- let relativeScreenshotPath = screenshotPath;
- if (!screenshotPath || screenshotPath === '__AUTO_SCREENSHOT__' || screenshotPath === null) {
- if (!device) {
- return { success: false, error: '缺少完整截图路径,且无法自动获取设备截图(缺少设备ID)' };
- }
-
- // 自动获取设备截图
- const resolutionResult = await getDeviceResolution(device);
- if (!resolutionResult.success) {
- return { success: false, error: '获取设备分辨率失败' };
- }
- const screenshotResult = await captureScreenshot(device, { format: 'png' });
- if (!screenshotResult.success || !screenshotResult.data) {
- return { success: false, error: '自动获取设备截图失败' };
- }
- // 保存截图到临时文件(使用相对路径)
- relativeScreenshotPath = 'temp_screenshot.png';
- const tempScreenshotAbsolutePath = join(projectRoot, relativeScreenshotPath);
- const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
- await writeFile(tempScreenshotAbsolutePath, screenshotBuffer);
- } else {
- // 如果传入的是绝对路径,转换为相对路径
- if (isAbsolute(screenshotPath)) {
- try {
- relativeScreenshotPath = require('path').relative(projectRoot, screenshotPath).replace(/\\/g, '/');
- } catch (e) {
- relativeScreenshotPath = screenshotPath.replace(/\\/g, '/');
- }
- } else {
- relativeScreenshotPath = screenshotPath.replace(/\\/g, '/');
- }
- }
- // 如果传入的是绝对路径,转换为相对路径
- let relativeRegionPath = regionPath;
- if (isAbsolute(regionPath)) {
- try {
- relativeRegionPath = require('path').relative(projectRoot, regionPath).replace(/\\/g, '/');
- } catch (e) {
- relativeRegionPath = regionPath.replace(/\\/g, '/');
- }
- } else {
- relativeRegionPath = regionPath.replace(/\\/g, '/');
- }
- // 可选:如果提供了设备ID,获取设备分辨率用于缩放
- let width = null;
- let height = null;
- if (device) {
- const resolutionResult = await getDeviceResolution(device);
- if (resolutionResult.success) {
- width = resolutionResult.width;
- height = resolutionResult.height;
- }
- }
- // 调用图像匹配函数(使用相对路径)
- const matchResult = await matchImage(relativeScreenshotPath, relativeRegionPath, width, height);
-
- if (!matchResult.success) {
- return { success: false, error: matchResult.error || '图像匹配失败' };
- }
- // 获取匹配结果
- const { x, y, width: w, height: h } = matchResult;
-
- // 计算四个顶点坐标
- const corners = {
- topLeft: { x, y },
- topRight: { x: x + w, y },
- bottomLeft: { x, y: y + h },
- bottomRight: { x: x + w, y: y + h }
- };
- // 如果提供了保存路径,裁剪并保存区域图片
- // 这个功能会在 executeImageRegionLocation 中调用时传入 savePath
- // 但为了保持API简洁,我们在这里不处理,而是在 executeImageRegionLocation 中处理
- return {
- success: true,
- x,
- y,
- width: w,
- height: h,
- corners: corners,
- similarity: matchResult.similarity,
- screenshotPath: relativeScreenshotPath // 返回截图路径(相对路径),用于后续裁剪
- };
- } catch (error) {
- // 图像区域定位失败
- return { success: false, error: error.message };
- }
- }
- /**
- * 裁剪并保存图片区域
- * @param {string} imagePath - 原图片路径
- * @param {number} x - 裁剪区域左上角x坐标
- * @param {number} y - 裁剪区域左上角y坐标
- * @param {number} width - 裁剪区域宽度
- * @param {number} height - 裁剪区域高度
- * @param {string} savePath - 保存路径
- * @returns {Promise<{success: boolean, error?: string}>}
- */
- export async function cropAndSaveImage(imagePath, x, y, width, height, savePath) {
- try {
- // 使用相对路径(相对于项目根目录)
- const projectRoot = join(__dirname, '..');
-
- // 如果传入的是绝对路径,转换为相对路径
- let relativeImagePath = imagePath;
- if (isAbsolute(imagePath)) {
- try {
- relativeImagePath = require('path').relative(projectRoot, imagePath).replace(/\\/g, '/');
- } catch (e) {
- relativeImagePath = imagePath.replace(/\\/g, '/');
- }
- } else {
- relativeImagePath = imagePath.replace(/\\/g, '/');
- }
-
- let relativeSavePath = savePath;
- if (isAbsolute(savePath)) {
- try {
- relativeSavePath = require('path').relative(projectRoot, savePath).replace(/\\/g, '/');
- } catch (e) {
- relativeSavePath = savePath.replace(/\\/g, '/');
- }
- } else {
- relativeSavePath = savePath.replace(/\\/g, '/');
- }
-
- // 构建Python脚本代码
- // 使用 pathlib.Path 来处理路径,确保中文路径正确
- // 使用相对路径
- const normalizedImagePath = relativeImagePath;
- const normalizedSavePath = relativeSavePath;
-
- // 转义路径中的特殊字符,确保 Python 字符串正确
- const escapedImagePath = normalizedImagePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
- const escapedSavePath = normalizedSavePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
-
- const pythonCode = `
- # -*- coding: utf-8 -*-
- import sys
- import cv2
- import os
- from pathlib import Path
- # 立即输出,确认脚本开始执行
- print("Python脚本开始执行", file=sys.stderr)
- sys.stderr.flush()
- # 使用 Path 对象来处理路径,确保中文路径正确
- try:
- image_path_obj = Path(r"${escapedImagePath}")
- save_path_obj = Path(r"${escapedSavePath}")
- print(f"Path对象创建成功", file=sys.stderr)
- sys.stderr.flush()
- except Exception as e:
- print(f"创建Path对象失败: {e}", file=sys.stderr)
- sys.stderr.flush()
- sys.exit(1)
- # 转换为字符串(Path 会自动处理编码)
- image_path = str(image_path_obj)
- save_path = str(save_path_obj)
- x = ${x}
- y = ${y}
- w = ${width}
- h = ${height}
- print(f"图片路径: {image_path}", file=sys.stderr)
- sys.stderr.flush()
- print(f"保存路径: {save_path}", file=sys.stderr)
- sys.stderr.flush()
- print(f"裁剪参数: x={x}, y={y}, w={w}, h={h}", file=sys.stderr)
- sys.stderr.flush()
- try:
- # 检查图片文件是否存在
- print(f"检查图片文件: {image_path_obj}", file=sys.stderr)
- sys.stderr.flush()
- print(f"图片文件是否存在: {image_path_obj.exists()}", file=sys.stderr)
- sys.stderr.flush()
- if not image_path_obj.exists():
- print(f"错误: 图片文件不存在: {image_path}", file=sys.stderr)
- sys.stderr.flush()
- # 检查父目录是否存在
- parent = image_path_obj.parent
- print(f"父目录: {parent}", file=sys.stderr)
- sys.stderr.flush()
- print(f"父目录是否存在: {parent.exists()}", file=sys.stderr)
- sys.stderr.flush()
- if parent.exists():
- try:
- files = list(parent.iterdir())
- print(f"父目录中的文件: {[str(f.name) for f in files]}", file=sys.stderr)
- sys.stderr.flush()
- except Exception as e:
- print(f"列出父目录内容失败: {e}", file=sys.stderr)
- sys.stderr.flush()
- sys.exit(1)
-
- # 读取图片
- print(f"开始读取图片: {image_path}", file=sys.stderr)
- img = cv2.imread(image_path)
- if img is None:
- print(f"错误: 无法读取图片 {image_path}", file=sys.stderr)
- print(f"cv2.imread 返回 None,可能是文件格式不支持或文件损坏", file=sys.stderr)
- sys.exit(1)
-
- print(f"图片读取成功,尺寸: {img.shape}", file=sys.stderr)
-
- # 验证坐标是否在图片范围内
- img_height, img_width = img.shape[:2]
- if x < 0 or y < 0 or x + w > img_width or y + h > img_height:
- print(f"错误: 裁剪区域超出图片范围。图片尺寸: {img_width}x{img_height}, 裁剪区域: x={x}, y={y}, w={w}, h={h}", file=sys.stderr)
- sys.exit(1)
-
- # 裁剪区域
- cropped = img[y:y+h, x:x+w]
- print(f"裁剪成功,裁剪后尺寸: {cropped.shape}", file=sys.stderr)
-
- # 确保保存目录存在
- save_dir = save_path_obj.parent
- save_dir.mkdir(parents=True, exist_ok=True)
- print(f"保存目录已创建/存在: {save_dir}", file=sys.stderr)
-
- # 保存裁剪后的图片
- success = cv2.imwrite(str(save_path), cropped)
- print(f"cv2.imwrite 返回值: {success}", file=sys.stderr)
- if not success:
- print(f"错误: cv2.imwrite 返回 False,保存失败", file=sys.stderr)
- print(f"尝试保存到: {save_path}", file=sys.stderr)
- print(f"保存路径类型: {type(save_path)}", file=sys.stderr)
- sys.exit(1)
-
- # 验证文件是否真的保存了
- print(f"检查文件是否存在: {save_path_obj}", file=sys.stderr)
- print(f"文件是否存在: {save_path_obj.exists()}", file=sys.stderr)
- if save_path_obj.exists():
- file_size = save_path_obj.stat().st_size
- print(f"成功保存区域截图到: {save_path} (文件大小: {file_size} 字节)", file=sys.stderr)
- else:
- print(f"错误: 文件保存后不存在: {save_path}", file=sys.stderr)
- print(f"保存目录是否存在: {save_dir.exists()}", file=sys.stderr)
- print(f"保存目录路径: {save_dir}", file=sys.stderr)
- # 尝试列出目录内容
- try:
- if save_dir.exists():
- files = list(save_dir.iterdir())
- print(f"目录中的文件: {[str(f) for f in files]}", file=sys.stderr)
- except Exception as e:
- print(f"列出目录内容失败: {e}", file=sys.stderr)
- sys.exit(1)
- except Exception as e:
- print(f"裁剪图片失败: {e}", file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
- sys.exit(1)
- `;
- // 优先使用项目下的便携版 Python
- let pythonExeAbsolutePath = join(projectRoot, 'python', 'python.exe');
- let isPortablePython = false;
-
- // 如果便携版 Python 不存在,回退到虚拟环境
- if (!existsSync(pythonExeAbsolutePath)) {
- isPortablePython = false;
- pythonExeAbsolutePath = join(projectRoot, 'py', 'venv', 'Scripts', 'python.exe');
- } else {
- isPortablePython = true;
- }
-
- // 虚拟环境路径(用于设置环境变量)
- const venvAbsolutePath = isPortablePython ? join(projectRoot, 'python') : join(projectRoot, 'py', 'venv');
- const venvScriptsAbsolutePath = isPortablePython ? join(projectRoot, 'python', 'Scripts') : join(projectRoot, 'py', 'venv', 'Scripts');
-
- // 使用绝对路径执行 Python 命令(确保路径正确)
- const pythonCommand = pythonExeAbsolutePath;
-
- // 执行Python脚本
- try {
- const env = {
- ...process.env,
- // 设置虚拟环境相关环境变量
- VIRTUAL_ENV: venvAbsolutePath,
- // 将虚拟环境的 Scripts 目录添加到 PATH 前面,确保使用虚拟环境中的工具
- PATH: `${venvScriptsAbsolutePath};${process.env.PATH}`
- };
-
- // 使用绝对路径的 Python 命令(用引号包裹,确保路径中的空格被正确处理)
- const { stdout, stderr } = await execAsync(`"${pythonCommand}" -c "${pythonCode.replace(/"/g, '\\"')}"`, {
- cwd: projectRoot, // 设置工作目录为项目根目录,这样相对路径才能正确解析
- maxBuffer: 10 * 1024 * 1024,
- encoding: 'utf8',
- env: env
- });
-
- // 检查是否有错误(Python脚本通过 sys.exit(1) 退出时,execAsync 会抛出错误)
- // 但如果脚本正常退出,stderr 可能包含我们的调试信息
- if (stderr && !stderr.includes('成功') && !stderr.includes('图片路径') && !stderr.includes('保存路径') && !stderr.includes('裁剪参数') && !stderr.includes('图片读取成功') && !stderr.includes('裁剪成功') && !stderr.includes('保存目录')) {
- // 如果 stderr 包含错误信息(不是我们的调试信息),可能是错误
- if (!stderr.includes('成功保存')) {
- // 不抛出错误,让后续验证文件是否存在
- }
- }
-
- // 验证文件是否真的保存了
- // 检查截图文件是否存在(使用绝对路径进行文件系统检查)
- const absoluteImagePath = join(projectRoot, relativeImagePath);
- const absoluteSavePath = join(projectRoot, relativeSavePath);
- const screenshotExists = fs.existsSync(absoluteImagePath);
-
- if (fs.existsSync(absoluteSavePath)) {
- return { success: true };
- } else {
- // 检查父目录是否存在
- const parentDir = dirname(absoluteSavePath);
- const parentExists = fs.existsSync(parentDir);
-
- // 构建详细的错误信息(显示相对路径)
- let errorMsg = `文件保存失败,文件不存在: ${relativeSavePath}`;
- if (!screenshotExists) {
- errorMsg += `\n截图文件不存在: ${relativeImagePath}`;
- }
- if (!parentExists) {
- errorMsg += `\n保存目录不存在: ${parentDir}`;
- }
- if (stderr) {
- errorMsg += `\nPython stderr: ${stderr}`;
- } else {
- errorMsg += `\nPython stderr: (空) - 可能Python脚本未执行或执行失败`;
- }
- if (stdout) {
- errorMsg += `\nPython stdout: ${stdout}`;
- }
-
- return { success: false, error: errorMsg };
- }
- } catch (execError) {
- // execAsync 执行失败(Python脚本返回非0退出码)
- return { success: false, error: execError.stderr || execError.message || 'Python脚本执行失败' };
- }
- } catch (error) {
- return { success: false, error: error.message };
- }
- }
- /**
- * 执行文字识别:截图、调用 Python 脚本、返回坐标
- * @param {string} ipPort - 设备 ID/IP:Port
- * @param {string} targetText - 目标文字
- * @returns {Promise<{success: boolean, error?: string, coordinate?: Object, clickPosition?: Object}>}
- */
- export async function findTextAndGetCoordinate(ipPort, targetText) {
- try {
- if (!ipPort) {
- return { success: false, error: '缺少设备 ID' };
- }
- if (!targetText) {
- return { success: false, error: '缺少目标文字' };
- }
- // 1. 获取设备分辨率
- const resolutionResult = await getDeviceResolution(ipPort);
- if (!resolutionResult.success) {
- return { success: false, error: '获取设备分辨率失败' };
- }
- const { width, height } = resolutionResult;
- // 2. 获取屏幕截图
- const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
- if (!screenshotResult.success || !screenshotResult.data) {
- return { success: false, error: '获取屏幕截图失败' };
- }
- // 3. 保存截图到临时文件
- const tempDir = join(__dirname, '..');
- const screenshotPath = join(tempDir, 'temp_screenshot.png');
- const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
- await writeFile(screenshotPath, screenshotBuffer);
- // 4. 调用 JS 函数进行文字识别
- const textResult = await findTextLocation(screenshotPath, targetText, width, height);
-
- if (!textResult.success || !textResult.found) {
- return { success: false, error: textResult.error || `未找到文字: ${targetText}` };
- }
- // 5. 返回识别结果
- const { x, y, width: w, height: h } = textResult;
-
- // 计算点击位置(中心点)
- const clickX = Math.round(x + w / 2);
- const clickY = Math.round(y + h / 2);
- return {
- success: true,
- coordinate: { x, y, width: w, height: h },
- clickPosition: { x: clickX, y: clickY }
- };
- } catch (error) {
- // 如果是超时错误,提供更友好的提示
- if (error.message && error.message.includes('timeout')) {
- return { success: false, error: '文字识别超时,请检查网络连接或稍后重试' };
- }
- return { success: false, error: error.message };
- }
- }
- /**
- * 全屏OCR识别(通用功能)
- * @param {string} ipPort - 设备 ID/IP:Port
- * @param {string} folderPath - 工作流文件夹路径(可选,用于保存临时文件)
- * @returns {Promise<{success: boolean, error?: string, text?: string}>}
- */
- export async function ocrFullScreen(ipPort, folderPath = null) {
- try {
- if (!ipPort) {
- return { success: false, error: '缺少设备 ID' };
- }
- // 1. 获取设备分辨率
- const resolutionResult = await getDeviceResolution(ipPort);
- if (!resolutionResult.success) {
- return { success: false, error: '获取设备分辨率失败' };
- }
- const { width, height } = resolutionResult;
- // 2. 获取屏幕截图
- const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
- if (!screenshotResult.success || !screenshotResult.data) {
- return { success: false, error: '获取屏幕截图失败' };
- }
- // 3. 保存截图到临时文件(如果提供了工作流文件夹,保存到 tmp/时间戳 目录)
- let screenshotPath;
- let tmpDir = null; // 用于跟踪需要删除的临时目录
- if (folderPath) {
- // 确保 folderPath 是绝对路径
- let absoluteFolderPath = folderPath;
- if (!isAbsolute(folderPath)) {
- // 如果已经是 static/processing/xxx 格式,去掉开头的 static/processing 再拼接
- if (folderPath.startsWith('static/processing/')) {
- const folderName = folderPath.replace('static/processing/', '');
- absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
- } else if (folderPath.startsWith('static\\processing\\')) {
- const folderName = folderPath.replace('static\\processing\\', '');
- absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
- } else {
- // 如果只是文件夹名,需要加上 static/processing
- absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderPath);
- }
- }
-
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19).replace('T', '_');
- tmpDir = join(absoluteFolderPath, 'tmp', timestamp);
- await mkdir(tmpDir, { recursive: true });
- screenshotPath = join(tmpDir, 'screenshot_ocr.png');
- } else {
- const tempDir = join(__dirname, '..');
- screenshotPath = join(tempDir, 'temp_screenshot_ocr.png');
- }
- const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
- await writeFile(screenshotPath, screenshotBuffer);
- try {
- // 4. 调用 JS 实现进行全屏OCR识别
- const normalizedScreenshotPath = screenshotPath.replace(/\\/g, '/');
- const result = await ocrFullScreenFromFunc(normalizedScreenshotPath, width, height);
-
- if (result.success) {
- return {
- success: true,
- text: result.text || ''
- };
- } else {
- return { success: false, error: result.error || 'OCR识别失败' };
- }
- } finally {
- // 5. 使用完后,先判断 tmp 目录总大小是否超过 20MB,再决定是否删除临时目录
- if (tmpDir) {
- try {
- // 获取 tmp 目录的父目录(工作流目录下的 tmp 文件夹)
- const tmpParentDir = dirname(tmpDir);
-
- // 检查 tmp 目录下所有文件和子目录的总大小
- let totalSize = 0;
- const dirsToDelete = [];
-
- try {
- const entries = await readdir(tmpParentDir, { withFileTypes: true });
- for (const entry of entries) {
- const entryPath = join(tmpParentDir, entry.name);
- try {
- if (entry.isFile()) {
- const stats = await stat(entryPath);
- totalSize += stats.size;
- } else if (entry.isDirectory()) {
- // 递归计算子目录大小
- const dirSize = await calculateDirSize(entryPath);
- totalSize += dirSize;
- const dirStats = await stat(entryPath);
- dirsToDelete.push({ path: entryPath, size: dirSize, mtime: dirStats.mtime });
- }
- } catch (e) {
- // 忽略无法访问的文件
- }
- }
- } catch (e) {
- // 如果无法读取目录,直接删除临时目录
- await rm(tmpDir, { recursive: true, force: true });
- return;
- }
-
- const maxSize = 20 * 1024 * 1024; // 20MB
-
- // 如果总大小超过 20MB,删除时间最早的目录
- if (totalSize > maxSize) {
- // 按修改时间排序(最早的在前)
- dirsToDelete.sort((a, b) => a.mtime - b.mtime);
-
- // 删除最早的目录直到总大小小于 20MB
- for (const dirInfo of dirsToDelete) {
- if (totalSize <= maxSize) {
- break;
- }
- try {
- await rm(dirInfo.path, { recursive: true, force: true });
- totalSize -= dirInfo.size;
- } catch (e) {
- // 忽略删除失败
- }
- }
- }
-
- // 如果临时目录仍然存在且总大小未超过限制,也删除它(保持原有行为)
- try {
- const tmpDirExists = await stat(tmpDir).then(() => true).catch(() => false);
- if (tmpDirExists) {
- await rm(tmpDir, { recursive: true, force: true });
- }
- } catch (rmError) {
- // 忽略删除失败
- }
- } catch (error) {
- // 清理失败不影响主流程
- }
- }
- }
- } catch (error) {
- if (error.message && error.message.includes('timeout')) {
- return { success: false, error: 'OCR识别超时,请检查网络连接或稍后重试' };
- }
- return { success: false, error: error.message };
- }
- }
- /**
- * OCR识别最后一条消息(兼容旧API)
- * @param {string} ipPort - 设备 ID/IP:Port
- * @param {string} method - 识别方法 ('full-screen' | 'by-avatar')
- * @param {string} avatarPath - 头像路径(by-avatar 时使用)
- * @param {string} area - 区域(未使用,保留兼容性)
- * @param {string} folderPath - 工作流文件夹路径(可选)
- * @returns {Promise<{success: boolean, error?: string, text?: string, position?: Object}>}
- */
- export async function ocrLastMessage(ipPort, method, avatarPath, area, folderPath = null) {
- try {
- if (!ipPort) {
- return { success: false, error: '缺少设备 ID' };
- }
- // 1. 获取设备分辨率
- const resolutionResult = await getDeviceResolution(ipPort);
- if (!resolutionResult.success) {
- return { success: false, error: '获取设备分辨率失败' };
- }
- const { width, height } = resolutionResult;
- // 2. 获取屏幕截图
- const screenshotResult = await captureScreenshot(ipPort, { format: 'png' });
- if (!screenshotResult.success || !screenshotResult.data) {
- return { success: false, error: '获取屏幕截图失败' };
- }
- // 3. 保存截图到临时文件(如果提供了工作流文件夹,保存到 tmp/时间戳 目录)
- let screenshotPath;
- let tmpDir = null; // 用于跟踪需要删除的临时目录
- if (folderPath) {
- // 确保 folderPath 是绝对路径
- let absoluteFolderPath = folderPath;
- if (!isAbsolute(folderPath)) {
- // 如果已经是 static/processing/xxx 格式,去掉开头的 static/processing 再拼接
- if (folderPath.startsWith('static/processing/')) {
- const folderName = folderPath.replace('static/processing/', '');
- absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
- } else if (folderPath.startsWith('static\\processing\\')) {
- const folderName = folderPath.replace('static\\processing\\', '');
- absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderName);
- } else {
- // 如果只是文件夹名,需要加上 static/processing
- absoluteFolderPath = join(__dirname, '..', 'static', 'processing', folderPath);
- }
- }
-
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19).replace('T', '_');
- tmpDir = join(absoluteFolderPath, 'tmp', timestamp);
- await mkdir(tmpDir, { recursive: true });
- screenshotPath = join(tmpDir, 'screenshot_ocr.png');
- } else {
- const tempDir = join(__dirname, '..');
- screenshotPath = join(tempDir, 'temp_screenshot_ocr.png');
- }
- const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64');
- await writeFile(screenshotPath, screenshotBuffer);
- try {
- // 4. 调用 JS 实现进行OCR识别
- const normalizedScreenshotPath = screenshotPath.replace(/\\/g, '/');
- let result;
-
- if (method === 'full-screen') {
- // 全屏OCR识别
- result = await ocrFullScreenFromFunc(normalizedScreenshotPath, width, height);
- } else if (method === 'by-avatar' && avatarPath) {
- // 通过头像定位最后一条消息
- let friendAvatarArg = null;
- let myAvatarArg = null;
-
- if (isAbsolute(avatarPath)) {
- friendAvatarArg = avatarPath;
- myAvatarArg = avatarPath;
- } else {
- const folderName = avatarPath.split(/[/\\]/)[0];
- const avatarName = avatarPath.split(/[/\\]/).slice(1).join('/');
- friendAvatarArg = join(__dirname, '..', 'static', 'processing', folderName, avatarName);
- myAvatarArg = friendAvatarArg;
- }
-
- const normalizedFriendAvatar = friendAvatarArg.replace(/\\/g, '/');
- const normalizedMyAvatar = myAvatarArg.replace(/\\/g, '/');
- result = await getLastMessageFromFunc(normalizedScreenshotPath, normalizedFriendAvatar, normalizedMyAvatar, width, height);
- } else {
- // 默认使用全屏OCR
- result = await ocrFullScreenFromFunc(normalizedScreenshotPath, width, height);
- }
-
- if (result.success) {
- // 返回兼容旧API的格式
- return {
- success: true,
- text: result.text || '',
- position: result.position || null
- };
- } else {
- return { success: false, error: result.error || 'OCR识别失败' };
- }
- } finally {
- // 5. 使用完后,先判断 tmp 目录总大小是否超过 20MB,再决定是否删除临时目录
- if (tmpDir) {
- try {
- // 获取 tmp 目录的父目录(工作流目录下的 tmp 文件夹)
- const tmpParentDir = dirname(tmpDir);
-
- // 检查 tmp 目录下所有文件和子目录的总大小
- let totalSize = 0;
- const dirsToDelete = [];
-
- try {
- const entries = await readdir(tmpParentDir, { withFileTypes: true });
- for (const entry of entries) {
- const entryPath = join(tmpParentDir, entry.name);
- try {
- if (entry.isFile()) {
- const stats = await stat(entryPath);
- totalSize += stats.size;
- } else if (entry.isDirectory()) {
- // 递归计算子目录大小
- const dirSize = await calculateDirSize(entryPath);
- totalSize += dirSize;
- const dirStats = await stat(entryPath);
- dirsToDelete.push({ path: entryPath, size: dirSize, mtime: dirStats.mtime });
- }
- } catch (e) {
- // 忽略无法访问的文件
- }
- }
- } catch (e) {
- // 如果无法读取目录,直接删除临时目录
- await rm(tmpDir, { recursive: true, force: true });
- return;
- }
-
- const maxSize = 20 * 1024 * 1024; // 20MB
-
- // 如果总大小超过 20MB,删除时间最早的目录
- if (totalSize > maxSize) {
- // 按修改时间排序(最早的在前)
- dirsToDelete.sort((a, b) => a.mtime - b.mtime);
-
- // 删除最早的目录直到总大小小于 20MB
- for (const dirInfo of dirsToDelete) {
- if (totalSize <= maxSize) {
- break;
- }
- try {
- await rm(dirInfo.path, { recursive: true, force: true });
- totalSize -= dirInfo.size;
- } catch (e) {
- // 忽略删除失败
- }
- }
- }
-
- // 如果临时目录仍然存在且总大小未超过限制,也删除它(保持原有行为)
- try {
- const tmpDirExists = await stat(tmpDir).then(() => true).catch(() => false);
- if (tmpDirExists) {
- await rm(tmpDir, { recursive: true, force: true });
- }
- } catch (rmError) {
- // 忽略删除失败
- }
- } catch (error) {
- // 清理失败不影响主流程
- }
- }
- }
- } catch (error) {
- if (error.message && error.message.includes('timeout')) {
- return { success: false, error: 'OCR识别超时,请检查网络连接或稍后重试' };
- }
- return { success: false, error: error.message };
- }
- }
- /**
- * 检测虚拟环境的 Python 是否安装正确
- * @returns {Promise<{success: boolean, details: Object, error?: string}>}
- */
- export async function checkPythonEnvironment() {
- try {
- // 获取项目根目录
- const projectRoot = join(__dirname, '..');
-
- // 优先使用项目下的便携版 Python
- let pythonExePath = join(projectRoot, 'python', 'python.exe');
- let isPortablePython = false;
-
- // 如果便携版 Python 不存在,回退到虚拟环境
- if (!existsSync(pythonExePath)) {
- pythonExePath = join(projectRoot, 'py', 'venv', 'Scripts', 'python.exe');
- isPortablePython = false;
- } else {
- isPortablePython = true;
- }
-
- const details = {
- projectRoot,
- pythonExePath,
- isPortablePython,
- pythonExists: false,
- pythonVersion: null,
- pythonVersionRaw: null,
- packages: {},
- pyvenvCfg: null,
- errors: []
- };
-
- // 1. 检查 Python 可执行文件是否存在
- if (!existsSync(pythonExePath)) {
- details.errors.push(`Python 可执行文件不存在: ${pythonExePath}`);
- return { success: false, details, error: `Python 可执行文件不存在。尝试的路径:\n1. ${join(projectRoot, 'python', 'python.exe')}\n2. ${pythonExePath}` };
- }
- details.pythonExists = true;
-
- // 2. 检查 pyvenv.cfg 配置(仅当使用虚拟环境时)
- if (!isPortablePython) {
- const pyvenvCfgPath = join(projectRoot, 'py', 'venv', 'pyvenv.cfg');
- if (existsSync(pyvenvCfgPath)) {
- try {
- const cfgContent = await readFile(pyvenvCfgPath, 'utf8');
- details.pyvenvCfg = cfgContent;
- } catch (e) {
- details.errors.push(`无法读取 pyvenv.cfg: ${e.message}`);
- }
- } else {
- details.errors.push('pyvenv.cfg 文件不存在');
- }
- } else {
- // 便携版 Python 不需要 pyvenv.cfg
- details.pyvenvCfg = '使用便携版 Python,无需 pyvenv.cfg';
- }
-
- // 3. 检查 Python 版本
- try {
- const { stdout: versionOutput } = await execAsync(`"${pythonExePath}" --version`, {
- encoding: 'utf8',
- timeout: 5000,
- cwd: projectRoot
- });
- details.pythonVersionRaw = versionOutput.trim();
-
- // 提取版本号
- const versionMatch = versionOutput.match(/Python (\d+\.\d+\.\d+)/);
- if (versionMatch) {
- details.pythonVersion = versionMatch[1];
- }
- } catch (e) {
- details.errors.push(`无法获取 Python 版本: ${e.message}`);
- }
-
- // 4. 检查必要的 Python 包
- const requiredPackages = [
- { name: 'cv2', importName: 'cv2', displayName: 'OpenCV' },
- { name: 'numpy', importName: 'numpy', displayName: 'NumPy' },
- { name: 'onnxocr', importName: 'onnxocr', displayName: 'OnnxOCR' }
- ];
-
- for (const pkg of requiredPackages) {
- try {
- const { stdout } = await execAsync(`"${pythonExePath}" -c "import ${pkg.importName}; print(${pkg.importName}.__version__ if hasattr(${pkg.importName}, '__version__') else 'installed')"`, {
- encoding: 'utf8',
- timeout: 5000,
- cwd: projectRoot,
- env: {
- ...process.env,
- PYTHONIOENCODING: 'utf-8',
- PYTHONUTF8: '1'
- }
- });
- details.packages[pkg.name] = {
- installed: true,
- version: stdout.trim() || 'installed',
- displayName: pkg.displayName
- };
- } catch (e) {
- details.packages[pkg.name] = {
- installed: false,
- error: e.message,
- displayName: pkg.displayName
- };
- details.errors.push(`${pkg.displayName} (${pkg.name}) 未安装或无法导入: ${e.message}`);
- }
- }
-
- // 5. 检查 Python 环境结构
- if (isPortablePython) {
- // 便携版 Python 的结构
- const pythonDirs = {
- Scripts: join(projectRoot, 'python', 'Scripts'),
- Lib: join(projectRoot, 'python', 'Lib'),
- 'site-packages': join(projectRoot, 'python', 'Lib', 'site-packages')
- };
-
- details.venvStructure = {};
- for (const [name, path] of Object.entries(pythonDirs)) {
- details.venvStructure[name] = {
- exists: existsSync(path),
- path
- };
- if (!existsSync(path) && name !== 'site-packages') {
- details.errors.push(`Python 目录不存在: ${name} (${path})`);
- }
- }
- } else {
- // 虚拟环境的结构
- const venvDirs = {
- Scripts: join(projectRoot, 'py', 'venv', 'Scripts'),
- Lib: join(projectRoot, 'py', 'venv', 'Lib'),
- 'site-packages': join(projectRoot, 'py', 'venv', 'Lib', 'site-packages')
- };
-
- details.venvStructure = {};
- for (const [name, path] of Object.entries(venvDirs)) {
- details.venvStructure[name] = {
- exists: existsSync(path),
- path
- };
- if (!existsSync(path)) {
- details.errors.push(`虚拟环境目录不存在: ${name} (${path})`);
- }
- }
- }
-
- // 判断整体是否成功
- const hasCriticalErrors = details.errors.length > 0 && (
- !details.pythonExists ||
- !details.pythonVersion ||
- !details.packages.cv2?.installed ||
- !details.packages.numpy?.installed
- );
-
- return {
- success: !hasCriticalErrors,
- details,
- error: hasCriticalErrors ? `检测到关键问题: ${details.errors.slice(0, 3).join('; ')}` : null
- };
- } catch (error) {
- return {
- success: false,
- details: { error: error.message },
- error: `检测 Python 环境时出错: ${error.message}`
- };
- }
- }
- /**
- * 注册 IPC 处理器(Python 执行相关)
- */
- export function registerIpcHandlers() {
- // 图像匹配
- ipcMain.handle('match-image-and-get-coordinate', async (event, ipPort, templateImagePath) => {
- return await matchImageAndGetCoordinate(ipPort, templateImagePath);
- });
- // 图像区域定位
- ipcMain.handle('match-image-region-location', async (event, screenshotPath, regionPath, device) => {
- return await matchImageRegionLocation(screenshotPath, regionPath, device);
- });
- ipcMain.handle('crop-and-save-image', async (event, imagePath, x, y, width, height, savePath) => {
- const result = await cropAndSaveImage(imagePath, x, y, width, height, savePath);
- return result;
- });
- // 文字识别
- ipcMain.handle('find-text-and-get-coordinate', async (event, ipPort, targetText) => {
- return await findTextAndGetCoordinate(ipPort, targetText);
- });
- // OCR识别最后一条消息(兼容旧API)
- ipcMain.handle('ocr-last-message', async (event, ipPort, method, avatarPath, area, folderPath) => {
- return await ocrLastMessage(ipPort, method, avatarPath, area, folderPath);
- });
-
- // 检测 Python 环境
- ipcMain.handle('check-python-environment', async () => {
- return await checkPythonEnvironment();
- });
- }
|