├── .gitignore ├── LICENSE ├── README.md ├── cli ├── pom.xml └── src │ └── main │ └── java │ └── ocr │ └── cli │ └── CLI.java ├── common ├── pom.xml └── src │ └── main │ └── java │ └── ocr │ └── common │ └── Util.java ├── conversion ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ocr │ │ │ └── conversion │ │ │ └── AlmostSimpleRenderer.java │ ├── resources │ │ ├── log4j.properties │ │ └── logback.xml │ └── scala │ │ └── ocr │ │ └── conversion │ │ ├── ConfigOptions.scala │ │ ├── Converter.scala │ │ └── Driver.scala │ └── test │ ├── resources │ └── text-detection.pdf │ └── scala │ └── ocr │ └── conversion │ └── ConverterSpec.scala ├── extraction ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ocr │ │ │ └── extraction │ │ │ └── tesseract │ │ │ └── TesseractUtil.java │ └── resources │ │ ├── log4j.properties │ │ └── logback.xml │ └── test │ ├── java │ └── ocr │ │ └── extraction │ │ └── tesseract │ │ └── TesseractUtilTest.java │ └── resources │ └── pdf-test.tiff ├── nifi ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ocr │ │ │ └── nifi │ │ │ ├── conversion │ │ │ └── ConversionProcessor.java │ │ │ ├── extraction │ │ │ └── ExtractionProcessor.java │ │ │ ├── preprocessing │ │ │ └── PreprocessingProcessor.java │ │ │ ├── util │ │ │ └── JSONUtils.java │ │ │ └── validation │ │ │ ├── JsonValidator.java │ │ │ └── Validation.java │ ├── nifi │ │ └── templates │ │ │ └── scalable-ocr.xml │ └── resources │ │ ├── META-INF │ │ └── services │ │ │ └── org.apache.nifi.processor.Processor │ │ ├── log4j.properties │ │ └── logback.xml │ └── test │ └── java │ └── ocr │ └── nifi │ ├── conversion │ └── ConversionProcessorTest.java │ ├── extraction │ └── ExtractionProcessorTest.java │ └── preprocessing │ └── PreprocessingTest.java ├── pom.xml ├── preprocessing ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ocr │ │ │ └── preprocessing │ │ │ └── conversion │ │ │ ├── CLIUtils.java │ │ │ ├── CleaningOptions.java │ │ │ ├── CommandFailedException.java │ │ │ ├── Handler.java │ │ │ ├── ImageUtils.java │ │ │ ├── TextCleaner.java │ │ │ └── handler │ │ │ ├── AdaptiveBlurringHandler.java │ │ │ ├── EnhancingHandler.java │ │ │ ├── FilterHandler.java │ │ │ ├── GrayscaleHandler.java │ │ │ ├── LayoutHandler.java │ │ │ ├── OffsetHandler.java │ │ │ ├── PadHandler.java │ │ │ ├── RotationHandler.java │ │ │ ├── SaturationHandler.java │ │ │ ├── SharpenHandler.java │ │ │ ├── SmoothingThresholdHandler.java │ │ │ ├── TrimHandler.java │ │ │ └── UnrotateHandler.java │ └── resources │ │ ├── log4j.properties │ │ └── logback.xml │ └── test │ ├── java │ └── ocr │ │ └── preprocessing │ │ └── conversion │ │ └── TextCleanerTest.java │ └── resources │ └── images │ ├── abbott2.jpg │ ├── brscan_original_r90-out.jpg │ └── brscan_original_r90.jpg ├── presentation ├── README.md ├── conference-rules.txt ├── scalable-ocr-hadoop-summit-2016.pptx └── text-detection.pdf └── scripts ├── clinton_email_grabber.py └── metadata.csv /.gitignore: -------------------------------------------------------------------------------- 1 | # Covers Eclipse 2 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 3 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 4 | 5 | # User-specific stuff: 6 | .idea/workspace.xml 7 | .idea/tasks.xml 8 | .idea/dictionaries 9 | 10 | # Sensitive or high-churn files: 11 | .idea/dataSources.ids 12 | .idea/dataSources.xml 13 | .idea/sqlDataSources.xml 14 | .idea/dynamic.xml 15 | .idea/uiDesigner.xml 16 | 17 | # Gradle: 18 | .idea/gradle.xml 19 | .idea/libraries 20 | 21 | # Mongo Explorer plugin: 22 | .idea/mongoSettings.xml 23 | 24 | ## File-based project format: 25 | *.iws 26 | 27 | ## Plugin-specific files: 28 | 29 | # IntelliJ 30 | /out/ 31 | 32 | # mpeltonen/sbt-idea plugin 33 | .idea_modules/ 34 | 35 | # JIRA plugin 36 | atlassian-ide-plugin.xml 37 | 38 | # Crashlytics plugin (for Android Studio and IntelliJ) 39 | com_crashlytics_export_strings.xml 40 | crashlytics.properties 41 | crashlytics-build.properties 42 | fabric.properties 43 | 44 | # Intellij 45 | .idea/ 46 | *.iml 47 | *.iws 48 | 49 | # Mobile Tools for Java (J2ME) 50 | .mtj.tmp/ 51 | 52 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 53 | hs_err_pid* 54 | 55 | *~ 56 | *.swp 57 | target/ 58 | pig*.log 59 | logs/* 60 | temp/ 61 | mockito-capture/ 62 | 63 | *.pydevproject 64 | .project 65 | .metadata 66 | bin/** 67 | tmp/** 68 | tmp/**/* 69 | *.tmp 70 | *.bak 71 | *.swp 72 | *~.nib 73 | local.properties 74 | .classpath 75 | .settings/ 76 | .loadpath 77 | target/ 78 | *.class 79 | *.factorypath 80 | 81 | # External tool builders 82 | .externalToolBuilders/ 83 | 84 | # Locally stored "Eclipse launch configurations" 85 | *.launch 86 | 87 | # CDT-specific 88 | .cproject 89 | 90 | # PDT-specific 91 | .buildpath 92 | 93 | .DS_Store 94 | 95 | dependency-reduced-pom.xml 96 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Scalable OCR 2 | 3 | Welcome to the project 4 | 5 | So much of our data is represented as human readable scans of documents. 6 | However, this kind of document-by-document analysis does not scale, so 7 | it is becoming evermore common to need to ingest large numbers of PDFs 8 | or scanned documents shows up in almost all sectors. Inevitably these 9 | scanned documents must be converted to text for analysis. And since 10 | dealing with unstructured data is one of the main selling points for a 11 | platform like Hadoop, it means that we must convert large volumes of 12 | potentially large documents into a textual representation. We will show 13 | you how to use scalable open source tooling (Apache NiFi and Tesseract) to scalably convert volumes of PDFs and ingest into a platform that will allow you to analyze this data at scale. 14 | 15 | # Modules 16 | 17 | ### Core Modules 18 | - conversion - convert multi-page PDFs to single-page TIFF files 19 | - preprocessing - image correction for better text extraction during OCR 20 | - extraction - OCR images and output text 21 | 22 | ### Utility 23 | - CLI - command line tool for manual pipeline process execution 24 | - NiFi - custom processors for exposing the core modules via NiFi. Workflow template. 25 | 26 | # Developers 27 | 28 | #### Cutting a release for ocr 29 | 30 | ```bash 31 | mvn release:prepare -Dscm-connection.url= -Dscm-developer-connection.url= 32 | ``` 33 | 34 | **Note**: The main pom assumes "scm:git:" - simply pass in the URL portion as a build parameter as shown above. 35 | 36 | Examples: [maven scm] (http://maven.apache.org/scm/git.html) 37 | 38 | 1. local git - file://localhost/foo/bar/mygitrepodir 39 | 1. github connection url (readonly) - git://github.com/mmiklavc/myproject.git 40 | 1. github developer connection url (read/write) - git@github.com:mmiklavc/myproject.git 41 | 42 | Performing the release prepare will do the following high-level steps: 43 | 44 | 1. Change pom versions from X.X-SNAPSHOT to X.X 45 | 1. Commit the new poms for the release to Git 46 | 1. Tag the release commit in Git 47 | 1. Increment poms to a new SNAPSHOT version, e.g. Update from X.0-SNAPSHOT to X.1-SNAPSHOT 48 | 1. Commit the updated SNAPSHOT poms 49 | 50 | *See [Maven release prepare] (http://maven.apache.org/maven-release/maven-release-plugin/examples/prepare-release.html) documentation for more detail* 51 | 52 | -------------------------------------------------------------------------------- /cli/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | ocr 9 | ocr 10 | 1.0-SNAPSHOT 11 | 12 | 13 | cli 14 | cli 15 | 16 | 17 | 18 | 19 | ocr 20 | conversion 21 | ${project.parent.version} 22 | 23 | 24 | ocr 25 | extraction 26 | ${project.parent.version} 27 | 28 | 29 | ocr 30 | preprocessing 31 | ${project.parent.version} 32 | 33 | 34 | 35 | 36 | 37 | 38 | maven-compiler-plugin 39 | 3.1 40 | 41 | 1.8 42 | 1.8 43 | 44 | 45 | 46 | org.apache.maven.plugins 47 | maven-shade-plugin 48 | 2.4.3 49 | 50 | 51 | package 52 | 53 | shade 54 | 55 | 56 | 57 | 58 | *:* 59 | 60 | META-INF/*.SF 61 | META-INF/*.DSA 62 | META-INF/*.RSA 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.opentripplanner.graph_builder.GraphBuilderMain 71 | Java Advanced Imaging Image I/O Tools 72 | 1.1 73 | Sun Microsystems, Inc. 74 | com.sun.media.imageio 75 | 1.1 76 | Sun Microsystems, Inc. 77 | com.sun.media.imageio 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /cli/src/main/java/ocr/cli/CLI.java: -------------------------------------------------------------------------------- 1 | package ocr.cli; 2 | 3 | import com.google.common.base.Joiner; 4 | import com.google.common.base.Splitter; 5 | import com.google.common.collect.Iterables; 6 | import net.sourceforge.tess4j.TesseractException; 7 | import ocr.conversion.Converter; 8 | import ocr.extraction.tesseract.TesseractUtil; 9 | import ocr.preprocessing.conversion.CLIUtils; 10 | import ocr.preprocessing.conversion.CleaningOptions; 11 | import ocr.preprocessing.conversion.CommandFailedException; 12 | import ocr.preprocessing.conversion.TextCleaner; 13 | import org.apache.commons.cli.*; 14 | import org.apache.commons.io.IOUtils; 15 | 16 | import java.io.*; 17 | import java.util.*; 18 | import java.util.function.Function; 19 | 20 | public class CLI { 21 | public static enum OcrOptions { 22 | HELP("h", code -> { 23 | Option o = new Option(code, "help", false, "This screen"); 24 | o.setRequired(false); 25 | return o; 26 | }), 27 | INPUT("i", code -> { 28 | Option o = new Option(code, "input", true, "Single Input File"); 29 | o.setRequired(false); 30 | o.setArgName("INPUT"); 31 | return o; 32 | }), 33 | INPUT_DIR("id", code -> { 34 | Option o = new Option(code, "input", true, "Input Directory"); 35 | o.setRequired(false); 36 | o.setArgName("DIR"); 37 | return o; 38 | }), 39 | INPUT_FILE("if", code -> { 40 | Option o = new Option(code, "input_file", true, "Input File"); 41 | o.setRequired(false); 42 | o.setArgName("FILE"); 43 | return o; 44 | }), 45 | OUTPUT("o", code -> { 46 | Option o = new Option(code, "output", true, "Output Directory"); 47 | o.setRequired(false); 48 | o.setArgName("DIR"); 49 | return o; 50 | }), 51 | PREPROCESSING("p", code -> { 52 | Option o = new Option(code, "preprocessing", true, "Preprocessing Config"); 53 | o.setRequired(false); 54 | o.setArgName("Preprocessing Configs"); 55 | return o; 56 | }), 57 | TEMP_DIR("t", code -> { 58 | Option o = new Option(code, "temp_dir", true, "Temp Dir"); 59 | o.setRequired(false); 60 | o.setArgName("DIR"); 61 | return o; 62 | }), 63 | LIB_PATH("l", code -> { 64 | Option o = new Option(code, "lib_path", true, "jna library path"); 65 | o.setRequired(false); 66 | o.setArgName("DIR"); 67 | return o; 68 | }), 69 | CONVERT_PATH("c", code -> { 70 | Option o = new Option(code, "convert_path", true, "Path to the Convert utility"); 71 | o.setRequired(false); 72 | o.setArgName("PATH"); 73 | return o; 74 | }), 75 | TESSDATA_PATH("d", code -> { 76 | Option o = new Option(code, "tess_data_path", true, "Path to TESS_DATA"); 77 | o.setRequired(false); 78 | o.setArgName("PATH"); 79 | return o; 80 | }), 81 | TESSPROPERTIES("D", code -> 82 | OptionBuilder.withArgName( "property=value" ) 83 | .hasArgs(2) 84 | .withValueSeparator() 85 | .withDescription( "Tesseract variables" ) 86 | .create( code ) 87 | 88 | ), 89 | PHASE("ph", code -> { 90 | Option o = new Option(code, "phases", true, "Which phases to run: [convert|preprocess|ocr]"); 91 | o.setRequired(false); 92 | o.setArgName("PHASE"); 93 | return o; 94 | }); 95 | Option option; 96 | String shortCode; 97 | OcrOptions(String shortCode 98 | , Function optionHandler 99 | ) { 100 | this.shortCode = shortCode; 101 | this.option = optionHandler.apply(shortCode); 102 | 103 | } 104 | 105 | public boolean has(CommandLine cli) { 106 | return cli.hasOption(shortCode); 107 | } 108 | 109 | public String get(CommandLine cli) { 110 | return cli.getOptionValue(shortCode); 111 | } 112 | public String get(CommandLine cli, String def) { 113 | return has(cli)?cli.getOptionValue(shortCode):def; 114 | } 115 | 116 | public Map getProperties(CommandLine cli) { 117 | Properties p = cli.getOptionProperties(shortCode); 118 | Map ret = new HashMap<>(); 119 | for(Map.Entry kv : p.entrySet()) { 120 | ret.put(kv.getKey().toString(), kv.getValue().toString()); 121 | } 122 | return ret; 123 | } 124 | 125 | 126 | public static CommandLine parse(CommandLineParser parser, String[] args) throws ParseException { 127 | try { 128 | CommandLine cli = parser.parse(getOptions(), args); 129 | if(HELP.has(cli)) { 130 | printHelp(); 131 | System.exit(0); 132 | } 133 | return cli; 134 | } catch (ParseException e) { 135 | System.err.println("Unable to parse args: " + Joiner.on(' ').join(args)); 136 | e.printStackTrace(System.err); 137 | printHelp(); 138 | throw e; 139 | } 140 | } 141 | 142 | public static void printHelp() { 143 | HelpFormatter formatter = new HelpFormatter(); 144 | formatter.printHelp( "OCRCLI", getOptions()); 145 | } 146 | 147 | public static Options getOptions() { 148 | Options ret = new Options(); 149 | for(OcrOptions o : OcrOptions.values()) { 150 | ret.addOption(o.option); 151 | } 152 | return ret; 153 | } 154 | } 155 | 156 | public static Set getAlreadyProcessed(File outputDir) { 157 | Set ret = new HashSet<>(); 158 | for(File f : outputDir.listFiles()) { 159 | ret.add(stripSuffix(f.getName())); 160 | } 161 | return ret; 162 | } 163 | 164 | public static String stripSuffix(String filename) { 165 | if(filename.contains(".")) { 166 | return Iterables.getFirst(Splitter.on(".").split(filename), null); 167 | } 168 | else { 169 | return filename; 170 | } 171 | } 172 | 173 | public static List filterFilesToProcess(Iterable files, Set alreadyProcessed) { 174 | List ret = new ArrayList<>(); 175 | for(File f : files) { 176 | if(!alreadyProcessed.contains(stripSuffix(f.getName()))) { 177 | ret.add(f); 178 | } 179 | else { 180 | System.out.println("Skipping " + f.getName()); 181 | } 182 | } 183 | return ret; 184 | } 185 | 186 | public static List extractFilesFromFile(File inputFile) throws IOException { 187 | BufferedReader br = new BufferedReader(new FileReader(inputFile)); 188 | List ret = new ArrayList<>(); 189 | for(String line = null; (line = br.readLine()) != null;) { 190 | ret.add(new File(line)); 191 | } 192 | return ret; 193 | } 194 | 195 | public static List extractFilesFromDirectory(File inputDir) throws IOException { 196 | List ret = new ArrayList<>(); 197 | for(File f : inputDir.listFiles()) { 198 | ret.add(f); 199 | } 200 | return ret; 201 | } 202 | 203 | public static void main(String... argv) throws ParseException, IOException, CommandFailedException, TesseractException { 204 | PosixParser parser = new PosixParser(); 205 | CommandLine cli = OcrOptions.parse(parser, argv); 206 | String phase = "all"; 207 | if(OcrOptions.PHASE.has(cli)) { 208 | phase = OcrOptions.PHASE.get(cli); 209 | } 210 | System.getProperties().setProperty("jna.library.path", OcrOptions.LIB_PATH.get(cli, "/opt/local/lib")); 211 | String preprocessingDef = OcrOptions.PREPROCESSING.get(cli); 212 | String tempDirStr = OcrOptions.TEMP_DIR.get(cli, "/tmp"); 213 | List files = null; 214 | File outDir = new File(OcrOptions.OUTPUT.get(cli, ".")); 215 | Set alreadyProcessed = getAlreadyProcessed(outDir); 216 | Map tessProperties = OcrOptions.TESSPROPERTIES.getProperties(cli); 217 | if(OcrOptions.INPUT.has(cli)) { 218 | files = Arrays.asList(new File(OcrOptions.INPUT.get(cli))); 219 | } else if(OcrOptions.INPUT_FILE.has(cli)) { 220 | files = filterFilesToProcess(extractFilesFromFile(new File(OcrOptions.INPUT_FILE.get(cli))), alreadyProcessed); 221 | } else if(OcrOptions.INPUT_DIR.has(cli)){ 222 | files = filterFilesToProcess(extractFilesFromDirectory(new File(OcrOptions.INPUT_DIR.get(cli))), alreadyProcessed); 223 | } else { 224 | throw new IllegalStateException("Must specify one of input, input directory or input file"); 225 | } 226 | File tempDir = new File(tempDirStr); 227 | String convertPath = OcrOptions.CONVERT_PATH.get(cli, "/usr/local/bin/convert"); 228 | File tessDataPath = new File(OcrOptions.TESSDATA_PATH.get(cli,"/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/")); 229 | CommandLine cleaningCli = CleaningOptions.parse(new DefaultParser(), CLIUtils.translateCommandline(preprocessingDef) ); 230 | final TextCleaner cleaner = CleaningOptions.createTextCleaner(cleaningCli, convertPath, tempDirStr); 231 | int i = 0; 232 | for(File f : files) { 233 | System.out.println("Processing " + f.getName() + " (" + i++ + " / " + files.size()+ ")"); 234 | int pageNumber = 0; 235 | if("all".equals(phase)) { 236 | for (Map.Entry page : toPages(new BufferedInputStream(new FileInputStream(f)), tempDir)) { 237 | pageNumber++; 238 | System.out.println("Page " + pageNumber); 239 | try { 240 | if (page.getValue()) { 241 | byte[] converted = cleaner.convert(new BufferedInputStream(new FileInputStream(page.getKey()))); 242 | writePreprocessed(converted, new File(outDir, f.getName() + "-" + pageNumber + ".tiff")); 243 | String pageText = TesseractUtil.INSTANCE.ocr(converted, tessDataPath, tessProperties); 244 | String fileName = f.getName() + "-" + pageNumber + ".txt"; 245 | File outFile = new File(outDir, fileName); 246 | try (PrintWriter pw = new PrintWriter(outFile)) { 247 | IOUtils.write(pageText, pw); 248 | pw.flush(); 249 | } 250 | } 251 | } finally { 252 | page.getKey().delete(); 253 | } 254 | } 255 | } else { 256 | switch(phase) { 257 | case "convert" : 258 | toPages(new BufferedInputStream(new FileInputStream(f)), outDir); 259 | return; 260 | case "preprocess" : 261 | byte[] converted = cleaner.convert(new BufferedInputStream(new FileInputStream(f))); 262 | writePreprocessed(converted, new File(outDir, f.getName() + "-" + pageNumber + ".tiff")); 263 | return; 264 | case "ocr" : 265 | try (FileInputStream fis = new FileInputStream(f)) { 266 | byte[] inFile = IOUtils.toByteArray(fis); 267 | String pageText = TesseractUtil.INSTANCE.ocr(inFile, tessDataPath, tessProperties); 268 | String fileName = f.getName() + "-" + pageNumber + ".txt"; 269 | File outFile = new File(outDir, fileName); 270 | try (PrintWriter pw = new PrintWriter(outFile)) { 271 | IOUtils.write(pageText, pw); 272 | pw.flush(); 273 | } 274 | } 275 | return; 276 | default : 277 | throw new IllegalArgumentException("Unknown phase: " + phase); 278 | } 279 | } 280 | } 281 | } 282 | 283 | private static void writePreprocessed(byte[] converted, File file) { 284 | try(FileOutputStream fos = new FileOutputStream(file)) { 285 | IOUtils.write(converted, fos); 286 | fos.flush(); 287 | } catch (IOException e) { 288 | e.printStackTrace(); 289 | } 290 | } 291 | 292 | private static List> toPages(InputStream in, File tempDir) { 293 | Converter converter = new Converter(); 294 | if(!tempDir.exists()) { 295 | tempDir.mkdirs(); 296 | } 297 | List> ret = new ArrayList<>(); 298 | for(Map.Entry kv : converter.toJava(converter.convert(in, tempDir))) { 299 | ret.add(new AbstractMap.SimpleEntry<>(kv.getKey(), kv.getValue())); 300 | } 301 | return ret; 302 | } 303 | } 304 | -------------------------------------------------------------------------------- /common/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | ocr 7 | ocr 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | common 13 | 14 | 15 | -------------------------------------------------------------------------------- /common/src/main/java/ocr/common/Util.java: -------------------------------------------------------------------------------- 1 | package ocr.common; 2 | 3 | import java.io.File; 4 | import java.util.Optional; 5 | import java.util.function.Function; 6 | 7 | public class Util { 8 | public enum Locations { 9 | CONVERT(new String[]{ 10 | "/usr/local/bin/convert", 11 | "/opt/local/bin/convert" 12 | }, t -> findFile(t, "convert tool")), 13 | TESSDATA(new String[]{ 14 | "/opt/local/share/tessdata/", 15 | "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/" 16 | }, t -> findFile(t, "tessdata")), 17 | JNA(new String[]{ 18 | "/opt/local/lib" 19 | }, t -> findDir(t, "jna library")); 20 | 21 | private final String[] locs; 22 | private final Function> searchHandler; 23 | 24 | Locations(String[] locs, Function> searchHandler) { 25 | this.locs = locs; 26 | this.searchHandler = searchHandler; 27 | } 28 | 29 | public Optional find() { 30 | return searchHandler.apply(locs); 31 | } 32 | 33 | public Optional find(Optional path) { 34 | if (path.isPresent()) { 35 | File f = new File(path.get().toString()); 36 | if (f.exists()) { 37 | return Optional.of(f); 38 | } 39 | } 40 | return find(); 41 | } 42 | } 43 | 44 | public static Optional findFile(String[] locs, String item) { 45 | return findFile(locs, item, false); 46 | } 47 | 48 | public static Optional findDir(String[] locs, String item) { 49 | return findFile(locs, item, true); 50 | } 51 | 52 | public static Optional findFile(String[] locs, String item, boolean checkIsDir) { 53 | for (String loc : locs) { 54 | File binPath = new File(loc); 55 | if (binPath.exists()) { 56 | if (checkIsDir) { 57 | if (binPath.isDirectory()) { 58 | return Optional.of(binPath); 59 | } 60 | continue; 61 | } 62 | return Optional.of(binPath); 63 | } 64 | } 65 | return Optional.empty(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /conversion/README.md: -------------------------------------------------------------------------------- 1 | # Conversion 2 | 3 | Convert images from PDF to an image format 4 | 5 | #### Requirements 6 | 7 | Must have Ghostscript installed 8 | 9 | Example on Mac 10 | 11 | ```bash 12 | sudo port install ghostscript 13 | ``` 14 | 15 | #### Running project from command line 16 | 17 | Note: On Mac you will need to specify the jna native library path as the Maven jar's for Ghostscript do not contain the required binary dependencies. 18 | More details can be found in this [Stack Overflow response](http://stackoverflow.com/a/36533605/2163229) 19 | 20 | ```bash 21 | $ mvn exec:java -Dexec.mainClass="ocr.conversion.Convert" -Dexec.args="file-location" 22 | 23 | or, including custom jna path 24 | 25 | $ mvn -Djna.library.path=/opt/local/lib/ exec:java -Dexec.mainClass="ocr.conversion.Convert" -Dexec.args="file-location" 26 | ``` 27 | 28 | **Reference** 29 | 30 | * [Ghost4j](http://www.ghost4j.org/) 31 | -------------------------------------------------------------------------------- /conversion/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | ocr 9 | ocr 10 | 1.0-SNAPSHOT 11 | 12 | 13 | conversion 14 | conversion 15 | 16 | 17 | 18 | geotoolkit 19 | Geotk repository 20 | http://maven.geotoolkit.org 21 | 22 | 23 | 24 | 25 | 26 | 27 | 1.0.1 28 | 1.46 29 | 30 | 31 | 32 | 33 | org.bouncycastle 34 | bcprov-jdk15on 35 | ${bouncycastle.version} 36 | 37 | 38 | org.bouncycastle 39 | bcmail-jdk15on 40 | ${bouncycastle.version} 41 | 42 | 43 | org.geotoolkit 44 | geotk-coverageio 45 | 3.17 46 | 47 | 48 | org.scala-lang 49 | scala-library 50 | 51 | 52 | org.scalactic 53 | scalactic_${scala.binary.version} 54 | 55 | 56 | org.scalatest 57 | scalatest_${scala.binary.version} 58 | 59 | 60 | org.ghost4j 61 | ghost4j 62 | ${ghost4j.version} 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | net.alchim31.maven 71 | scala-maven-plugin 72 | 73 | 74 | 75 | org.apache.maven.plugins 76 | maven-surefire-plugin 77 | 78 | true 79 | 80 | 81 | 82 | 83 | org.scalatest 84 | scalatest-maven-plugin 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | net.alchim31.maven 93 | scala-maven-plugin 94 | 95 | 96 | 97 | doc-jar 98 | doc 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /conversion/src/main/java/ocr/conversion/AlmostSimpleRenderer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ghost4J: a Java wrapper for Ghostscript API. 3 | * 4 | * Distributable under LGPL license. 5 | * See terms of license at http://www.gnu.org/licenses/lgpl.html. 6 | */ 7 | package ocr.conversion; 8 | 9 | import org.ghost4j.Ghostscript; 10 | import org.ghost4j.GhostscriptException; 11 | import org.ghost4j.display.PageRaster; 12 | import org.ghost4j.display.PageRasterDisplayCallback; 13 | import org.ghost4j.document.Document; 14 | import org.ghost4j.document.DocumentException; 15 | import org.ghost4j.document.PDFDocument; 16 | import org.ghost4j.document.PSDocument; 17 | import org.ghost4j.renderer.AbstractRemoteRenderer; 18 | import org.ghost4j.renderer.RendererException; 19 | import org.ghost4j.util.DiskStore; 20 | 21 | import java.io.IOException; 22 | import java.util.Arrays; 23 | import java.util.List; 24 | 25 | public class AlmostSimpleRenderer extends AbstractRemoteRenderer { 26 | 27 | public static final int OPTION_ANTIALIASING_NONE = 0; 28 | public static final int OPTION_ANTIALIASING_LOW = 1; 29 | public static final int OPTION_ANTIALIASING_MEDIUM = 2; 30 | public static final int OPTION_ANTIALIASING_HIGH = 4; 31 | 32 | /** 33 | * Define subsample antialiasing level (default is high). 34 | */ 35 | private int antialiasing = OPTION_ANTIALIASING_HIGH; 36 | 37 | /** 38 | * Define renderer output resolution in DPI (default is 75dpi). 39 | */ 40 | private int resolution = 75; 41 | 42 | public AlmostSimpleRenderer() { 43 | 44 | // set supported classes 45 | supportedDocumentClasses = new Class[2]; 46 | supportedDocumentClasses[0] = PDFDocument.class; 47 | supportedDocumentClasses[1] = PSDocument.class; 48 | } 49 | 50 | /** 51 | * Main method used to start the renderer in standalone 'slave mode'. 52 | * 53 | * @param args 54 | * @throws RendererException 55 | */ 56 | public static void main(String[] args) throws RendererException { 57 | 58 | startRemoteRenderer(new org.ghost4j.renderer.SimpleRenderer()); 59 | } 60 | 61 | @Override 62 | public List run(Document document, int begin, int end) 63 | throws IOException, RendererException, DocumentException { 64 | 65 | // assert document is supported 66 | this.assertDocumentSupported(document); 67 | 68 | // get Ghostscript instance 69 | Ghostscript gs = Ghostscript.getInstance(); 70 | 71 | // generate a unique diskstore key for input file 72 | DiskStore diskStore = DiskStore.getInstance(); 73 | String inputDiskStoreKey = diskStore.generateUniqueKey(); 74 | // write document to input file 75 | document.write(diskStore.addFile(inputDiskStoreKey)); 76 | 77 | // create display callback 78 | PageRasterDisplayCallback displayCallback = new PageRasterDisplayCallback(); 79 | 80 | // prepare args 81 | // ** ADDED REDIRECTION OF OUTPUT TO SILENCE LOG NOISE ** 82 | String[] gsArgs = {"-sstdout=%stderr", "-dQUIET", "-dNOPAUSE", "-dBATCH", "-dSAFER", 83 | "-dFirstPage=" + (begin + 1), "-dLastPage=" + (end + 1), 84 | "-sDEVICE=display", "-sDisplayHandle=0", 85 | "-dDisplayFormat=16#804", "-r" + this.getResolution()}; 86 | 87 | // antialiasing 88 | if (this.antialiasing != OPTION_ANTIALIASING_NONE) { 89 | gsArgs = Arrays.copyOf(gsArgs, gsArgs.length + 2); 90 | gsArgs[gsArgs.length - 2] = "-dTextAlphaBits=" + this.antialiasing; 91 | gsArgs[gsArgs.length - 1] = "-dGraphicsAlphaBits=" 92 | + this.antialiasing; 93 | } 94 | 95 | // add file path args 96 | gsArgs = Arrays.copyOf(gsArgs, gsArgs.length + 2); 97 | gsArgs[gsArgs.length - 2] = "-f"; 98 | gsArgs[gsArgs.length - 1] = diskStore.getFile(inputDiskStoreKey).getAbsolutePath(); 99 | 100 | // execute and exit interpreter 101 | try { 102 | synchronized (gs) { 103 | 104 | // set display callback 105 | gs.setDisplayCallback(displayCallback); 106 | 107 | gs.initialize(gsArgs); 108 | gs.exit(); 109 | 110 | } 111 | } catch (GhostscriptException e) { 112 | 113 | throw new RendererException(e); 114 | 115 | } finally { 116 | 117 | // delete Ghostscript instance 118 | try { 119 | Ghostscript.deleteInstance(); 120 | } catch (GhostscriptException e) { 121 | throw new RendererException(e); 122 | } 123 | 124 | // remove temporary file 125 | diskStore.removeFile(inputDiskStoreKey); 126 | } 127 | 128 | return displayCallback.getRasters(); 129 | 130 | } 131 | 132 | public int getAntialiasing() { 133 | return antialiasing; 134 | } 135 | 136 | public void setAntialiasing(int antialiasing) { 137 | this.antialiasing = antialiasing; 138 | } 139 | 140 | public int getResolution() { 141 | return resolution; 142 | } 143 | 144 | public void setResolution(int resolution) { 145 | this.resolution = resolution; 146 | } 147 | } 148 | 149 | -------------------------------------------------------------------------------- /conversion/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Set root logger level to DEBUG and its only appender to STDOUT. 2 | log4j.rootLogger=INFO, STDOUT 3 | 4 | # STDOUT is set to be a ConsoleAppender. 5 | log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender 6 | 7 | # STDOUT uses PatternLayout. 8 | log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout 9 | log4j.appender.STDOUT.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m %C%n 10 | -------------------------------------------------------------------------------- /conversion/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /conversion/src/main/scala/ocr/conversion/ConfigOptions.scala: -------------------------------------------------------------------------------- 1 | package ocr.conversion 2 | 3 | import java.io.File 4 | 5 | class ConfigOptions(pdf: File, outDir: File, jnaLibPath: Option[String]) { 6 | def getPdfFile() = pdf 7 | 8 | def getOutDir() = outDir 9 | 10 | def getJnaLibPath = jnaLibPath 11 | } 12 | -------------------------------------------------------------------------------- /conversion/src/main/scala/ocr/conversion/Converter.scala: -------------------------------------------------------------------------------- 1 | package ocr.conversion 2 | 3 | import java.awt.image.RenderedImage 4 | import java.io.{File, FileInputStream, InputStream} 5 | import java.util.UUID 6 | import javax.imageio.ImageIO 7 | import javax.imageio.spi.IIORegistry 8 | 9 | import com.google.common.base.Splitter 10 | import com.google.common.collect.Iterables 11 | import org.apache.commons.io.IOUtils 12 | import org.geotoolkit.image.io.plugin.RawTiffImageReader 13 | import org.ghost4j.document.PDFDocument 14 | 15 | import scala.collection.JavaConversions._ 16 | 17 | class Converter { 18 | 19 | object StaticConfig { 20 | IIORegistry.getDefaultInstance() 21 | .registerServiceProvider(new RawTiffImageReader.Spi()); 22 | } 23 | 24 | def convert(in: InputStream, outDir: File): List[Tuple2[File, Boolean]] = { 25 | val document = new PDFDocument() 26 | document.load(IOUtils.toBufferedInputStream(in)) 27 | 28 | val renderer: AlmostSimpleRenderer = new AlmostSimpleRenderer() 29 | renderer.setResolution(300) 30 | val images = renderer.render(document) 31 | val uuid = UUID.randomUUID().toString 32 | images.toList 33 | .zipWithIndex.map { 34 | case (img, i) => { 35 | val outFile = new File(outDir, uuid + "-" + i + ".tiff"); 36 | Tuple2(outFile, ImageIO.write(img.asInstanceOf[RenderedImage], "tif", outFile)) 37 | } 38 | } 39 | } 40 | 41 | def convert(config: ConfigOptions): List[File] = { 42 | config.getOutDir().mkdirs() 43 | convert(new FileInputStream(config.getPdfFile()), config.getOutDir()) 44 | .map { 45 | case (f, b) => f 46 | } 47 | } 48 | 49 | def toJava(in: List[Tuple2[File, Boolean]]): java.util.List[java.util.Map.Entry[java.io.File, java.lang.Boolean]] = { 50 | val ret = new java.util.ArrayList[java.util.Map.Entry[java.io.File, java.lang.Boolean]] 51 | in.foreach { 52 | case (f, b) => ret.add(new java.util.AbstractMap.SimpleEntry[java.io.File, java.lang.Boolean](f, b)) 53 | } 54 | ret 55 | } 56 | 57 | def getPageNumber(fileName: String): Integer = { 58 | val it = Splitter.on(".tiff").split(fileName); 59 | val first = Iterables.getFirst(it, null); 60 | Integer.parseInt(Iterables.getLast(Splitter.on("-").split(first))); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /conversion/src/main/scala/ocr/conversion/Driver.scala: -------------------------------------------------------------------------------- 1 | package ocr.conversion 2 | 3 | import java.io.File 4 | 5 | import scala.collection.JavaConversions._ 6 | 7 | object Driver { 8 | 9 | val usage = 10 | """ 11 | |Usage: convert pdfFile outDir [jnaLibPath] 12 | """.stripMargin 13 | 14 | /** 15 | * Convert each page of PDF to TIFF file 16 | * 17 | * @param args 18 | */ 19 | def main(args: Array[String]): Unit = { 20 | run(args) 21 | } 22 | 23 | def run(args: Array[String]): List[File] = { 24 | val config: ConfigOptions = buildConfig(args) 25 | setupJnaLibPath(config) 26 | setupOutputLocation(config) 27 | val converter = new Converter 28 | converter.convert(config) 29 | } 30 | 31 | def setupOutputLocation(config: ConfigOptions): Unit = { 32 | config.getOutDir().mkdirs() 33 | } 34 | 35 | def buildConfig(args: Array[String]): ConfigOptions = { 36 | if (args.length < 2) { 37 | println("Incorrect arguments: \n" + usage) 38 | System.exit(1) 39 | } 40 | val argsList = args.toList 41 | 42 | val config = new ConfigOptions(new File(argsList.get(0)), new File(argsList.get(1)), getJnaLibPath(argsList)) 43 | config 44 | } 45 | 46 | def setupJnaLibPath(config: ConfigOptions): Any = { 47 | config.getJnaLibPath match { 48 | case Some(s) => System.getProperties.setProperty("jna.library.path", s) 49 | case None => println("No jna lib path set") 50 | } 51 | } 52 | 53 | def getJnaLibPath(argsList: List[String]): Option[String] = { 54 | if (argsList.isDefinedAt(3)) { 55 | return Some(argsList.get(3)) 56 | } else if (System.getProperty("os.name").toLowerCase.contains("mac os x")) { 57 | return Some("/opt/local/lib/") 58 | } else { 59 | return None 60 | } 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /conversion/src/test/resources/text-detection.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmiklavc/scalable-ocr/9c9e42c4844799c860a3cf344a2d0eb218a6d438/conversion/src/test/resources/text-detection.pdf -------------------------------------------------------------------------------- /conversion/src/test/scala/ocr/conversion/ConverterSpec.scala: -------------------------------------------------------------------------------- 1 | package ocr.conversion 2 | 3 | import java.io.File 4 | import javax.imageio.ImageIO 5 | 6 | import org.apache.commons.io.FileUtils 7 | import org.scalatest.{BeforeAndAfter, FlatSpec, Matchers} 8 | 9 | class ConverterSpec extends FlatSpec with Matchers with BeforeAndAfter { 10 | 11 | val outDir = new File("target/converter-output") 12 | 13 | before { 14 | FileUtils.deleteDirectory(outDir) 15 | } 16 | 17 | "converter" should "put 2 files in destination directory" in { 18 | val samplePDF = "target/test-classes/text-detection.pdf" 19 | val outFiles = Driver.run(Array(samplePDF, outDir.getAbsolutePath)) 20 | outDir.exists() shouldBe true 21 | outDir.listFiles().length shouldBe outFiles.length 22 | outDir.listFiles().length shouldBe 2 23 | outDir.listFiles.map(f => f.getName).toSet shouldBe outFiles.map(f => f.getName).toSet 24 | outFiles.map( f => ImageIO.read(f)).foreach( bi => bi.getHeight > 0 && bi.getWidth > 0 shouldBe true) 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /extraction/README.md: -------------------------------------------------------------------------------- 1 | # Extraction 2 | 3 | Dependencies: 4 | 5 | - Install Tesseract using Homebrew or MacPorts 6 | 7 | -------------------------------------------------------------------------------- /extraction/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | ocr 9 | ocr 10 | 1.0-SNAPSHOT 11 | 12 | 13 | extraction 14 | extraction 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | ocr 25 | common 26 | 1.0-SNAPSHOT 27 | 28 | 29 | net.sourceforge.tess4j 30 | tess4j 31 | 3.2.1 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /extraction/src/main/java/ocr/extraction/tesseract/TesseractUtil.java: -------------------------------------------------------------------------------- 1 | package ocr.extraction.tesseract; 2 | 3 | import net.sourceforge.tess4j.Tesseract; 4 | import net.sourceforge.tess4j.TesseractException; 5 | import org.apache.commons.io.IOUtils; 6 | 7 | import javax.imageio.ImageIO; 8 | import java.awt.image.BufferedImage; 9 | import java.io.ByteArrayInputStream; 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.util.Map; 14 | 15 | public enum TesseractUtil { 16 | INSTANCE; 17 | 18 | public String ocr(byte[] img, File dataPath) throws IOException, TesseractException { 19 | return ocr(new ByteArrayInputStream(img), dataPath); 20 | } 21 | 22 | public String ocr(InputStream is, File dataPath) throws IOException, TesseractException { 23 | Tesseract instance = new Tesseract(); 24 | instance.setDatapath(dataPath.getPath()); 25 | BufferedImage bi = ImageIO.read(IOUtils.toBufferedInputStream(is)); 26 | return instance.doOCR(bi); 27 | } 28 | 29 | public String ocr(byte[] img, File dataPath, Map variables) throws IOException, TesseractException { 30 | return ocr(new ByteArrayInputStream(img), dataPath, variables); 31 | } 32 | 33 | public String ocr(InputStream is, File dataPath, Map variables) throws IOException, TesseractException { 34 | Tesseract instance = new Tesseract(); 35 | for (Map.Entry kv : variables.entrySet()) { 36 | instance.setTessVariable(kv.getKey(), kv.getValue()); 37 | } 38 | instance.setDatapath(dataPath.getPath()); 39 | BufferedImage bi = ImageIO.read(IOUtils.toBufferedInputStream(is)); 40 | return instance.doOCR(bi); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /extraction/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Set root logger level to DEBUG and its only appender to STDOUT. 2 | log4j.rootLogger=INFO, STDOUT 3 | 4 | # STDOUT is set to be a ConsoleAppender. 5 | log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender 6 | 7 | # STDOUT uses PatternLayout. 8 | log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout 9 | log4j.appender.STDOUT.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m %C%n 10 | -------------------------------------------------------------------------------- /extraction/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /extraction/src/test/java/ocr/extraction/tesseract/TesseractUtilTest.java: -------------------------------------------------------------------------------- 1 | package ocr.extraction.tesseract; 2 | 3 | import ocr.common.Util; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | 7 | import java.io.File; 8 | import java.nio.file.Files; 9 | import java.util.HashMap; 10 | 11 | public class TesseractUtilTest { 12 | 13 | @Test 14 | public void testTesseractHappyPath() throws Exception { 15 | System.getProperties().setProperty("jna.library.path", Util.Locations.JNA.find().get().getAbsolutePath()); 16 | File inFile = new File("src/test/resources/pdf-test.tiff"); 17 | File txtFile = new File("src/test/resources/pdf-test.txt"); 18 | String text = TesseractUtil.INSTANCE.ocr(Files.readAllBytes(inFile.toPath()), Util.Locations.TESSDATA.find().get(), new HashMap<>()); 19 | Assert.assertTrue(text.contains("Congratulations, your computer is equipped with a PDF (Portable Document Format)\nreader!")); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /extraction/src/test/resources/pdf-test.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmiklavc/scalable-ocr/9c9e42c4844799c860a3cf344a2d0eb218a6d438/extraction/src/test/resources/pdf-test.tiff -------------------------------------------------------------------------------- /nifi/README.md: -------------------------------------------------------------------------------- 1 | # NiFi 2 | 3 | -------------------------------------------------------------------------------- /nifi/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | ocr 9 | ocr 10 | 1.0-SNAPSHOT 11 | 12 | 13 | nifi 14 | nifi 15 | nar 16 | 17 | 18 | 19 | 1.1.0 20 | 21 | 22 | 0.6.1 23 | 24 | 25 | 26 | 27 | ocr 28 | common 29 | 1.0-SNAPSHOT 30 | 31 | 32 | ocr 33 | conversion 34 | ${project.parent.version} 35 | 36 | 37 | ocr 38 | extraction 39 | ${project.parent.version} 40 | 41 | 42 | ocr 43 | preprocessing 44 | ${project.parent.version} 45 | 46 | 47 | org.apache.nifi 48 | nifi-api 49 | ${nifi.version} 50 | 51 | 52 | org.apache.nifi 53 | nifi-utils 54 | ${nifi.version} 55 | 56 | 57 | org.apache.nifi 58 | nifi-processor-utils 59 | ${nifi.version} 60 | 61 | 62 | org.apache.nifi 63 | nifi-mock 64 | ${nifi.version} 65 | test 66 | 67 | 68 | com.fasterxml.jackson.core 69 | jackson-databind 70 | 2.7.4 71 | 72 | 73 | 74 | 75 | 76 | 77 | org.apache.nifi 78 | nifi-nar-maven-plugin 79 | ${nifi.nar.version} 80 | true 81 | 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /nifi/src/main/java/ocr/nifi/conversion/ConversionProcessor.java: -------------------------------------------------------------------------------- 1 | package ocr.nifi.conversion; 2 | 3 | import com.google.common.base.Splitter; 4 | import com.google.common.collect.ImmutableList; 5 | import com.google.common.collect.ImmutableSet; 6 | import com.google.common.collect.Iterables; 7 | import ocr.conversion.Converter; 8 | import org.apache.commons.io.IOUtils; 9 | import org.apache.nifi.annotation.behavior.SideEffectFree; 10 | import org.apache.nifi.annotation.documentation.CapabilityDescription; 11 | import org.apache.nifi.annotation.documentation.Tags; 12 | import org.apache.nifi.components.PropertyDescriptor; 13 | import org.apache.nifi.flowfile.FlowFile; 14 | import org.apache.nifi.logging.ProcessorLog; 15 | import org.apache.nifi.processor.AbstractProcessor; 16 | import org.apache.nifi.processor.ProcessContext; 17 | import org.apache.nifi.processor.ProcessSession; 18 | import org.apache.nifi.processor.Relationship; 19 | import org.apache.nifi.processor.exception.ProcessException; 20 | import org.apache.nifi.processor.util.StandardValidators; 21 | 22 | import java.io.BufferedInputStream; 23 | import java.io.File; 24 | import java.io.FileInputStream; 25 | import java.io.InputStream; 26 | import java.util.*; 27 | import java.util.concurrent.atomic.AtomicReference; 28 | 29 | @SideEffectFree 30 | @Tags({"ocr preprocessing", "image manipulation"}) 31 | @CapabilityDescription("Preprocess images of text documents extract pages and data") 32 | public class ConversionProcessor extends AbstractProcessor { 33 | static PropertyDescriptor JNI_PATH = new PropertyDescriptor.Builder() 34 | .name("jni_path") 35 | .description("JNI Path") 36 | .required(true) 37 | .addValidator(StandardValidators.FILE_EXISTS_VALIDATOR) 38 | .build(); 39 | static PropertyDescriptor TEMP_DIR = new PropertyDescriptor.Builder() 40 | .name("temp_space") 41 | .description("Temporary directory to be used.") 42 | .required(false) 43 | .addValidator(StandardValidators.FILE_EXISTS_VALIDATOR) 44 | .build(); 45 | static Relationship SUCCESS = new Relationship.Builder() 46 | .name("SUCCESS") 47 | .description("Success relationship") 48 | .build(); 49 | static Relationship RAW = new Relationship.Builder() 50 | .name("RAW") 51 | .description("Raw data") 52 | .build(); 53 | private List properties = ImmutableList.of(TEMP_DIR, JNI_PATH); 54 | 55 | private Set relationships = ImmutableSet.of( SUCCESS, RAW ); 56 | @Override 57 | public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { 58 | final ProcessorLog log = this.getLogger(); 59 | final AtomicReference>> value = new AtomicReference<>(); 60 | final File tempDir = new File(context.getProperty(TEMP_DIR).getValue()); 61 | System.getProperties().setProperty("jna.library.path", context.getProperty(JNI_PATH).getValue()); 62 | FlowFile flowfile = session.get(); 63 | session.read(flowfile, in -> { 64 | try { 65 | value.set(convert(in, tempDir)); 66 | } 67 | catch(Exception e) { 68 | log.error("Unable to convert: " + e.getMessage(), e); 69 | } 70 | }); 71 | if(value.get() != null) { 72 | for(Map.Entry kv : value.get()) { 73 | final File convertedFile = kv.getKey(); 74 | try { 75 | final int pageNumber = getPageNumber(convertedFile.getName()); 76 | if(kv.getValue()) { 77 | FlowFile ff = session.clone(flowfile); 78 | ff = session.putAttribute(ff, "pageNumber", "" + pageNumber); 79 | ff = session.write(ff, out -> IOUtils.copy(new BufferedInputStream(new FileInputStream(convertedFile)), out)); 80 | session.transfer(ff, SUCCESS); 81 | } 82 | } 83 | finally { 84 | if(convertedFile != null && convertedFile.exists()) { 85 | convertedFile.delete(); 86 | } 87 | } 88 | } 89 | } 90 | session.transfer(flowfile, RAW); 91 | } 92 | 93 | private int getPageNumber(String fileName) { 94 | Iterable it = Splitter.on(".tiff").split(fileName); 95 | String first = Iterables.getFirst(it, null); 96 | return Integer.parseInt(Iterables.getLast(Splitter.on("-").split(first))); 97 | } 98 | private List> convert(InputStream in, File tempDir) { 99 | Converter converter = new Converter(); 100 | if(!tempDir.exists()) { 101 | tempDir.mkdirs(); 102 | } 103 | List> ret = new ArrayList<>(); 104 | for(Map.Entry kv : converter.toJava(converter.convert(in, tempDir))) { 105 | ret.add(new AbstractMap.SimpleEntry<>(kv.getKey(), kv.getValue())); 106 | } 107 | return ret; 108 | } 109 | 110 | @Override 111 | public Set getRelationships() { 112 | return relationships; 113 | } 114 | 115 | @Override 116 | protected List getSupportedPropertyDescriptors() { 117 | return properties; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /nifi/src/main/java/ocr/nifi/extraction/ExtractionProcessor.java: -------------------------------------------------------------------------------- 1 | package ocr.nifi.extraction; 2 | 3 | import com.fasterxml.jackson.core.type.TypeReference; 4 | import com.google.common.collect.ImmutableList; 5 | import com.google.common.collect.ImmutableSet; 6 | import ocr.extraction.tesseract.TesseractUtil; 7 | import ocr.nifi.util.JSONUtils; 8 | import ocr.nifi.validation.Validation; 9 | import org.apache.nifi.annotation.behavior.SideEffectFree; 10 | import org.apache.nifi.annotation.documentation.CapabilityDescription; 11 | import org.apache.nifi.annotation.documentation.Tags; 12 | import org.apache.nifi.components.PropertyDescriptor; 13 | import org.apache.nifi.flowfile.FlowFile; 14 | import org.apache.nifi.logging.ProcessorLog; 15 | import org.apache.nifi.processor.AbstractProcessor; 16 | import org.apache.nifi.processor.ProcessContext; 17 | import org.apache.nifi.processor.ProcessSession; 18 | import org.apache.nifi.processor.Relationship; 19 | import org.apache.nifi.processor.exception.ProcessException; 20 | import org.apache.nifi.processor.util.StandardValidators; 21 | 22 | import java.io.File; 23 | import java.util.HashMap; 24 | import java.util.List; 25 | import java.util.Map; 26 | import java.util.Set; 27 | import java.util.concurrent.atomic.AtomicReference; 28 | @SideEffectFree 29 | @Tags({"ocr"}) 30 | @CapabilityDescription("Extracts text from images") 31 | public class ExtractionProcessor extends AbstractProcessor { 32 | static PropertyDescriptor JNI_PATH = new PropertyDescriptor.Builder() 33 | .name("jni_path") 34 | .description("JNI Path") 35 | .required(true) 36 | .addValidator(StandardValidators.FILE_EXISTS_VALIDATOR) 37 | .build(); 38 | static PropertyDescriptor TESS_DATA = new PropertyDescriptor.Builder() 39 | .name("tess_data_dir") 40 | .description("Tesseract data directory") 41 | .required(true) 42 | .addValidator(StandardValidators.FILE_EXISTS_VALIDATOR) 43 | .build(); 44 | static PropertyDescriptor TESS_PROPERTIES = new PropertyDescriptor.Builder() 45 | .name("tess_properties") 46 | .description("Tesseract properties") 47 | .required(false) 48 | .addValidator(Validation.Validators.JSON_MAP) 49 | .build(); 50 | static Relationship SUCCESS = new Relationship.Builder() 51 | .name("SUCCESS") 52 | .description("Success relationship") 53 | .build(); 54 | private List properties = ImmutableList.of(TESS_DATA, JNI_PATH, TESS_PROPERTIES); 55 | 56 | private Set relationships = ImmutableSet.of( SUCCESS ); 57 | 58 | private Map toProperties(String properties) throws ProcessException { 59 | Map ret = new HashMap<>(); 60 | if(properties == null) { 61 | return ret; 62 | } 63 | else { 64 | try { 65 | return JSONUtils.INSTANCE.load(properties, new TypeReference>() { 66 | }); 67 | } 68 | catch(Throwable t) { 69 | throw new ProcessException("Unable to load properties: " + t.getMessage(), t); 70 | } 71 | } 72 | } 73 | 74 | @Override 75 | public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { 76 | final ProcessorLog log = this.getLogger(); 77 | final AtomicReference value = new AtomicReference<>(); 78 | final Map tessProperties = toProperties(context.getProperty(TESS_PROPERTIES).getValue()); 79 | final File tessDataDir = new File(context.getProperty(TESS_DATA).getValue()); 80 | System.getProperties().setProperty("jna.library.path", context.getProperty(JNI_PATH).getValue()); 81 | FlowFile flowfile = session.get(); 82 | if (null != flowfile) { 83 | session.read(flowfile, in -> { 84 | try { 85 | value.set(TesseractUtil.INSTANCE.ocr(in, tessDataDir, tessProperties)); 86 | } catch (Exception e) { 87 | log.error("Unable to ocr: " + e.getMessage(), e); 88 | } 89 | }); 90 | 91 | flowfile = session.write(flowfile, out -> { 92 | out.write(value.get().getBytes()); 93 | out.flush(); 94 | }); 95 | session.transfer(flowfile, SUCCESS); 96 | } else { 97 | log.warn("NULL flow file"); 98 | } 99 | } 100 | 101 | @Override 102 | public Set getRelationships() { 103 | return relationships; 104 | } 105 | 106 | @Override 107 | protected List getSupportedPropertyDescriptors() { 108 | return properties; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /nifi/src/main/java/ocr/nifi/preprocessing/PreprocessingProcessor.java: -------------------------------------------------------------------------------- 1 | package ocr.nifi.preprocessing; 2 | 3 | import com.google.common.collect.ImmutableList; 4 | import com.google.common.collect.ImmutableSet; 5 | import ocr.preprocessing.conversion.CLIUtils; 6 | import ocr.preprocessing.conversion.CleaningOptions; 7 | import ocr.preprocessing.conversion.TextCleaner; 8 | import org.apache.commons.cli.CommandLine; 9 | import org.apache.commons.cli.DefaultParser; 10 | import org.apache.commons.io.IOUtils; 11 | import org.apache.nifi.annotation.behavior.SideEffectFree; 12 | import org.apache.nifi.annotation.documentation.CapabilityDescription; 13 | import org.apache.nifi.annotation.documentation.Tags; 14 | import org.apache.nifi.components.PropertyDescriptor; 15 | import org.apache.nifi.components.ValidationResult; 16 | import org.apache.nifi.flowfile.FlowFile; 17 | import org.apache.nifi.logging.ProcessorLog; 18 | import org.apache.nifi.processor.*; 19 | import org.apache.nifi.processor.exception.ProcessException; 20 | import org.apache.nifi.processor.util.StandardValidators; 21 | 22 | import java.util.List; 23 | import java.util.Set; 24 | import java.util.concurrent.atomic.AtomicReference; 25 | 26 | @SideEffectFree 27 | @Tags({"ocr preprocessing", "image manipulation"}) 28 | @CapabilityDescription("Preprocess images of text documents to clean them") 29 | public class PreprocessingProcessor extends AbstractProcessor { 30 | static PropertyDescriptor DEFINITIONS = new PropertyDescriptor.Builder() 31 | .name("definition") 32 | .description(CleaningOptions.getUsage()) 33 | .required(true) 34 | .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) 35 | .addValidator( 36 | (subject, value, context) -> { 37 | boolean valid = true; 38 | String explanation = ""; 39 | try { 40 | CleaningOptions.parse(new DefaultParser() 41 | , CLIUtils.translateCommandline(value) 42 | ); 43 | } 44 | catch(Throwable t) { 45 | valid = false; 46 | explanation = t.getMessage(); 47 | } 48 | return 49 | new ValidationResult.Builder() 50 | .subject(subject) 51 | .input(value) 52 | .valid(valid) 53 | .explanation(explanation) 54 | .build(); 55 | } 56 | ) 57 | .build(); 58 | static PropertyDescriptor TEMP_DIR = new PropertyDescriptor.Builder() 59 | .name("temp_space") 60 | .description("Temporary directory to be used.") 61 | .required(false) 62 | .addValidator(StandardValidators.FILE_EXISTS_VALIDATOR) 63 | .build(); 64 | static PropertyDescriptor CONVERT_PATH = new PropertyDescriptor.Builder() 65 | .name("convert_bin_path") 66 | .description("The path to the convert (imagemagick) utility") 67 | .required(true) 68 | .addValidator(StandardValidators.FILE_EXISTS_VALIDATOR) 69 | .build(); 70 | static Relationship SUCCESS = new Relationship.Builder() 71 | .name("SUCCESS") 72 | .description("Success relationship") 73 | .build(); 74 | private List properties = ImmutableList.of( DEFINITIONS ,TEMP_DIR, CONVERT_PATH ); 75 | 76 | private Set relationships = ImmutableSet.of( SUCCESS ); 77 | 78 | @Override 79 | protected void init(ProcessorInitializationContext context) { 80 | } 81 | 82 | @Override 83 | public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { 84 | final ProcessorLog log = this.getLogger(); 85 | final AtomicReference value = new AtomicReference<>(); 86 | String preprocessingDef = context.getProperty(DEFINITIONS).getValue(); 87 | String tempDir = context.getProperty(TEMP_DIR).getValue(); 88 | String convertPath = context.getProperty(CONVERT_PATH).getValue(); 89 | CommandLine cli = CleaningOptions.parse(new DefaultParser(), CLIUtils.translateCommandline(preprocessingDef) ); 90 | final TextCleaner cleaner = CleaningOptions.createTextCleaner(cli, convertPath, tempDir); 91 | FlowFile flowfile = session.get(); 92 | session.read(flowfile, in -> { 93 | try { 94 | value.set(cleaner.convert(in)); 95 | } catch (Exception e) { 96 | value.set(IOUtils.toByteArray(in)); 97 | log.error("Unable to execute command: " + e.getMessage(), e); 98 | } 99 | }); 100 | flowfile = session.write(flowfile, out -> { 101 | out.write(value.get()); 102 | out.flush(); 103 | }); 104 | session.transfer(flowfile, SUCCESS); 105 | } 106 | 107 | @Override 108 | public Set getRelationships() { 109 | return relationships; 110 | } 111 | 112 | @Override 113 | protected List getSupportedPropertyDescriptors() { 114 | return properties; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /nifi/src/main/java/ocr/nifi/util/JSONUtils.java: -------------------------------------------------------------------------------- 1 | package ocr.nifi.util; 2 | import com.fasterxml.jackson.core.JsonProcessingException; 3 | import com.fasterxml.jackson.core.type.TypeReference; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import java.io.*; 7 | 8 | public enum JSONUtils { 9 | INSTANCE; 10 | private static ThreadLocal _mapper = new ThreadLocal() { 11 | /** 12 | * Returns the current thread's "initial value" for this 13 | * thread-local variable. This method will be invoked the first 14 | * time a thread accesses the variable with the {@link #get} 15 | * method, unless the thread previously invoked the {@link #set} 16 | * method, in which case the {@code initialValue} method will not 17 | * be invoked for the thread. Normally, this method is invoked at 18 | * most once per thread, but it may be invoked again in case of 19 | * subsequent invocations of {@link #remove} followed by {@link #get}. 20 | *

