DocxToMarkdownConverter.java
11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package com.glsk.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.nio.file.*;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Pattern;
@Slf4j
public class DocxToMarkdownConverter {
/**
* 修复文件名处理的主方法
*/
public static Map<String, Object> textToExcel(String fileName) {
log.info("开始将doc转markdown, fileName: {}", fileName);
Map<String, Object> result = new HashMap<>();
try {
// 配置路径
String inputDirectory = "/data/soft/java_project/dify-projects/doc/input";
String outputDirectory = "/data/soft/java_project/dify-projects/doc/output";
// String inputDirectory = "E:\\Agi_Project\\glsk-mcp\\glsk-mcp-server\\data\\input";
// String outputDirectory = "E:\\Agi_Project\\glsk-mcp\\glsk-mcp-server\\data\\output";
// 修复文件名处理
String correctedFileName = correctFileName(fileName);
System.out.println("原始文件名: " + fileName);
System.out.println("修正后文件名: " + correctedFileName);
// 构建完整文件路径
Path inputPath = Paths.get(inputDirectory, correctedFileName);
// 如果修正后的文件不存在,尝试查找实际文件
if (!Files.exists(inputPath)) {
String actualFileName = findActualFile(inputDirectory, fileName);
if (actualFileName != null) {
inputPath = Paths.get(inputDirectory, actualFileName);
correctedFileName = actualFileName;
System.out.println("找到实际文件: " + actualFileName);
}
}
String outputFilename = correctedFileName.replace(".docx", ".md");
Path outputPath = Paths.get(outputDirectory, outputFilename);
// 检查输入文件是否存在
if (!Files.exists(inputPath)) {
// 列出目录内容帮助调试
List<String> availableFiles = listAvailableFiles(inputDirectory);
result.put("result", "错误: 输入文件不存在: " + inputPath +
"\n目录中的文件: " + availableFiles);
return result;
}
// 确保输出目录存在
Files.createDirectories(outputPath.getParent());
System.out.println("开始转换文件: " + correctedFileName);
// 提取文本内容
String textContent = extractTextFromDocx(inputPath.toString());
if (textContent == null || textContent.trim().isEmpty()) {
result.put("result", "错误: 文件内容为空或提取失败: " + correctedFileName);
return result;
}
// 转换为 Markdown 格式
String markdownContent = convertToMarkdown(textContent);
// 保存 Markdown 文件
Files.write(outputPath, markdownContent.getBytes("UTF-8"));
System.out.println("转换完成: " + correctedFileName + " → " + outputFilename);
// 构建返回结果
String preview = markdownContent.length() > 500 ?
markdownContent.substring(0, 500) + "..." : markdownContent;
result.put("result", "成功转换文件: " + correctedFileName + " -> " + outputFilename +
"\n\n内容预览:\n" + preview);
} catch (Exception e) {
String errorMsg = "转换过程中发生错误: " + e.getMessage();
System.err.println(errorMsg);
result.put("result", errorMsg);
}
return result;
}
/**
* 修正文件名中的特殊字符
*/
private static String correctFileName(String fileName) {
if (fileName == null) return "";
String corrected = fileName;
try {
// 尝试 URL 解码(处理 + 号被编码的情况)
corrected = URLDecoder.decode(fileName, "UTF-8");
} catch (Exception e) {
System.out.println("URL解码失败,使用原始文件名");
}
// 处理常见的编码问题
corrected = corrected
.replace(" ", "+") // 空格转回加号
.replace("%20", "+") // URL 空格转加号
.replace("%2B", "+") // 显式的加号编码转回加号
.trim();
return corrected;
}
/**
* 在目录中查找实际文件(处理文件名不匹配)
*/
private static String findActualFile(String directory, String targetFileName) {
try {
File dir = new File(directory);
if (!dir.exists() || !dir.isDirectory()) {
return null;
}
// 生成可能的文件名变体
String[] possibleNames = generatePossibleFileNames(targetFileName);
for (String possibleName : possibleNames) {
File possibleFile = new File(dir, possibleName);
if (possibleFile.exists()) {
return possibleName;
}
}
// 如果没有精确匹配,尝试模糊匹配
String[] files = dir.list();
if (files != null) {
for (String file : files) {
if (isLikelyMatch(file, targetFileName)) {
return file;
}
}
}
} catch (Exception e) {
System.err.println("查找文件时出错: " + e.getMessage());
}
return null;
}
/**
* 生成可能的文件名变体
*/
private static String[] generatePossibleFileNames(String fileName) {
List<String> variants = new ArrayList<>();
// 原始文件名
variants.add(fileName);
// URL 解码变体
try {
variants.add(URLDecoder.decode(fileName, "UTF-8"));
} catch (Exception e) {
// 忽略解码错误
}
// 加号处理变体
variants.add(fileName.replace("+", " ")); // 加号变空格
variants.add(fileName.replace("+", "%2B")); // 加号编码
variants.add(fileName.replace("+", "")); // 去掉加号
// 中文文件名常见问题
variants.add(fileName.replace("SAAS", "SaaS")); // 大小写修正
return variants.toArray(new String[0]);
}
/**
* 模糊匹配文件名
*/
private static boolean isLikelyMatch(String actualFile, String targetFile) {
String actualLower = actualFile.toLowerCase();
String targetLower = targetFile.toLowerCase();
// 去掉扩展名比较
String actualBase = actualLower.replace(".docx", "");
String targetBase = targetLower.replace(".docx", "");
// 去掉特殊字符比较
actualBase = actualBase.replaceAll("[+\\s]", "");
targetBase = targetBase.replaceAll("[+\\s]", "");
return actualBase.contains(targetBase) || targetBase.contains(actualBase);
}
/**
* 列出目录中所有可用的文件
*/
private static List<String> listAvailableFiles(String directory) {
List<String> files = new ArrayList<>();
try {
File dir = new File(directory);
String[] fileList = dir.list();
if (fileList != null) {
files.addAll(Arrays.asList(fileList));
}
} catch (Exception e) {
files.add("无法读取目录: " + e.getMessage());
}
return files;
}
/**
* 从 DOCX 文件中提取文本内容
*/
private static String extractTextFromDocx(String filePath) {
StringBuilder content = new StringBuilder();
try (FileInputStream fis = new FileInputStream(filePath);
XWPFDocument document = new XWPFDocument(fis)) {
// 处理段落
for (XWPFParagraph paragraph : document.getParagraphs()) {
String text = paragraph.getText();
if (text != null && !text.trim().isEmpty()) {
content.append(text).append("\n");
}
}
// 处理表格
for (XWPFTable table : document.getTables()) {
for (XWPFTableRow row : table.getRows()) {
List<String> rowData = new ArrayList<>();
for (XWPFTableCell cell : row.getTableCells()) {
rowData.add(cell.getText());
}
content.append(String.join(" | ", rowData)).append("\n");
}
content.append("\n");
}
} catch (Exception e) {
System.err.println("提取文本时出错: " + e.getMessage());
return null;
}
return content.toString();
}
/**
* 将纯文本转换为基本的 Markdown 格式
*/
private static String convertToMarkdown(String text) {
if (text == null || text.trim().isEmpty()) {
return "";
}
String[] lines = text.split("\n");
List<String> processedLines = new ArrayList<>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i].trim();
// 跳过空行(除非是连续的空行)
if (line.isEmpty()) {
if (!processedLines.isEmpty() && !processedLines.get(processedLines.size() - 1).isEmpty()) {
processedLines.add("");
}
continue;
}
// 检测标题(基于行长度和上下文)
if (isLikelyHeading(line, i, lines)) {
processedLines.add("## " + line);
}
// 检测列表项
else if (line.startsWith("•") || line.startsWith("·") || line.startsWith("-")) {
processedLines.add("- " + line.substring(1).trim());
}
// 检测数字列表
else if (Pattern.matches("^\\d+\\.\\s.*", line)) {
processedLines.add(line);
}
else {
// 普通段落
processedLines.add(line);
}
}
// 重新组合并清理格式
String result = String.join("\n", processedLines);
result = result.replaceAll("\n{3,}", "\n\n");
return result.trim();
}
private static boolean isLikelyHeading(String line, int lineIndex, String[] allLines) {
if (line.trim().isEmpty()) return false;
if (line.length() > 150) return false;
if (line.endsWith(".") || line.endsWith("。") || line.endsWith(";") || line.endsWith(";")) {
return false;
}
if (lineIndex + 1 < allLines.length) {
String nextLine = allLines[lineIndex + 1].trim();
if (!nextLine.isEmpty() && nextLine.length() > line.length() * 1.5) {
return true;
}
}
List<Boolean> headingIndicators = Arrays.asList(
line.length() < 80,
line.equals(line.toUpperCase()),
Character.isUpperCase(line.charAt(0)) && countUppercaseChars(line) > line.length() * 0.3,
containsHeadingKeywords(line.toLowerCase())
);
return headingIndicators.stream().anyMatch(Boolean::booleanValue);
}
private static int countUppercaseChars(String str) {
int count = 0;
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) count++;
}
return count;
}
private static boolean containsHeadingKeywords(String line) {
String[] keywords = {"chapter", "section", "part", "引言", "目录", "摘要", "结论"};
return Arrays.stream(keywords).anyMatch(line::contains);
}
}