diff --git a/README.md b/README.md index d3757f9..4162812 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ =============== Программа для поиска номеров УДК PDF и DJVU файлах. + Для распознавания используется OCR Tesseract 5 https://github.com/tesseract-ocr/tesseract + Для Windows 7, я использую https://github.com/UB-Mannheim/tesseract/wiki + Для работы с djvu используется DjVuLibre https://djvu.sourceforge.net/index.html diff --git a/pom.xml b/pom.xml index a0b4b4c..3bf0829 100644 --- a/pom.xml +++ b/pom.xml @@ -42,6 +42,12 @@ commons-cli 1.9.0 + + org.junit.jupiter + junit-jupiter + RELEASE + test + diff --git a/src/main/java/ru/mcs/udk/UDKSearcher.java b/src/main/java/ru/mcs/udk/UDKSearcher.java index 8a563f0..91c9dfd 100644 --- a/src/main/java/ru/mcs/udk/UDKSearcher.java +++ b/src/main/java/ru/mcs/udk/UDKSearcher.java @@ -10,15 +10,22 @@ import ru.mcs.udk.factory.DocumentScannerFactory; import ru.mcs.udk.wrapper.DocumentInfo; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; @@ -63,7 +70,8 @@ } // проходимся по всем найденым файлам и ищем УДК - findUdk(outputFile); +// findUdk(outputFile); + findUdk2(outputFile, foundFiles.size()); } catch (ParseException e) { System.out.println("Ошибка при разборе аргументов: " + e.getMessage()); printHelp(options); @@ -106,18 +114,19 @@ formatter.printHelp("UDKSearcher", options); } - private static void findUdk(String outputFile) { - try { - // Чтение всех строк из CSV-файла - List lines = Files.readAllLines(Paths.get(outputFile)); - List updatedLines = new ArrayList<>(); - int processedFiles = 0; // Количество обработанных файлов - int totalFiles = lines.size(); // Общее количество файлов - DocumentInfo documentInfo; + private static void findUdk2(String fileCsv, int totalFiles) { + Path inputPath = Paths.get(fileCsv); + Path outputPath = inputPath.resolveSibling(inputPath.getFileName() + ".out"); + DocumentInfo documentInfo; + int processedFiles = 0; // Количество обработанных файлов - // Проход по каждой строке в CSV - for (String line : lines) { - String filePath = line.trim(); // Получаем путь к файлу + try (BufferedReader reader = Files.newBufferedReader(inputPath); + BufferedWriter writer = Files.newBufferedWriter(outputPath)) { + + String line; + while ((line = reader.readLine()) != null) { + + String filePath = line.trim(); File file = new File(filePath); // Проверка, существует ли файл @@ -132,17 +141,40 @@ // Вычисляем процент завершения double progress = (double) processedFiles / totalFiles * 100; System.out.printf("Прогресс: %.2f%%\r", progress); - - updatedLines.add(String.format("%s;%s;%s;%s;%s;%s", line, documentInfo.getFileSize(), documentInfo.getTime(), documentInfo.getLanguage(), documentInfo.getUdk(), documentInfo.getError())); + writer.write(String.format("%s;%s;%s;%s;%s;%s", line, documentInfo.getFileSize(), documentInfo.getTime(), documentInfo.getLanguage(), documentInfo.getUdk(), documentInfo.getError())); } else { - updatedLines.add(String.format("%s;%s;%s;%s;%s;%s", line, "File not found", "", "", "", "")); // Если файл не найден + writer.write(String.format("%s;%s;%s;%s;%s;%s", line, "File not found", "", "", "", "")); // Если файл не найден } - - // Запись обновленных строк обратно в файл после обработки каждой строки - Files.write(Paths.get(outputFile), updatedLines); + writer.newLine(); } - } catch (IOException e) { - System.out.println("Ошибка при работе с файлом: " + e.getMessage()); + } catch (Exception e) { + System.err.println("Error: " + e.getMessage()); + e.printStackTrace(); + System.exit(2); + } + + try { + replaceOriginalFile(inputPath, outputPath); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static void replaceOriginalFile(Path original, Path tempFile) throws Exception { + Path backup = original.resolveSibling(original.getFileName() + ".bak"); + + // Создаем бэкап оригинала + Files.move(original, backup, StandardCopyOption.REPLACE_EXISTING); + + try { + // Перемещаем временный файл на место оригинала + Files.move(tempFile, original, StandardCopyOption.ATOMIC_MOVE); + // Удаляем бэкап после успешной замены + Files.deleteIfExists(backup); + } catch (Exception e) { + // Восстанавливаем из бэкапа при ошибке + Files.move(backup, original, StandardCopyOption.REPLACE_EXISTING); + throw e; } } } diff --git a/src/main/java/ru/mcs/udk/document/impl/DJVUScanner.java b/src/main/java/ru/mcs/udk/document/impl/DJVUScanner.java index 827a80a..c4466b4 100644 --- a/src/main/java/ru/mcs/udk/document/impl/DJVUScanner.java +++ b/src/main/java/ru/mcs/udk/document/impl/DJVUScanner.java @@ -20,7 +20,7 @@ DocumentInfo documentInfo = new DocumentInfo(); documentInfo.setError(""); documentInfo.setUdk(""); - for (int pageIndex = 0; pageIndex < 6; pageIndex++) { + for (int pageIndex = 1; pageIndex < 7; pageIndex++) { String outputFile = String.format("temp/page_%d.tiff", pageIndex); Process process; try { @@ -37,6 +37,7 @@ String udk = findUDK(text); documentInfo.setUdk(udk); if (udk != null && !udk.isEmpty()) { + documentInfo.setLanguage("ru"); break; } } diff --git a/temp/page_3.tiff b/temp/page_3.tiff deleted file mode 100644 index 85c95e1..0000000 --- a/temp/page_3.tiff +++ /dev/null Binary files differ