| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- /**
- * 步骤1: 创建startSortSentence()函数
- * 步骤2: 接收参数:ocrResultJsonPathArr(识别结果json文件路径数组)
- * 步骤4: 依次遍历ocrResultJsonPathArr里的每一个json文件,根据json里的bbox信息,按照x1越大越靠前的原则排序,把text拼接成字符串。
- * 步骤5: 将字符串保存到txt文件中,文件名称为ocrResultJsonPathArr的文件名,文件保存位置为ocrResultJsonPathArr的文件夹位置
- * 步骤6: 返回保存的txt文件路径数组
- */
- import fs from 'fs';
- import path from 'path';
- /**
- * 步骤1: 创建startSortSentence()函数
- * @param {Array<string>} ocrResultJsonPathArr - 步骤2: 识别结果json文件路径数组(外部传入)
- * @returns {Array<string>} 步骤6: 返回保存的txt文件路径数组
- */
- function startSortSentence(ocrResultJsonPathArr) {
- try {
- console.log('🚀 开始整理语句排序流程...');
-
- // 步骤2: 接收参数:ocrResultJsonPathArr(识别结果json文件路径数组)
- console.log('\n📋 步骤2: 验证JSON文件路径数组参数');
- if (!ocrResultJsonPathArr || !Array.isArray(ocrResultJsonPathArr)) {
- throw new Error('步骤2失败: ocrResultJsonPathArr 必须是一个数组');
- }
- if (ocrResultJsonPathArr.length === 0) {
- throw new Error('步骤2失败: ocrResultJsonPathArr 不能为空数组');
- }
- console.log(`✅ JSON文件路径数组长度: ${ocrResultJsonPathArr.length}`);
-
- // 步骤4: 依次遍历ocrResultJsonPathArr里的每一个json文件
- console.log('\n📄 步骤4: 开始遍历JSON文件并排序文本...');
- const txtFilePaths = [];
-
- for (let i = 0; i < ocrResultJsonPathArr.length; i++) {
- const jsonPath = ocrResultJsonPathArr[i];
-
- console.log(`\n 📖 [${i + 1}/${ocrResultJsonPathArr.length}] 处理JSON文件: ${path.basename(jsonPath)}`);
-
- // 验证JSON文件存在
- if (!fs.existsSync(jsonPath)) {
- console.log(` ⚠️ JSON文件不存在,跳过: ${jsonPath}`);
- continue;
- }
-
- // 读取JSON文件
- let jsonData;
- try {
- const jsonContent = fs.readFileSync(jsonPath, 'utf-8');
- jsonData = JSON.parse(jsonContent);
- } catch (error) {
- console.log(` ⚠️ JSON文件解析失败,跳过: ${error.message}`);
- continue;
- }
-
- // 获取dialogues数组
- const dialogues = jsonData.dialogues || [];
-
- if (dialogues.length === 0) {
- console.log(` ⚠️ JSON文件中没有dialogues数据,跳过`);
- continue;
- }
-
- console.log(` 📊 找到 ${dialogues.length} 个文字块`);
-
- // 根据json里的bbox信息,按照x1越大越靠前的原则排序
- const sortedDialogues = dialogues.sort((a, b) => {
- // 获取bbox的x1值
- let x1A = 0;
- let x1B = 0;
-
- if (a.bbox) {
- // bbox可能是数组格式 [[x1,y1], [x2,y2], [x3,y3], [x4,y4]] 或对象格式 {x1, y1, x2, y2}
- if (Array.isArray(a.bbox) && a.bbox.length > 0) {
- x1A = a.bbox[0][0] || 0; // 取第一个点的x坐标
- } else if (typeof a.bbox === 'object' && a.bbox.x1 !== undefined) {
- x1A = a.bbox.x1;
- }
- }
-
- if (b.bbox) {
- if (Array.isArray(b.bbox) && b.bbox.length > 0) {
- x1B = b.bbox[0][0] || 0;
- } else if (typeof b.bbox === 'object' && b.bbox.x1 !== undefined) {
- x1B = b.bbox.x1;
- }
- }
-
- return x1B - x1A; // x1越大越靠前(从右到左)
- });
-
- // 把text拼接成字符串
- const textString = sortedDialogues.map(d => d.text || '').join('');
-
- console.log(` 📝 排序后文本长度: ${textString.length} 字符`);
- if (textString.length > 0) {
- console.log(` 📄 文本预览: ${textString.substring(0, 30)}${textString.length > 30 ? '...' : ''}`);
- }
-
- // 步骤5: 将字符串保存到txt文件中
- // 文件名称为ocrResultJsonPathArr的文件名(只是扩展名不同)
- const jsonDir = path.dirname(jsonPath);
- const jsonFileName = path.basename(jsonPath, path.extname(jsonPath));
- const txtFileName = `${jsonFileName}.txt`;
- const txtFilePath = path.join(jsonDir, txtFileName);
-
- // 文件保存位置为ocrResultJsonPathArr的文件夹位置
- fs.writeFileSync(txtFilePath, textString, 'utf-8');
-
- txtFilePaths.push(txtFilePath);
-
- const stats = fs.statSync(txtFilePath);
- console.log(` ✅ 已保存txt文件: ${txtFileName} (${Math.round(stats.size / 1024)}KB)`);
- }
-
- // 步骤6: 返回保存的txt文件路径数组
- console.log('\n📋 步骤6: 准备返回txt文件路径数组...');
- console.log(`📄 txt文件路径列表 (${txtFilePaths.length} 个):`);
- txtFilePaths.forEach((txtPath, index) => {
- console.log(` ${index + 1}. ${path.basename(txtPath)}`);
- });
- console.log(`✅ 步骤6完成: txt文件路径数组已准备就绪 (${txtFilePaths.length} 个路径)`);
-
- console.log('\n🎉 所有步骤完成!');
- console.log(`📊 共处理 ${ocrResultJsonPathArr.length} 个JSON文件`);
- console.log(`📊 共生成 ${txtFilePaths.length} 个txt文件`);
-
- return txtFilePaths; // 步骤6: 返回保存的txt文件路径数组
-
- } catch (error) {
- console.error(`\n❌ 整理语句排序失败: ${error.message}`);
- throw error;
- }
- }
- // 导出函数
- export { startSortSentence };
|