/** * 执行 Python 相关操作模块(通用功能) * 负责图像匹配、OCR识别等通用功能(通过调用 Python/JS 实现) * 注意:聊天记录提取等业务相关功能在 read-and-write.js 中 */ import { ipcMain } from 'electron'; import { writeFile, mkdir, rm, readdir, stat } from 'fs/promises'; import fs 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); /** * 递归计算目录大小 * @param {string} dirPath - 目录路径 * @returns {Promise} 目录总大小(字节) */ 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) { console.error('图像匹配失败:', 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: '缺少区域截图路径' }; } // 如果 screenshotPath 为 '__AUTO_SCREENSHOT__' 或 null,自动从设备获取截图 let absoluteScreenshotPath = 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: '自动获取设备截图失败' }; } // 保存截图到临时文件 const tempDir = join(__dirname, '..'); const tempScreenshotPath = join(tempDir, 'temp_screenshot.png'); const screenshotBuffer = Buffer.from(screenshotResult.data, 'base64'); await writeFile(tempScreenshotPath, screenshotBuffer); absoluteScreenshotPath = tempScreenshotPath; } else { // 将相对路径转换为绝对路径 if (!isAbsolute(screenshotPath)) { absoluteScreenshotPath = join(__dirname, '..', screenshotPath); } } let absoluteRegionPath = regionPath; if (!isAbsolute(regionPath)) { absoluteRegionPath = join(__dirname, '..', regionPath); } // 可选:如果提供了设备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(absoluteScreenshotPath, absoluteRegionPath, 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: absoluteScreenshotPath // 返回截图路径,用于后续裁剪 }; } catch (error) { console.error('图像区域定位失败:', 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) { console.log('[cropAndSaveImage] 收到请求,参数:', { imagePath, x, y, width, height, savePath }); try { // 处理相对路径,转换为绝对路径 let absoluteImagePath = imagePath; if (!isAbsolute(imagePath)) { // 如果是相对路径,相对于项目根目录 if (imagePath.startsWith('static/processing/')) { absoluteImagePath = join(__dirname, '..', imagePath); } else { absoluteImagePath = join(__dirname, '..', imagePath); } console.log('[cropAndSaveImage] 图片路径转换,原始:', imagePath, '-> 绝对:', absoluteImagePath); } else { console.log('[cropAndSaveImage] 图片路径已经是绝对路径:', absoluteImagePath); } let absoluteSavePath = savePath; if (!isAbsolute(savePath)) { // 如果是相对路径,需要判断是相对于工作流目录还是项目根目录 // 优先检查 savePath 是否已经包含完整路径(以 static/processing/ 开头) if (savePath.startsWith('static/processing/')) { // savePath 已经是完整路径,如 "static/processing/微信聊天自动发送工作流/history/chat-area-cropped.png" // 直接拼接项目根目录即可,不需要再次提取工作流目录 absoluteSavePath = join(__dirname, '..', savePath); console.log('[cropAndSaveImage] savePath 已包含完整路径,直接拼接项目根目录'); } else if (imagePath.includes('static/processing/')) { // savePath 是相对于工作流目录的,如 "history/chat-area-cropped.png" // 从 imagePath 提取工作流目录路径 const workflowMatch = imagePath.match(/static\/processing\/[^\/]+/); if (workflowMatch) { absoluteSavePath = join(__dirname, '..', workflowMatch[0], savePath); console.log('[cropAndSaveImage] savePath 相对于工作流目录,从 imagePath 提取工作流目录:', workflowMatch[0]); } else { // 如果无法匹配,尝试从 imagePath 提取工作流目录(去掉 /resources/ScreenShot.jpg) const workflowDir = imagePath.split('/resources/')[0]; absoluteSavePath = join(__dirname, '..', workflowDir, savePath); console.log('[cropAndSaveImage] savePath 相对于工作流目录,从 imagePath 提取(备用方法):', workflowDir); } } else { // 默认相对于项目根目录 absoluteSavePath = join(__dirname, '..', savePath); console.log('[cropAndSaveImage] savePath 相对于项目根目录'); } console.log('[cropAndSaveImage] 保存路径转换,原始:', savePath, '-> 绝对:', absoluteSavePath); } else { console.log('[cropAndSaveImage] 保存路径已经是绝对路径:', absoluteSavePath); } console.log('[cropAndSaveImage] 最终路径:', { absoluteImagePath, absoluteSavePath }); // 构建Python脚本代码 // 使用 pathlib.Path 来处理路径,确保中文路径正确 // 将 Windows 路径转换为 Python 可以处理的格式 const normalizedImagePath = absoluteImagePath.replace(/\\/g, '/'); const normalizedSavePath = absoluteSavePath.replace(/\\/g, '/'); // 转义路径中的特殊字符,确保 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可执行文件路径 const pythonExePath = join(__dirname, '..', 'py', 'venv', 'Scripts', 'python.exe'); console.log('[cropAndSaveImage] Python路径:', pythonExePath); console.log('[cropAndSaveImage] Python脚本代码长度:', pythonCode.length); // 执行Python脚本 console.log('[cropAndSaveImage] 开始执行Python脚本...'); console.log('[cropAndSaveImage] 命令:', `"${pythonExePath}" -c "..."`); try { const { stdout, stderr } = await execAsync(`"${pythonExePath}" -c "${pythonCode.replace(/"/g, '\\"')}"`, { maxBuffer: 10 * 1024 * 1024, encoding: 'utf8', cwd: join(__dirname, '..') }); // 打印 stdout 和 stderr 以便调试(必须输出,无论是否为空) console.log('[cropAndSaveImage] Python 执行完成'); console.log('[cropAndSaveImage] Python stdout 长度:', stdout ? stdout.length : 0); if (stdout) { console.log('[cropAndSaveImage] Python stdout:', stdout); } else { console.log('[cropAndSaveImage] Python stdout: (空)'); } console.log('[cropAndSaveImage] Python stderr 长度:', stderr ? stderr.length : 0); if (stderr) { console.log('[cropAndSaveImage] Python stderr:', stderr); } else { console.log('[cropAndSaveImage] Python stderr: (空)'); } // 检查是否有错误(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('成功保存')) { console.error('[cropAndSaveImage] Python执行可能出错:', stderr); // 不抛出错误,让后续验证文件是否存在 } } // 验证文件是否真的保存了 console.log('[cropAndSaveImage] 检查文件是否存在:', absoluteSavePath); // 检查截图文件是否存在(用于调试) console.log('[cropAndSaveImage] 检查截图文件是否存在:', absoluteImagePath); const screenshotExists = fs.existsSync(absoluteImagePath); console.log('[cropAndSaveImage] 截图文件存在:', screenshotExists); if (!screenshotExists) { console.error('[cropAndSaveImage] ⚠️ 截图文件不存在,Python脚本可能无法执行'); } if (fs.existsSync(absoluteSavePath)) { const stats = fs.statSync(absoluteSavePath); console.log('[cropAndSaveImage] ✅ 文件保存成功,路径:', absoluteSavePath, '大小:', stats.size, '字节'); return { success: true }; } else { console.error('[cropAndSaveImage] ❌ 文件保存失败,文件不存在:', absoluteSavePath); // 检查父目录是否存在 const parentDir = dirname(absoluteSavePath); const parentExists = fs.existsSync(parentDir); console.error('[cropAndSaveImage] 父目录是否存在:', parentDir, '->', parentExists); if (!parentExists) { console.error('[cropAndSaveImage] 父目录不存在,可能是路径问题或Python脚本未创建目录'); } // 构建详细的错误信息 let errorMsg = `文件保存失败,文件不存在: ${absoluteSavePath}`; if (!screenshotExists) { errorMsg += `\n截图文件不存在: ${absoluteImagePath}`; } 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退出码) console.error('[cropAndSaveImage] ❌ Python脚本执行失败:', execError); console.error('[cropAndSaveImage] 错误类型:', execError.constructor.name); console.error('[cropAndSaveImage] 错误消息:', execError.message); if (execError.code !== undefined) { console.error('[cropAndSaveImage] 退出码:', execError.code); } if (execError.stdout) { console.error('[cropAndSaveImage] Python stdout:', execError.stdout); } else { console.error('[cropAndSaveImage] Python stdout: (空)'); } if (execError.stderr) { console.error('[cropAndSaveImage] Python stderr:', execError.stderr); } else { console.error('[cropAndSaveImage] Python stderr: (空)'); } return { success: false, error: execError.stderr || execError.message || 'Python脚本执行失败' }; } } catch (error) { console.error('[cropAndSaveImage] 裁剪图片失败:', error); console.error('[cropAndSaveImage] 错误堆栈:', error.stack); 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) { console.error('文字识别失败:', 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) { console.error('OCR识别失败:', 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) { console.error('OCR识别失败:', error); if (error.message && error.message.includes('timeout')) { return { success: false, error: 'OCR识别超时,请检查网络连接或稍后重试' }; } return { success: false, error: 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) => { console.log('[IPC] crop-and-save-image 收到请求:', { imagePath, x, y, width, height, savePath }); const result = await cropAndSaveImage(imagePath, x, y, width, height, savePath); console.log('[IPC] crop-and-save-image 返回结果:', result); 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); }); }