| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879 |
- /**
- * 执行 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<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: '缺少区域截图路径' };
- }
- // 如果 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) {
- // 图像区域定位失败
- 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 {
- // 处理相对路径,转换为绝对路径
- let absoluteImagePath = imagePath;
- if (!isAbsolute(imagePath)) {
- // 如果是相对路径,相对于项目根目录
- if (imagePath.startsWith('static/processing/')) {
- absoluteImagePath = join(__dirname, '..', imagePath);
- } else {
- absoluteImagePath = join(__dirname, '..', imagePath);
- }
- }
-
- 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);
- } 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);
- } else {
- // 如果无法匹配,尝试从 imagePath 提取工作流目录(去掉 /resources/ScreenShot.jpg)
- const workflowDir = imagePath.split('/resources/')[0];
- absoluteSavePath = join(__dirname, '..', workflowDir, savePath);
- }
- } else {
- // 默认相对于项目根目录
- absoluteSavePath = join(__dirname, '..', savePath);
- }
- }
-
- // 构建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');
-
- // 执行Python脚本
- try {
- const { stdout, stderr } = await execAsync(`"${pythonExePath}" -c "${pythonCode.replace(/"/g, '\\"')}"`, {
- maxBuffer: 10 * 1024 * 1024,
- encoding: 'utf8',
- cwd: join(__dirname, '..')
- });
-
- // 检查是否有错误(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 screenshotExists = fs.existsSync(absoluteImagePath);
-
- if (fs.existsSync(absoluteSavePath)) {
- return { success: true };
- } else {
- // 检查父目录是否存在
- const parentDir = dirname(absoluteSavePath);
- const parentExists = fs.existsSync(parentDir);
-
- // 构建详细的错误信息
- 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退出码)
- 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 };
- }
- }
- /**
- * 注册 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);
- });
- }
|