sort-sentence.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. /**
  2. * 步骤1: 创建startSortSentence()函数
  3. * 步骤2: 接收参数:ocrResultJsonPathArr(识别结果json文件路径数组)
  4. * 步骤4: 依次遍历ocrResultJsonPathArr里的每一个json文件,根据json里的bbox信息,按照x1越大越靠前的原则排序,把text拼接成字符串。
  5. * 步骤5: 将字符串保存到txt文件中,文件名称为ocrResultJsonPathArr的文件名,文件保存位置为ocrResultJsonPathArr的文件夹位置
  6. * 步骤6: 返回保存的txt文件路径数组
  7. */
  8. import fs from 'fs';
  9. import path from 'path';
  10. /**
  11. * 步骤1: 创建startSortSentence()函数
  12. * @param {Array<string>} ocrResultJsonPathArr - 步骤2: 识别结果json文件路径数组(外部传入)
  13. * @returns {Array<string>} 步骤6: 返回保存的txt文件路径数组
  14. */
  15. function startSortSentence(ocrResultJsonPathArr) {
  16. try {
  17. console.log('🚀 开始整理语句排序流程...');
  18. // 步骤2: 接收参数:ocrResultJsonPathArr(识别结果json文件路径数组)
  19. console.log('\n📋 步骤2: 验证JSON文件路径数组参数');
  20. if (!ocrResultJsonPathArr || !Array.isArray(ocrResultJsonPathArr)) {
  21. throw new Error('步骤2失败: ocrResultJsonPathArr 必须是一个数组');
  22. }
  23. if (ocrResultJsonPathArr.length === 0) {
  24. throw new Error('步骤2失败: ocrResultJsonPathArr 不能为空数组');
  25. }
  26. console.log(`✅ JSON文件路径数组长度: ${ocrResultJsonPathArr.length}`);
  27. // 步骤4: 依次遍历ocrResultJsonPathArr里的每一个json文件
  28. console.log('\n📄 步骤4: 开始遍历JSON文件并排序文本...');
  29. const txtFilePaths = [];
  30. for (let i = 0; i < ocrResultJsonPathArr.length; i++) {
  31. const jsonPath = ocrResultJsonPathArr[i];
  32. console.log(`\n 📖 [${i + 1}/${ocrResultJsonPathArr.length}] 处理JSON文件: ${path.basename(jsonPath)}`);
  33. // 验证JSON文件存在
  34. if (!fs.existsSync(jsonPath)) {
  35. console.log(` ⚠️ JSON文件不存在,跳过: ${jsonPath}`);
  36. continue;
  37. }
  38. // 读取JSON文件
  39. let jsonData;
  40. try {
  41. const jsonContent = fs.readFileSync(jsonPath, 'utf-8');
  42. jsonData = JSON.parse(jsonContent);
  43. } catch (error) {
  44. console.log(` ⚠️ JSON文件解析失败,跳过: ${error.message}`);
  45. continue;
  46. }
  47. // 获取dialogues数组
  48. const dialogues = jsonData.dialogues || [];
  49. if (dialogues.length === 0) {
  50. console.log(` ⚠️ JSON文件中没有dialogues数据,跳过`);
  51. continue;
  52. }
  53. console.log(` 📊 找到 ${dialogues.length} 个文字块`);
  54. // 根据json里的bbox信息,按照x1越大越靠前的原则排序
  55. const sortedDialogues = dialogues.sort((a, b) => {
  56. // 获取bbox的x1值
  57. let x1A = 0;
  58. let x1B = 0;
  59. if (a.bbox) {
  60. // bbox可能是数组格式 [[x1,y1], [x2,y2], [x3,y3], [x4,y4]] 或对象格式 {x1, y1, x2, y2}
  61. if (Array.isArray(a.bbox) && a.bbox.length > 0) {
  62. x1A = a.bbox[0][0] || 0; // 取第一个点的x坐标
  63. } else if (typeof a.bbox === 'object' && a.bbox.x1 !== undefined) {
  64. x1A = a.bbox.x1;
  65. }
  66. }
  67. if (b.bbox) {
  68. if (Array.isArray(b.bbox) && b.bbox.length > 0) {
  69. x1B = b.bbox[0][0] || 0;
  70. } else if (typeof b.bbox === 'object' && b.bbox.x1 !== undefined) {
  71. x1B = b.bbox.x1;
  72. }
  73. }
  74. return x1B - x1A; // x1越大越靠前(从右到左)
  75. });
  76. // 把text拼接成字符串
  77. const textString = sortedDialogues.map(d => d.text || '').join('');
  78. console.log(` 📝 排序后文本长度: ${textString.length} 字符`);
  79. if (textString.length > 0) {
  80. console.log(` 📄 文本预览: ${textString.substring(0, 30)}${textString.length > 30 ? '...' : ''}`);
  81. }
  82. // 步骤5: 将字符串保存到txt文件中
  83. // 文件名称为ocrResultJsonPathArr的文件名(只是扩展名不同)
  84. const jsonDir = path.dirname(jsonPath);
  85. const jsonFileName = path.basename(jsonPath, path.extname(jsonPath));
  86. const txtFileName = `${jsonFileName}.txt`;
  87. const txtFilePath = path.join(jsonDir, txtFileName);
  88. // 文件保存位置为ocrResultJsonPathArr的文件夹位置
  89. fs.writeFileSync(txtFilePath, textString, 'utf-8');
  90. txtFilePaths.push(txtFilePath);
  91. const stats = fs.statSync(txtFilePath);
  92. console.log(` ✅ 已保存txt文件: ${txtFileName} (${Math.round(stats.size / 1024)}KB)`);
  93. }
  94. // 步骤6: 返回保存的txt文件路径数组
  95. console.log('\n📋 步骤6: 准备返回txt文件路径数组...');
  96. console.log(`📄 txt文件路径列表 (${txtFilePaths.length} 个):`);
  97. txtFilePaths.forEach((txtPath, index) => {
  98. console.log(` ${index + 1}. ${path.basename(txtPath)}`);
  99. });
  100. console.log(`✅ 步骤6完成: txt文件路径数组已准备就绪 (${txtFilePaths.length} 个路径)`);
  101. console.log('\n🎉 所有步骤完成!');
  102. console.log(`📊 共处理 ${ocrResultJsonPathArr.length} 个JSON文件`);
  103. console.log(`📊 共生成 ${txtFilePaths.length} 个txt文件`);
  104. return txtFilePaths; // 步骤6: 返回保存的txt文件路径数组
  105. } catch (error) {
  106. console.error(`\n❌ 整理语句排序失败: ${error.message}`);
  107. throw error;
  108. }
  109. }
  110. // 导出函数
  111. export { startSortSentence };