| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481 |
- /**
- * 执行 Python 相关操作模块(通用功能)
- * 负责图像匹配、OCR识别等通用功能(通过调用 Python/JS 实现)
- * 注意:聊天记录提取等业务相关功能在 read-and-write.js 中
- */
- import { ipcMain } from 'electron';
- import { writeFile, mkdir, rm } from 'fs/promises';
- import { join, dirname, isAbsolute } from 'path';
- import { fileURLToPath } from 'url';
- 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 __filename = fileURLToPath(import.meta.url);
- const __dirname = dirname(__filename);
- /**
- * 执行图像匹配:截图、调用 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 }
- };
- return {
- success: true,
- x,
- y,
- width: w,
- height: h,
- corners: corners,
- similarity: matchResult.similarity
- };
- } catch (error) {
- console.error('图像区域定位失败:', 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) {
- 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. 使用完后删除临时目录
- if (tmpDir) {
- try {
- await rm(tmpDir, { recursive: true, force: true });
- // 已删除临时目录日志(不显示)
- } catch (rmError) {
- console.warn(`删除临时目录失败: ${tmpDir}`, rmError);
- }
- }
- }
- } 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. 使用完后删除临时目录
- if (tmpDir) {
- try {
- await rm(tmpDir, { recursive: true, force: true });
- // 已删除临时目录日志(不显示)
- } catch (rmError) {
- console.warn(`删除临时目录失败: ${tmpDir}`, rmError);
- }
- }
- }
- } 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('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);
- });
- }
|