ocr.js 5.7 KB

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