21 | *

This implementation simply returns {@code null}; if the 22 | * programmer desires thread-local variables to have an initial 23 | * value other than {@code null}, {@code ThreadLocal} must be 24 | * subclassed, and this method overridden. Typically, an 25 | * anonymous inner class will be used. 26 | * 27 | * @return the initial value for this thread-local 28 | */ 29 | @Override 30 | protected ObjectMapper initialValue() { 31 | return new ObjectMapper(); 32 | } 33 | }; 34 | 35 | public T load(InputStream is, TypeReference ref) throws IOException { 36 | return _mapper.get().readValue(is, ref); 37 | } 38 | 39 | public T load(String is, TypeReference ref) throws IOException { 40 | return _mapper.get().readValue(is, ref); 41 | } 42 | 43 | public T load(File f, TypeReference ref) throws IOException { 44 | try (InputStream is = new BufferedInputStream(new FileInputStream(f))) { 45 | return _mapper.get().readValue(is, ref); 46 | } 47 | } 48 | 49 | public T load(InputStream is, Class clazz) throws IOException { 50 | return _mapper.get().readValue(is, clazz); 51 | } 52 | 53 | public T load(File f, Class clazz) throws IOException { 54 | try (InputStream is = new BufferedInputStream(new FileInputStream(f))) { 55 | return _mapper.get().readValue(is, clazz); 56 | } 57 | } 58 | 59 | public T load(String is, Class clazz) throws IOException { 60 | return _mapper.get().readValue(is, clazz); 61 | } 62 | 63 | public String toJSON(Object o, boolean pretty) throws JsonProcessingException { 64 | if (pretty) { 65 | return _mapper.get().writerWithDefaultPrettyPrinter().writeValueAsString(o); 66 | } else { 67 | return _mapper.get().writeValueAsString(o); 68 | } 69 | } 70 | 71 | public byte[] toJSON(Object config) throws JsonProcessingException { 72 | return _mapper.get().writeValueAsBytes(config); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /nifi/src/main/java/ocr/nifi/validation/JsonValidator.java: -------------------------------------------------------------------------------- 1 | package ocr.nifi.validation; 2 | 3 | import com.fasterxml.jackson.core.type.TypeReference; 4 | import ocr.nifi.util.JSONUtils; 5 | import org.apache.nifi.components.ValidationContext; 6 | import org.apache.nifi.components.ValidationResult; 7 | import org.apache.nifi.components.Validator; 8 | 9 | import java.io.IOException; 10 | import java.util.Map; 11 | 12 | import static com.sun.corba.se.spi.activation.IIOP_CLEAR_TEXT.value; 13 | 14 | public class JsonValidator implements Validator { 15 | @Override 16 | public ValidationResult validate(String subject, String input, ValidationContext context) { 17 | try { 18 | JSONUtils.INSTANCE.load(input, new TypeReference>() { 19 | }); 20 | } catch (IOException e) { 21 | return new ValidationResult.Builder() 22 | .subject(subject) 23 | .input(value) 24 | .valid(false) 25 | .explanation("Not a valid JSON map value: " + e.getMessage()) 26 | .build(); 27 | } 28 | return new ValidationResult.Builder() 29 | .valid(true) 30 | .input(value) 31 | .subject(subject) 32 | .build(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /nifi/src/main/java/ocr/nifi/validation/Validation.java: -------------------------------------------------------------------------------- 1 | package ocr.nifi.validation; 2 | 3 | import org.apache.nifi.components.ValidationContext; 4 | import org.apache.nifi.components.ValidationResult; 5 | import org.apache.nifi.components.Validator; 6 | 7 | public class Validation { 8 | public enum Validators implements Validator { 9 | JSON_MAP(new JsonValidator()); 10 | 11 | private Validator validator; 12 | 13 | Validators(Validator validator) { 14 | this.validator = validator; 15 | } 16 | 17 | @Override 18 | public ValidationResult validate(String subject, String input, ValidationContext context) { 19 | return validator.validate(subject, input, context); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /nifi/src/main/nifi/templates/scalable-ocr.xml: -------------------------------------------------------------------------------- 1 |