ocr.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /**
  2. * fun 标签:ocr(RapidOCR 识别,脚本为 python/scripts/ocr.py)
  3. * 1)image 为图片路径时:对图片做 OCR,识别全文写入变量。
  4. * 2)image 为要查找的文字时:对设备截图做 OCR,在图中查找该文字,返回中心点坐标写入变量(需有设备)。
  5. */
  6. const path = require('path')
  7. const fs = require('fs')
  8. const os = require('os')
  9. const { spawnSync } = require('child_process')
  10. const { captureScreenshot } = require('../../../adb/adb-screencap.js')
  11. const configPath = process.env.STATIC_ROOT
  12. ? path.join(path.dirname(process.env.STATIC_ROOT), 'config.js')
  13. : path.join(__dirname, '..', '..', '..', '..', 'config.js')
  14. const projectRoot = path.dirname(path.resolve(configPath))
  15. const config = fs.existsSync(configPath) ? require(configPath) : {}
  16. const ocrScriptPath = path.join(projectRoot, 'python', 'scripts', 'ocr.py')
  17. const tagName = 'ocr'
  18. const schema = {
  19. description: 'OCR:传入图片路径则识别全文;传入要查找的文字则在设备截图中定位该文字并返回中心点坐标。',
  20. inputs: { image: '图片路径 或 要查找的文字', variable: '输出变量名(保存识别文本或中心点 {"x", "y"})' },
  21. outputs: { variable: '识别文本 或 中心点 JSON' },
  22. }
  23. function getPythonPath() {
  24. const base = config.pythonPath?.path || path.join(projectRoot, 'python', 'py')
  25. const winPy = path.join(base, 'python.exe')
  26. if (fs.existsSync(winPy)) return winPy
  27. const unixPy = path.join(base, 'python')
  28. if (fs.existsSync(unixPy)) return unixPy
  29. return 'python'
  30. }
  31. /**
  32. * 对指定图片执行 RapidOCR 识别
  33. * @param {{ imagePath: string, folderPath?: string }} input - imagePath 图片路径(已解析后的相对或绝对路径), folderPath 流程目录
  34. * @returns {{ success: boolean, text?: string, error?: string }}
  35. */
  36. async function executeOcr({ imagePath, folderPath }) {
  37. if (!imagePath || typeof imagePath !== 'string') {
  38. return { success: false, error: '缺少图片路径' }
  39. }
  40. const baseDir = folderPath && typeof folderPath === 'string' ? folderPath : projectRoot
  41. const isAbsoluteOrDrive = imagePath.startsWith('/') || imagePath.includes(':')
  42. const hasSubPath = imagePath.includes('/') || imagePath.includes(path.sep)
  43. const resolvedImage = isAbsoluteOrDrive ? imagePath : (hasSubPath ? path.join(baseDir, imagePath) : path.join(baseDir, 'resources', imagePath))
  44. if (!fs.existsSync(ocrScriptPath)) {
  45. return { success: false, error: `OCR 脚本不存在: ${ocrScriptPath}(请确保 python/scripts/ocr.py 存在)` }
  46. }
  47. if (!fs.existsSync(resolvedImage)) {
  48. return { success: false, error: `图片不存在: ${resolvedImage}` }
  49. }
  50. const pythonPath = getPythonPath()
  51. const r = spawnSync(pythonPath, [ocrScriptPath, '--image', resolvedImage, '--project-root', projectRoot], {
  52. encoding: 'utf-8',
  53. timeout: 60000,
  54. env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
  55. cwd: projectRoot,
  56. })
  57. const outStr = (r.stdout || '').trim()
  58. const errStr = (r.stderr || '').trim()
  59. let out
  60. try {
  61. out = JSON.parse(outStr)
  62. } catch (e) {
  63. if (r.status !== 0) {
  64. return { success: false, error: errStr || outStr || 'OCR 执行失败' }
  65. }
  66. return { success: false, error: `OCR 输出解析失败: ${outStr}` }
  67. }
  68. if (!out.success) {
  69. return { success: false, error: out.error || 'OCR 识别失败' }
  70. }
  71. if (r.status !== 0) {
  72. return { success: false, error: out.error || errStr || outStr || 'OCR 执行失败' }
  73. }
  74. return { success: true, text: out.text != null ? String(out.text) : '' }
  75. }
  76. /**
  77. * 在设备截图中查找指定文字,返回该文字区域中心点
  78. * @param {{ device: string, findText: string, folderPath?: string }} input
  79. * @returns {{ success: boolean, center?: { x: number, y: number }, error?: string }}
  80. */
  81. async function executeOcrFindText({ device, findText, folderPath }) {
  82. if (!device) return { success: false, error: '缺少设备 ID,无法截图' }
  83. if (!findText || typeof findText !== 'string') return { success: false, error: '缺少要查找的文字' }
  84. const ts = Date.now()
  85. const screenshotPath = path.join(os.tmpdir(), `ef-ocr-screenshot-${ts}.png`)
  86. try {
  87. captureScreenshot(device, screenshotPath)
  88. if (!fs.existsSync(screenshotPath) || fs.statSync(screenshotPath).size === 0) {
  89. return { success: false, error: '设备截图失败或为空' }
  90. }
  91. const pythonPath = getPythonPath()
  92. const r = spawnSync(pythonPath, [ocrScriptPath, '--image', screenshotPath, '--find-text', findText.trim(), '--project-root', projectRoot], {
  93. encoding: 'utf-8',
  94. timeout: 60000,
  95. env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
  96. cwd: projectRoot,
  97. })
  98. const outStr = (r.stdout || '').trim()
  99. const errStr = (r.stderr || '').trim()
  100. let out
  101. try {
  102. out = JSON.parse(outStr)
  103. } catch (e) {
  104. if (r.status !== 0) {
  105. return { success: false, error: errStr || outStr || 'OCR 查找文字失败' }
  106. }
  107. return { success: false, error: `OCR 输出解析失败: ${outStr}` }
  108. }
  109. if (!out.success || out.x == null || out.y == null) {
  110. return { success: false, error: out.error || '图中未找到该文字' }
  111. }
  112. if (r.status !== 0) {
  113. return { success: false, error: out.error || errStr || outStr || 'OCR 查找文字失败' }
  114. }
  115. return { success: true, center: { x: out.x, y: out.y } }
  116. } finally {
  117. try { fs.unlinkSync(screenshotPath) } catch (_) {}
  118. }
  119. }
  120. module.exports = { tagName, schema, executeOcr, executeOcrFindText }