diff options
-rw-r--r-- | build.gradle | 22 | ||||
-rw-r--r-- | gradle/wrapper/gradle-wrapper.jar | bin | 0 -> 60756 bytes | |||
-rw-r--r-- | gradle/wrapper/gradle-wrapper.properties | 6 | ||||
-rwxr-xr-x | gradlew | 234 | ||||
-rw-r--r-- | gradlew.bat | 89 | ||||
-rw-r--r-- | settings.gradle | 2 | ||||
-rw-r--r-- | src/main/java/info/selflearner/ocr_telegram/Application.java | 93 | ||||
-rw-r--r-- | src/main/java/info/selflearner/ocr_telegram/exception/PassportNotFoundException.java | 7 | ||||
-rw-r--r-- | src/main/java/info/selflearner/ocr_telegram/model/Passport.java | 70 | ||||
-rw-r--r-- | src/main/java/info/selflearner/ocr_telegram/util/FileContentReader.java | 22 | ||||
-rw-r--r-- | src/main/java/info/selflearner/ocr_telegram/util/OCR.java | 120 | ||||
-rw-r--r-- | src/main/resources/secrets.properties | 1 |
12 files changed, 666 insertions, 0 deletions
diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..d82dff6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,22 @@ +plugins { + id 'java' +} + +group = 'info.selflearner' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'com.github.pengrad:java-telegram-bot-api:7.11.0' + implementation group: 'net.sourceforge.tess4j', name: 'tess4j', version: '5.13.0' + implementation group: 'org.json', name: 'json', version: '20250107' + testImplementation platform('org.junit:junit-bom:5.10.0') + testImplementation 'org.junit.jupiter:junit-jupiter' +} + +test { + useJUnitPlatform() +}
\ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..249e583 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..92420ce --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Jan 25 14:20:50 MVT 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..47106cf --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'ocr-telegram' + diff --git a/src/main/java/info/selflearner/ocr_telegram/Application.java b/src/main/java/info/selflearner/ocr_telegram/Application.java new file mode 100644 index 0000000..eacdfd4 --- /dev/null +++ b/src/main/java/info/selflearner/ocr_telegram/Application.java @@ -0,0 +1,93 @@ +package info.selflearner.ocr_telegram; + +import com.pengrad.telegrambot.TelegramBot; +import com.pengrad.telegrambot.UpdatesListener; +import com.pengrad.telegrambot.model.PhotoSize; +import com.pengrad.telegrambot.model.request.ParseMode; +import com.pengrad.telegrambot.request.GetFile; +import com.pengrad.telegrambot.request.SendMessage; +import com.pengrad.telegrambot.response.GetFileResponse; +import info.selflearner.ocr_telegram.exception.PassportNotFoundException; +import info.selflearner.ocr_telegram.model.Passport; +import info.selflearner.ocr_telegram.util.FileContentReader; +import info.selflearner.ocr_telegram.util.OCR; + +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.channels.ReadableByteChannel; +import java.util.ResourceBundle; + +public class Application { + + public static void main(String[] args) { + TelegramBot bot = new TelegramBot(ResourceBundle.getBundle("secrets").getString("BOT_TOKEN")); + + bot.setUpdatesListener(updateList -> { + if (updateList.getFirst().message() != null && updateList.getFirst().message().text() != null) { + long chatId = updateList.getFirst().message().chat().id(); + + bot.execute(new SendMessage(chatId, "Message received: " + updateList.getFirst().message().text())); + } + + if (updateList.getFirst().message() != null && updateList.getFirst().message().photo() != null) { + long chatId = updateList.getFirst().message().chat().id(); + + PhotoSize[] photoSizes = updateList.getFirst().message().photo(); + PhotoSize highestQualityPhotoSize = photoSizes[photoSizes.length - 1]; + GetFile request = new GetFile(highestQualityPhotoSize.fileId()); + GetFileResponse getFileResponse = bot.execute(request); + + try { + URL photoURL = new URI(bot.getFullFilePath(getFileResponse.file())).toURL(); + + ReadableByteChannel readableByteChannel = Channels.newChannel(photoURL.openStream()); + File photo = new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/" + getFileResponse.file().filePath()); + File ocrFile = new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/ocr/" + getFileResponse.file().filePath().split("/")[1] + ".txt"); + + bot.execute(new SendMessage(chatId, "Processing, please wait...")); + + new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/photos/").mkdirs(); + new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/ocr/").mkdirs(); + + if (!photo.exists()) { + try (FileOutputStream fileOutputStream = new FileOutputStream(photo)) { + FileChannel fileChannel = fileOutputStream.getChannel(); + fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE); + } catch (IOException ioException) { + throw new RuntimeException(ioException); + } + } + if (!ocrFile.exists()) { + Passport passport = OCR.performPassport(photo); + + try (BufferedWriter writer = new BufferedWriter(new FileWriter(ocrFile))) { + writer.write(passport.toString()); + } + } + + bot.execute(new SendMessage(chatId, FileContentReader.read(ocrFile)).parseMode(ParseMode.Markdown)); + } catch (URISyntaxException | IOException | InterruptedException e) { + throw new RuntimeException(e); + } catch (PassportNotFoundException e) { + bot.execute(new SendMessage(chatId, "Passport not found!")); + } + } + + return UpdatesListener.CONFIRMED_UPDATES_ALL; + }, telegramException -> { + if (telegramException.response() != null) { + // got bad response from telegram + telegramException.response().errorCode(); + telegramException.response().description(); + } else { + // probably network error + telegramException.printStackTrace(); + } + }); + } + +}
\ No newline at end of file diff --git a/src/main/java/info/selflearner/ocr_telegram/exception/PassportNotFoundException.java b/src/main/java/info/selflearner/ocr_telegram/exception/PassportNotFoundException.java new file mode 100644 index 0000000..50cb8f7 --- /dev/null +++ b/src/main/java/info/selflearner/ocr_telegram/exception/PassportNotFoundException.java @@ -0,0 +1,7 @@ +package info.selflearner.ocr_telegram.exception; + +public class PassportNotFoundException extends Exception { + public PassportNotFoundException(String errorMessage) { + super(errorMessage); + } +} diff --git a/src/main/java/info/selflearner/ocr_telegram/model/Passport.java b/src/main/java/info/selflearner/ocr_telegram/model/Passport.java new file mode 100644 index 0000000..4e8a0a7 --- /dev/null +++ b/src/main/java/info/selflearner/ocr_telegram/model/Passport.java @@ -0,0 +1,70 @@ +package info.selflearner.ocr_telegram.model; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class Passport { + public char type; + public Character subtype; + public String issuer; + public String surname; + public String givenNames; + public String number; + public String nationality; + public LocalDate dateOfBirth; + public Character sex; + public LocalDate expirationDate; + public String personalNumber; + public int[] mrzLinesConfidence; + + public Passport(char type, Character subtype, String issuer, String surname, String givenNames, String number, String nationality, LocalDate dateOfBirth, Character sex, LocalDate expirationDate, String personalNumber, int[] mrzLinesConfidence) { + this.type = type; + this.subtype = subtype; + this.issuer = issuer; + this.surname = surname; + this.givenNames = givenNames; + this.number = number; + this.nationality = nationality; + this.dateOfBirth = dateOfBirth; + this.sex = sex; + this.expirationDate = expirationDate; + this.personalNumber = personalNumber; + this.mrzLinesConfidence = mrzLinesConfidence; + } + + public Passport(String[] mrzLines, int[] mrzLinesConfidence) { + this.type = mrzLines[0].charAt(0); + this.subtype = mrzLines[0].charAt(1) == '<' ? null : mrzLines[0].charAt(0); + this.issuer = mrzLines[0].substring(2, 5); + this.surname = mrzLines[0].substring(5, mrzLines[0].indexOf('<', 6)); + this.givenNames = mrzLines[0].substring(surname.length() + 7, mrzLines[0].indexOf('<', surname.length() + 8)); + this.number = mrzLines[1].substring(0, 9); + this.nationality = mrzLines[1].substring(10, 13); + if (Integer.parseInt("20" + mrzLines[1].substring(13, 15)) < LocalDate.now().getYear()) { + this.dateOfBirth = LocalDate.of(Integer.parseInt("20" + mrzLines[1].substring(13, 15)), Integer.parseInt(mrzLines[1].substring(15, 17)), Integer.parseInt(mrzLines[1].substring(17, 19))); + } else { + this.dateOfBirth = LocalDate.of(Integer.parseInt("19" + mrzLines[1].substring(13, 15)), Integer.parseInt(mrzLines[1].substring(15, 17)), Integer.parseInt(mrzLines[1].substring(17, 19))); + } + this.sex = mrzLines[1].charAt(20) != '<' ? mrzLines[1].charAt(20) : null; + this.expirationDate = LocalDate.of(Integer.parseInt("20" + mrzLines[1].substring(21, 23)), Integer.parseInt(mrzLines[1].substring(23, 25)), Integer.parseInt(mrzLines[1].substring(25, 27))); + this.personalNumber = mrzLines[1].substring(28, 42); + this.mrzLinesConfidence = mrzLinesConfidence; + } + + @Override + public String toString() { + return "*Passport*\n" + + "Type: `" + type + "`\n" + + "Subtype: `" + subtype + "`\n" + + "Issuer: `" + issuer + "`\n" + + "Surname: `" + surname + "`\n" + + "Given names: `" + givenNames + "`\n" + + "Number: `" + number + "`\n" + + "Nationality: `" + nationality + "`\n" + + "Date of birth: `" + dateOfBirth.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + "`\n" + + "Gender: `" + sex + "`\n" + + "Expiration date: `" + expirationDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + "`\n" + + "Personal number: `" + personalNumber + "`\n"; + } +} + diff --git a/src/main/java/info/selflearner/ocr_telegram/util/FileContentReader.java b/src/main/java/info/selflearner/ocr_telegram/util/FileContentReader.java new file mode 100644 index 0000000..34123c5 --- /dev/null +++ b/src/main/java/info/selflearner/ocr_telegram/util/FileContentReader.java @@ -0,0 +1,22 @@ +package info.selflearner.ocr_telegram.util; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileContentReader { + + public static String read(File file) throws IOException { + try(FileReader fileReader = new FileReader(file)) { + StringBuilder content = new StringBuilder(); + int nextChar; + + while ((nextChar = fileReader.read()) != -1) { + content.append((char) nextChar); + } + + return String.valueOf(content); + } + } + +} diff --git a/src/main/java/info/selflearner/ocr_telegram/util/OCR.java b/src/main/java/info/selflearner/ocr_telegram/util/OCR.java new file mode 100644 index 0000000..55e577f --- /dev/null +++ b/src/main/java/info/selflearner/ocr_telegram/util/OCR.java @@ -0,0 +1,120 @@ +package info.selflearner.ocr_telegram.util; + +import info.selflearner.ocr_telegram.exception.PassportNotFoundException; +import info.selflearner.ocr_telegram.model.Passport; +import net.sourceforge.tess4j.*; +import net.sourceforge.tess4j.util.LoadLibs; +import org.json.JSONArray; +import org.json.JSONObject; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.geom.AffineTransform; +import java.awt.image.AffineTransformOp; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class OCR { + private static final ITesseract TESSERACT = new Tesseract(); + + static { + TESSERACT.setDatapath("src/main/resources/tessdata/"); + TESSERACT.setVariable("user_defined_dpi", "300"); + System.setProperty("java.library.path", LoadLibs.extractTessResources("win32-x86-64").getPath()); + } + + public static String perform(File file, String languages) throws TesseractException { + TESSERACT.setLanguage(languages); + String ocrResult = TESSERACT.doOCR(file); + file.delete(); + return ocrResult; + } + + public static Passport performPassport(File file) throws IOException, InterruptedException, PassportNotFoundException { + for (int imageRotateAngle = 0; imageRotateAngle <= 270; imageRotateAngle += 90) { + if (imageRotateAngle == 90) { + System.out.println("Rotating image to 90 degrees..."); + rotateImageVertically(file, true); + } else if (imageRotateAngle == 180) { + System.out.println("Rotating image to 180 degrees..."); + rotateImageHorizontally(file); + } else if (imageRotateAngle == 270) { + System.out.println("Rotating image to 270 degrees..."); + rotateImageVertically(file, false); + } + + Runtime.getRuntime().exec(new String[]{"surya_ocr", file.getPath(), "--results_dir", System.getProperty("java.io.tmpdir"), "--langs=en"}).waitFor(); + JSONArray jsonTextLines = new JSONObject(Files.readAllLines(Path.of(System.getProperty("java.io.tmpdir"), "/", file.getName().split("\\.")[0], "/results.json")).getFirst()) + .getJSONArray(file.getName().split("\\.")[0]).getJSONObject(0).getJSONArray("text_lines"); + int mrzStartingIndex = -1; + + for (int arrayIndex = 0; arrayIndex < jsonTextLines.length() && mrzStartingIndex == -1; arrayIndex++) { + if (jsonTextLines.getJSONObject(arrayIndex).getString("text").indexOf("P<") == 0) { + mrzStartingIndex = arrayIndex; + } + } + + if (mrzStartingIndex != -1) { + System.out.println("MRZ1: " + jsonTextLines.getJSONObject(mrzStartingIndex).getString("text")); + System.out.println("MRZ2: " + jsonTextLines.getJSONObject(mrzStartingIndex + 1).getString("text")); + try { + return new Passport(new String[]{jsonTextLines.getJSONObject(mrzStartingIndex).getString("text"), jsonTextLines.getJSONObject(mrzStartingIndex + 1).getString("text")}, + new int[]{(int) (jsonTextLines.getJSONObject(mrzStartingIndex).getDouble("confidence") * 100), (int) (jsonTextLines.getJSONObject(mrzStartingIndex + 1).getDouble("confidence") * 100)}); + } catch (Exception _) { + + } + } + } + throw new PassportNotFoundException("Passport not found"); + } + + private static void rotateImageVertically(File image, boolean counterClockwise) throws IOException { + BufferedImage bufferedImage = ImageIO.read(image); + BufferedImage output = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(), bufferedImage.getType()); + + AffineTransform affineTransform = getAffineTransform(counterClockwise, bufferedImage); + + AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR); + affineTransformOp.filter(bufferedImage, output); + + ImageIO.write(output, "jpg", image); + } + + public static void rotateImageHorizontally(File image) throws IOException { + BufferedImage imageToRotate = ImageIO.read(image); + + int widthOfImage = imageToRotate.getWidth(); + int heightOfImage = imageToRotate.getHeight(); + int typeOfImage = imageToRotate.getType(); + + BufferedImage output = new BufferedImage(widthOfImage, heightOfImage, typeOfImage); + + Graphics2D graphics2D = output.createGraphics(); + + graphics2D.rotate(Math.toRadians(180), widthOfImage / 2.0, heightOfImage / 2.0); + graphics2D.drawImage(imageToRotate, null, 0, 0); + + ImageIO.write(output, "jpg", image); + } + + private static AffineTransform getAffineTransform(boolean counterClockwise, BufferedImage bufferedImage) { + int imageWidth = bufferedImage.getWidth(); + int imageHeight = bufferedImage.getHeight(); + + AffineTransform affineTransform = new AffineTransform(); + affineTransform.rotate((!counterClockwise ? Math.PI : -Math.PI) / 2, imageWidth / 2.0, imageHeight / 2.0); + + double offset = (imageWidth - imageHeight) / 2.0; + if (!counterClockwise) { + affineTransform.translate(offset, offset); + } else { + affineTransform.translate(-offset, -offset); + } + return affineTransform; + } + +} + diff --git a/src/main/resources/secrets.properties b/src/main/resources/secrets.properties new file mode 100644 index 0000000..c85bd26 --- /dev/null +++ b/src/main/resources/secrets.properties @@ -0,0 +1 @@ +BOT_TOKEN=7609685856:AAGKF3Ld_OYqwsJ7a0b4oEknjJiqj8DJaWk
\ No newline at end of file |