├── .github └── workflows │ └── compile.yml ├── .gitmodules ├── INSTALL.md ├── LICENSE ├── PDFExtract.js ├── PDFExtract.json ├── README.md ├── Test ├── pdf-in │ ├── sample.pdf │ ├── sample2.pdf │ ├── sample3.pdf │ └── sample4.pdf ├── run-batch.sh ├── run-single.sh └── sample.tab ├── pom.xml ├── releases ├── sentence-join ├── README.md └── sentence-join.py ├── setup.sh └── src ├── Main.java └── pdfextract ├── Common.java ├── Config.java ├── DetectLanguage.java ├── HTMLObject.java ├── PDFExtract.java ├── PDFToHtml.java ├── SentenceJoin.java ├── StreamGobbler.java └── StreamGobblerWithOutput.java /.github/workflows/compile.yml: -------------------------------------------------------------------------------- 1 | name: Compile and Test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: Install dependencies 12 | run: sudo apt-get install protobuf-compiler libprotobuf-dev poppler-utils 13 | - uses: actions/checkout@v2 14 | - name: Checkout submodules 15 | run: git submodule update --init --force --recursive 16 | - name: Set up JDK 17 | uses: actions/setup-java@v1 18 | with: 19 | java-version: 13 20 | - name: Compile submodules 21 | working-directory: ./cld3-Java 22 | run: | 23 | ant jar 24 | mvn install:install-file -Dfile=cld3-java.jar -DgroupId=cld3-java -DartifactId=cld3-java -Dversion=1.0 -Dpackaging=jar 25 | - name: Build PDF Extract 26 | run: mvn package 27 | - name: Run Single Tests 28 | working-directory: ./Test 29 | run: time sh run-single.sh 30 | - name: Run Batch Tests 31 | working-directory: ./Test 32 | run: time sh run-batch.sh 33 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "cld3-Java"] 2 | path = cld3-Java 3 | url = https://github.com/xondre09/cld3-Java.git 4 | -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | # PDFExtract Installation 2 | 3 | - Download setup script to `work` directory: [setup.sh](setup.sh) 4 | 5 | *Support for Ubuntu >= 16.04 or CentOS >= 7 or Debian >= 9* 6 | 7 | 8 | - Go into `work` directory then execute setup script. 9 | 10 | ``` 11 | cd work 12 | sudo bash setup.sh 13 | ``` 14 | 15 | - After setup finish, there will have `PDFExtract-2.0.jar` and `PDFExtract.json` in `target` folder. 16 | 17 | ``` 18 | ls -l target/ 19 | - PDFExtract-2.0.jar 20 | - PDFExtract.json 21 | ``` 22 | 23 | - You can now run the PDFExtract-2.0.jar via command line using the instructions in [README.md](README.md) 24 | 25 | - PDFExtract project is now in `/work/setup-tmp/pdf-extract` directory. 26 | 27 | - And java library for PDFExtract in `/work/setup-tmp/pdf-extract/target/`. 28 | 29 | 30 | ## Protobuf installation issues 31 | If using your distribution packages for `libprotobuf` is not enough to compile `cld3`, please, install it manually (you can follow `bitextor` instructions: https://github.com/bitextor/bitextor#language-detector) 32 | 33 | 34 | 35 | # Sentence-join installation 36 | 37 | - Prequisite: [KenLM](https://github.com/kpu/kenlm) must be installed or you may use KenLM from [Moses](https://github.com/moses-smt/mosesdecoder). 38 | - Set the KenLM or Moses path in [pdf-extract config file](PDFExtract.json) in secgion `kenlm_path` 39 | 40 | ``` 41 | "sentence_join" : "/home/user/sentence-join/sentence-join.py" 42 | "kenlm_path" : "/home/user/kenlm/bin" 43 | ``` 44 | 45 | - Download the models for the language pairs that you want to process from `http://data.statmt.org/paracrawl/sentence-join/` 46 | - Set path with prefix for models (expected extensions forward.binlm and backward.binlm) in [pdf-extract config file](PDFExtract.json) in section `sentencejoin_model` for each language 47 | 48 | ``` 49 | "sentencejoin_model" : "/home/user/models/en/opus", 50 | ``` 51 | 52 | 53 | # Dependencies 54 | All dependencies are included in the project folder. 55 | 56 | 57 | | Library | URL| Description | 58 | | --- | --- | --- | 59 | | cld3-java.jar | https://github.com/xondre09/cld3-Java | Java wrapper for cld3 | 60 | | json-lib-2.4-jdk15.jar | https://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4 | Read json | 61 | | commons-beanutils-1.8.3.jar | https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils/1.8.3 | Dependency of json | 62 | | commons-collections.jar | https://mvnrepository.com/artifact/commons-collections/commons-collections/3.2 | Dependency of json | 63 | | commons-lang.jar | https://mvnrepository.com/artifact/commons-lang/commons-lang/2.1 | Dependency of json | 64 | | commons-logging-1.2.jar | https://mvnrepository.com/artifact/commons-logging/commons-logging/1.2 | Dependency of json | 65 | | ezmorph.jar | https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph/1.0.6 | Dependency of json | 66 | | commons-io-2.6.jar | https://mvnrepository.com/artifact/commons-io/commons-io/2.6 | Read / write file | 67 | | guava-15.0.jar | https://mvnrepository.com/artifact/com.google.guava/guava/15.0 | Manage collections | 68 | | pdfbox-2.0.17.jar | https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox/2.0.17 | Manage pdf file | 69 | 70 | 71 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /PDFExtract.js: -------------------------------------------------------------------------------- 1 | //Analyzes the lines in a chunk/paragraph to deterine if a line should be joined to the line that follows it. 2 | function analyzeJoins(lines, lang) { 3 | 4 | // 5 | switch(lang.toLower()) { 6 | case "en": 7 | // code block 8 | break; 9 | case "fr": 10 | // code block 11 | break; 12 | default: 13 | // code block 14 | } 15 | return lines; 16 | } 17 | 18 | //Adjusts the line to repair poorly rendered objects that may be split, but are one. 19 | function repairObjectSequence(line) { 20 | 21 | return line; 22 | } 23 | 24 | //Custom detection that would identify a section as a header. This is only called if internal logic has not already identified the content as a header and is within the first 5 paragraphs on the page. 25 | function isHeader(lines, pageWidth, pageHeight) { 26 | //code block 27 | return false; 28 | } 29 | 30 | //Custom detection that would identify a section as a footer. This is only called if internal logic has not already identified the content as a footer and is within the last 5 paragraphs on the page. 31 | function isFooter(lines, pageWidth, pageHeight) { 32 | //code block 33 | return false; 34 | } 35 | -------------------------------------------------------------------------------- /PDFExtract.json: -------------------------------------------------------------------------------- 1 | { 2 | "script" : { 3 | "sentence_join" : "/home/usr/sentence-join/sentence-join.py", 4 | "kenlm_path" : "/home/usr/kenlm/bin" 5 | }, 6 | "language" : 7 | [ 8 | { 9 | "name" : "common", 10 | "config" : { 11 | "join_words" : [ 12 | [".*[\\,\\&\\;\\:]$", "", " "], 13 | [".*[a-z]+\\-$", "^[a-z]+.*", ""], 14 | [".*[a-z]{1,}$", "^[a-z]+.*", " "], 15 | [".*[\\,\\;\\s][A-Z]{1,1}$", "", " "], 16 | [".*\\s(to|for|at|by)$", "", " "] 17 | ], 18 | "absolute_eof" : [ 19 | [".*(? sentence_join` specifies the path to the sentence join tool 50 | - `script > kenlm_path` specifies the prefix for kenlm (expected extensions kenlm_query, kenlm_lmplz and kenlm_build_binary) 51 | - `language[name=common] > config` rules to common use for all 52 | - `language[name=common] > config > join_word` rules for joining words ["rule for left side", "rule for right side", "join character"] 53 | - `language[name=common] > config > absolute_eof` rules for identify end of sentence ["rule for left side", "rule for right side"] 54 | - `language[name=common] > config > normalize` rules for normalize words ["rule", "word normalize"] 55 | - `language[name=common] > config > repair` rules for repair words at the last step of the process 56 | - `language[name=language] > config` rules use for specify language 57 | - `language[name=language] > config > sentencejoin_model` specifies the prefix model path for sentence join tool by language 58 | - `language[name=language] > config > join_word` rules for joining words by language 59 | - `language[name=language] > config > absolute_eof` rules for identify end of sentence by language 60 | - `language[name=language] > config > normalize` rules for normalize words by language 61 | - `language[name=language] > config > repair` rules for repair words at the last step of the process of the language 62 | 63 | ``` 64 | { 65 | "script" : { 66 | "sentence_join" : "/home/usr/sentence-join/sentence-join.py", 67 | "kenlm_path" : "/home/usr/kenlm/bin", 68 | }, 69 | "language" : 70 | [ 71 | { 72 | "name" : "common", 73 | "config" : { 74 | "join_words" : [ 75 | [".*[\\,\\&\\;\\:]$", "", " "], 76 | [".*[a-z]+\\-$", "^[a-z]+.*", ""], 77 | [".*[a-z]{1,}$", "^[a-z]+.*", " "], 78 | [".*[\\,\\;\\s][A-Z]{1,1}$", "", " "], 79 | [".*\\s(to|for|at|by)$", "", " "] 80 | ], 81 | "absolute_eof" : [ 82 | [".*(? -O -B [-L ] [-T ] [--keepbrtags] [--getperms] [-C ] [-t ] [-K ] [-S ] 137 | ``` 138 | *Arguments* 139 | - `-I ` specifies the path to the source PDF file process for extraction. 140 | - `-O ` specifies the path to the output HTML file after extraction. 141 | - `-B ` specifies the path to the batch file for processing list of files. The input file and output file are specified on the same line delimited by a tab. Each line is delimited by a new line character. 142 | - `-L ` specifies the path to write the log file to. As it is common for PDF files to have issues when processing such as being password protected or other forms of restricted permissions, the log file can be written to a specified location for additional processing. If not specified, then the log file will write to stdout. 143 | - `-T ` specifies the number of threads to run concurrently when processing PDF files. One file can be processed per thread. If not specified, then the default valur of 1 thread is used. 144 | - `--keepbrtags` by default <br /> is not included in the output. When this argument is specified, then the output will include the <br /> tag after each line. 145 | - `--getperms` by default the permissions is not included in the output. When this argument is specified, then the output will include permissions tag into header section. 146 | - `-C ` specifies a json configuration file. If not specify, then the file `PDFExtract.json` in the same folder as the `PDFExtract.jar` file will be used. 147 | - `-t ` specifies the maximum time wait in seconds for poppler extract 148 | - `-K ` specifies the prefix for kenlm (expected extensions kenlm_query, kenlm_lmplz and kenlm_build_binary), this value will override path in config file 149 | - `-S ` specifies the path to the sentence join tool, this value will override path in config file 150 | 151 | **Example:** 152 | 153 | This example processes a single English PDF file in English. 154 | 155 | ```sh 156 | java -jar PDFExtract.jar -I pdf-in/sample.pdf -O html-display/sample.html 157 | ``` 158 | 159 | This example processes a batch of files as specified in `sample-display.tab` using 3 threads and writing to a user specified log file. Custom JavaScript rules for sentence joining and object sequence repairs is also specified. 160 | 161 | ```sh 162 | java -jar PDFExtract.jar -B sample-display.tab -L batch.log -T 3 163 | ``` 164 | 165 | The contents of `sample-display.tab` are: 166 | ```text 167 | pdf-in/sample.pdf html-display/sample.html 168 | pdf-in/sample2.pdf html-display/sample2.html 169 | pdf-in/sample3.pdf html-display/sample3.html 170 | pdf-in/sample4.pdf html-display/sample4.html 171 | ``` 172 | 173 | The format is: 174 | ``` 175 | \t 176 | \t 177 | \t 178 | ... 179 | ``` 180 | 181 | ### Library PDF Extraction 182 | 183 | PDFExtract has 2 methods overloaded methods 184 | 185 | 1. Single File 186 | ```Java 187 | public void Extract(String inputFile, String outputFile, int keepBrTags) throws Exception 188 | ``` 189 | 190 | 2. Batch File 191 | ```java 192 | public void Extract(String batchFile, String rulePath, int threadCount, int keepBrTags) throws Exception 193 | ``` 194 | 195 | 3. Stream 196 | ```java 197 | public ByteArrayOutputStream Extract(ByteArrayInputStream inputStream, int keepBrTags) throws Exception 198 | ``` 199 | 200 | PDFExtract may be used from within Java with the following import: 201 | 202 | ```java 203 | import com.java.app.PDFExtract; 204 | 205 | PDFExtract pdf = new PDFExtract(logpath); 206 | 207 | String inputFile = "/data/test.pdf"; 208 | String outputFile = "/data/test.html"; 209 | int threadCount = 5; 210 | int keepBrTags = 0; 211 | 212 | // Single File 213 | pdf.Extract(inputFile, outputFile, keepBrTags); 214 | 215 | // Batch File 216 | pdf.Extract(batchFile, threadCount, keepBrTags); 217 | 218 | // Stream 219 | ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(new File(inputFile).toPath())); 220 | ByteArrayOutputStream outputStream = pdf.Extract(inputStream, keepBrTags); 221 | ``` 222 | 223 | ---- 224 | ## How It Works 225 | Adobe Portal Document Format (PDF) is a publishing format and is not designed for easy editing and manipulation. At the core of PDF is an advanced imaging model derived from the PostScript page description language. This PDF Imaging Model enables the description of text and graphics in a device-independent and resolution-independent manner. To improve performance for interactive viewing, PDF defines a more structured format than that used by most PostScript language programs. 226 | 227 | Unlike PostScript, which is a programming language, PDF is based on a structured binary file format that is optimized for high performance in interactive viewing. PDF also includes objects, such as annotations and hypertext links, that are not part of the page content itself but are useful for interactive viewing and document interchange. 228 | 229 | Our first step is to extract the PDF content out into a Document Object Model (DOM) that can be further processed into an optimal format for alignment between two similar documents. PDFExtract uses the Poppler (https://poppler.freedesktop.org/) as a parser in order to get the initial DOM. This DOM is designed for rendering in HTML with large output that may have content out of sequence in terms of when it is rendered, but sill in correctly placed on the page. For example, a footer could be embedded in the sequence at the start rather than at the bottom of the page. There may also be off-page noise from the PDF creation tool that can confuse many aligners. This content is not visible on the page but is embedded in the document. Each word (and sometimes each letter) may be a separate note in the DOM based on the original content. Poppler does a reasonable job of converting these to blocks of text, but the raw DOM output the raw DOM is not very suitable for aligning and mining of content without further processing. 230 | 231 | PDFExtract refines the initial DOM into a normalized and simplified HTML format that is light and fast to process. The content is refined, repaired then formatted into a cleaner format. Each block of text within the document is then processed through language identification. Once the language of the text is defined, a set of configurable language specific rules can be run to join split sentences and then the content is analyzed further with a sentence join tool to determine if 2 consecutive blocks of text should be joined as one. 232 | 233 | ## Document Format 234 | ### Alignment Optimized HTML 235 | The content below is a small sample of content that provides examples of each section of the document. 236 | ```html 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 |
250 |

251 | Associated British Foods plc 252 | Weston Centre 253 | 10 Grosvenor Street London W1K 4QY 254 | Tel + 44 (0) 20 7399 6500 255 | Fax + 44 (0) 20 7399 6580 256 | For an accessible version of the Annual Report and Accounts please visit www.abf.co.uk 257 |

258 |

259 | ... 260 |

261 |
262 |
263 |

264 | • Acquisition of the leading Iberian sugar producer, Azucarera Ebro 265 | • Sale of Polish sugar business 266 | • Restructuring of US packaged oils business - new joint venture, Stratas 267 | • Zambian cane sugar expansion completed - capacity doubled 268 | • Investment in Chinese beet and cane sugar 269 | • Enzyme capacity investment in Finland completed 270 | • Yeast and yeast extracts plant under construction in Harbin 271 | • New Primark stores in UK and Spain and first openings in the Netherlands, Germany and Portugal 272 | • US Private Placement secures long-term non-bank finance 273 |

274 |

275 | This report has been printed on revive 50:50 Silk paper. 276 | This paper is made from pre and post consumer waste and virgin wood fibre, independently certified in accordance with the Forest Stewardship Council (FSC). 277 | It is manufactured at a mill that is certified to ISO 14001 environmental management standards. The pulp is bleached using an elemental chlorine free process. The inks used are all vegetable oil based. 278 | Printed at St Ives Westerham Press Ltd, ISO 14001, FSC certified and CarbonNeutral® 279 |

280 | .... 281 |

282 | This report contains forward-looking statements. These have been made by the directors in good faith based on the information available to them up to the time of their approval of this report. The directors can give no assurance that these expectations will prove to have been correct. Due to the inherent uncertainties, including both economic and business risk factors underlying such forward-looking information, actual results may differ materially from those expressed or implied by these forward-looking statements. The directors undertake no obligation to update any forward-looking statements whether as a result of new information, future events or otherwise. 283 |

284 |
285 | 286 | 287 | 288 | ``` 289 | 290 | ### ID Formats 291 | The ID of a element is defined by is parent structure with an incremental counter: 292 | 293 | - page = page 294 | - paragraph = p 295 | 296 | **Example** 297 | 298 | Page 1, paragraph 3 would be written as `page1p3`. 299 | 300 | ### FontName 301 | The name of the font used for each paragraph is defined in the paragraph header. If there is a small change in font wihtin the paragraph, for example to highlight a color or if a part of the text was bold or italic, then these are removed and only the primary font is represented. 302 | 303 | ### Joining Lines 304 | Lines are joined automatically when they are split in the orignal content. Absolute line/sentence join rules are provided int he conifguration file. Automated sentence joining is provided by the Paracrawl Sentence Join tool. (https://github.com/paracrawl/sentence-join) 305 | 306 | ### Repairing Object Sequences 307 | Some PDF tools export malformed PDF content in some cases. For example, instead of rendering a word as a single object, a set of letters are rendered as individual objects. There are many exceptions that need to be handled. Common exceptions are handled wihtin the Java code. 308 | 309 | ## Search and Replace Characters 310 | Some PDF creation tools will transform characters resulting in words that are not using the correct letters (in terms of actual Unicode values), but look correct on the screen. 311 | 312 | For example (A) first (B) first 313 | 314 | Both of these look the same. But the "fi" in A is the letter "f" and "i" while the "fi" in B is the character "fi" (U+FB01). 315 | 316 | A list of these characters can be found in the file configuration file in the same folder as the PDFExtract.jar file. Additional search and replace characters can be added as needed. This search and replace is performed when processing words and merging them into lines. 317 | 318 | ## Performance 319 | The processing has been optimized and multithreaded. Reducing a large file can take some time. A 50MB PDF can be extracted, cleaned and stored in as little 10K, depending on the content. 320 | 321 | Previously for V1 and V2, the Apache PDF Box library was used to extract the intial DOM. V2 was a more optimize version using PDF Box. V3 is a complete rewrite and update to use the Poppler toolkit which is considerably faster. Poppler has some limitations and issues with paragragh font merging when they are different, but these have been worked around externally in the PDFExtract code. 322 | 323 | 1. Single file 324 | 325 | | Name | Size (KB) | V1 | V2 | V3 | 326 | | --- | --- | --- | --- | --- | 327 | | sample.pdf | 2.96 | 00:00:01.630 | 00:00:00.662 | 00:00:00.394 | 328 | | sample2.pdf | 34.72 | 00:00:01.698 | 00:00:00.909 | 00:00:00.454 | 329 | | sample3.pdf | 597.78 | 00:00:04.034 | 00:00:01.801 | 00:00:00.717 | 330 | | sample4.pdf | 3,462.57 | 00:01:38.810 | 00:00:32.910 | 00:00:08.949 | 331 | 332 | 2. Batch file, 10 files, 10 threads 333 | 334 | | Name | Size (KB) | V1 | V2 | V3 | 335 | | --- | --- | --- | --- | --- | 336 | | sample.pdf | 2.96 | 00:00:01.570 | 00:00:00.791 | 00:00:00.445 | 337 | | sample2.pdf | 34.72 | 00:00:02.452 | 00:00:01.377 | 00:00:00.718 | 338 | | sample3.pdf | 597.78 | 00:00:07.693 | 00:00:02.542 | 00:00:01.124 | 339 | | sample4.pdf | 3,462.57 | 00:03:35.353 | 00:00:36.036 | 00:00:12.594 | 340 | 341 | 342 | ## TODO 343 | The below list is a set of features planned for future: 344 | - Right-to-Left languages. 345 | - This code is untested on right-to-left languages and may need to be modified to support languages such as Arabic. 346 | - Vertical Script 347 | - This code is untested on right-to-left languages and may need to be modified to support languages such as Japanese when written down the page.. 348 | 349 | 350 | ---- 351 | ## FAQ 352 | ### Can the HTML output be loaded into the browser to view? 353 | Yes. By default the HTML output is not in a format that will render well in a browser as it is formatted for optimal processing and hot intended to be viewed by humans. Use the `--keepbrtags` option to output the HTML in a more visual format. 354 | 355 | ### Can this tool extract text from images embedded in PDF files? 356 | No. This tool processes only text. It is not an OCR tool, it is only able to extract text from PDF if the data is already in text format. 357 | 358 | 359 | -------------------------------------------------------------------------------- /Test/pdf-in/sample.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitextor/pdf-extract/6a8acac2bf99526e80604e377264aa1142be5471/Test/pdf-in/sample.pdf -------------------------------------------------------------------------------- /Test/pdf-in/sample2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitextor/pdf-extract/6a8acac2bf99526e80604e377264aa1142be5471/Test/pdf-in/sample2.pdf -------------------------------------------------------------------------------- /Test/pdf-in/sample3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitextor/pdf-extract/6a8acac2bf99526e80604e377264aa1142be5471/Test/pdf-in/sample3.pdf -------------------------------------------------------------------------------- /Test/pdf-in/sample4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitextor/pdf-extract/6a8acac2bf99526e80604e377264aa1142be5471/Test/pdf-in/sample4.pdf -------------------------------------------------------------------------------- /Test/run-batch.sh: -------------------------------------------------------------------------------- 1 | java -jar ../target/PDFExtract-2.0.jar -B "sample.tab" -T 10 -LANG "en" 2 | -------------------------------------------------------------------------------- /Test/run-single.sh: -------------------------------------------------------------------------------- 1 | java -jar ../target/PDFExtract-2.0.jar -I "pdf-in/sample.pdf" -O "html-out/sample.html" -LANG "en" 2 | -------------------------------------------------------------------------------- /Test/sample.tab: -------------------------------------------------------------------------------- 1 | pdf-in/sample.pdf html-out/sample.html 2 | pdf-in/sample2.pdf html-out/sample2.html 3 | pdf-in/sample3.pdf html-out/sample3.html 4 | pdf-in/sample4.pdf html-out/sample4.html 5 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | PDFExtract 6 | PDFExtract 7 | 2.0 8 | 9 | 1.8 10 | 1.8 11 | 1.8 12 | UTF-8 13 | UTF-8 14 | 15 | 16 | 17 | commons-beanutils 18 | commons-beanutils 19 | 1.9.4 20 | 21 | 22 | commons-collections 23 | commons-collections 24 | 3.2.2 25 | 26 | 27 | commons-io 28 | commons-io 29 | 2.8.0 30 | 31 | 32 | commons-lang 33 | commons-lang 34 | 2.1 35 | 36 | 37 | commons-logging 38 | commons-logging 39 | 1.2 40 | 41 | 42 | net.sf.ezmorph 43 | ezmorph 44 | 1.0.6 45 | 46 | 47 | com.google.guava 48 | guava 49 | [24.1.1,) 50 | 51 | 52 | net.sf.json-lib 53 | json-lib 54 | 2.4 55 | jdk15 56 | 57 | 58 | com.itextpdf 59 | itextpdf 60 | 5.5.13.3 61 | 62 | 63 | org.bouncycastle 64 | bcprov-jdk15on 65 | 1.67 66 | 67 | 68 | org.bouncycastle 69 | bcpkix-jdk15on 70 | 1.64 71 | 72 | cld3-java 73 | cld3-java 74 | 1.0 75 | 76 | 77 | 78 | src 79 | 80 | 81 | maven-compiler-plugin 82 | 3.8.0 83 | 84 | 1.8 85 | 1.8 86 | 87 | 88 | 89 | org.apache.maven.plugins 90 | maven-assembly-plugin 91 | 92 | 93 | 94 | Main 95 | 96 | 97 | false 98 | 99 | jar-with-dependencies 100 | 101 | 102 | 103 | 104 | make-assembly 105 | package 106 | 107 | single 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | ${project.basedir} 116 | ${project.build.directory} 117 | 118 | PDFExtract.json 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /releases: -------------------------------------------------------------------------------- 1 | ## v1.0 Changelog 2 | - 3 | -------------------------------------------------------------------------------- /sentence-join/README.md: -------------------------------------------------------------------------------- 1 | # SENTENCE JOIN TOOL FOR PARACRAWL 2 | 3 | written by Philipp Koehn, 2019 4 | 5 | ### Basic usage: 6 | > ./sentence-join.py --train --model MY_MODEL --text MY_TRAINING_CORPUS 7 | 8 | > ./sentence-join.py --tune --model MY_MODEL --dev MY_DEV_CORPUS 9 | 10 | > ./sentence-join.py --apply --model MY_MODEL --threshold MY_THRESHOLD < in > out 11 | 12 | Input when applying is a pair of lines, separated by a tab character 13 | 14 | Output is prediction if they should be joined 15 | 16 | 17 | ### Example: 18 | > This is a test This is a test 19 | > ===> True 20 | 21 | > This is a test and this is a test 22 | > ===> False 23 | 24 | -------------------------------------------------------------------------------- /sentence-join/sentence-join.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sys 4 | import os 5 | import subprocess 6 | import argparse 7 | 8 | kenlm_query = "/var/www/html/experiment/moses/bin/query" 9 | kenlm_lmplz = "/var/www/html/experiment/moses/bin/lmplz" 10 | kenlm_build_binary = "/var/www/html/experiment/moses/bin/build_binary" 11 | break_token = "___BREAK___" 12 | 13 | # SENTENCE JOIN TOOL FOR PARACRAWL 14 | # written by Philipp Koehn, 2019 15 | # 16 | # Basic usage: 17 | # ./sentence-join.py --train --model MY_MODEL --text MY_TRAINING_CORPUS 18 | # ./sentence-join.py --tune --model MY_MODEL --dev MY_DEV_CORPUS 19 | # ./sentence-join.py --apply --model MY_MODEL --threshold MY_THRESHOLD < in > out 20 | # 21 | # Input when applying is a pair of lines, separated by a tab character 22 | # Output is prediction if they should be joined 23 | # 2020-06-01 Modified by Ramoelee : Add a new input parameter --kenlm_path (optional) for define the kenlm path. 24 | # ./sentence-join.py --apply --model MY_MODEL --kenlm_path MY_KENLM_PATH 25 | 26 | class KenLM(object): 27 | def __init__(self, cmd): 28 | self.cmd = cmd 29 | self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) 30 | 31 | def process(self, line): 32 | input_string = u"%s\n" % line 33 | input_string = input_string.encode("utf-8") 34 | self.proc.stdin.write(input_string) 35 | self.proc.stdin.flush() 36 | result = self.proc.stdout.readline() 37 | #print(result.decode("utf-8").strip()) 38 | return result.decode("utf-8").strip().split("\t")[4].split(" ")[2] 39 | 40 | def train_models(text_file,model_stem): 41 | txt_fh = open(text_file,"r") 42 | forward_txt_fh = open(model_stem + ".forward.tok", "w") 43 | backward_txt_fh = open(model_stem + ".backward.tok", "w") 44 | line_buffer = [] 45 | max_line_size = 100 46 | for line in txt_fh: 47 | if remove_punctuation: 48 | line_buffer.extend([word for word in line.split() if word != "." and word != "!" and word != "?"]) 49 | else: 50 | line_buffer.extend(line.split()) 51 | line_buffer.append(break_token) 52 | while len(line_buffer) > max_line_size: 53 | block = line_buffer[0:max_line_size] 54 | forward_txt_fh.write( " ".join(block) + "\n") 55 | block.reverse() 56 | backward_txt_fh.write(" ".join(block) + "\n") 57 | line_buffer = line_buffer[max_line_size:] 58 | forward_txt_fh.close() 59 | backward_txt_fh.close() 60 | 61 | for direction in ["forward","backward"]: 62 | os.system(kenlm_lmplz + " --order 5 --prune 0 0 1 -S 10G " + 63 | "-T " + model_stem + ".tmp " + 64 | "--text " + model_stem + "." + direction + ".tok " + 65 | "--arpa " + model_stem + "." + direction + ".lm") 66 | os.system(kenlm_build_binary + " -a 22 -q 8 -b 8 -S 10G " + 67 | "-T " + model_stem + ".tmp " + 68 | "trie " + 69 | model_stem + "." + direction + ".lm " + 70 | model_stem + "." + direction + ".binlm") 71 | 72 | def score_context(left_context,left_no_break_token, right_context,right_no_break_token): 73 | left_context_no_break = " ".join(left_context) + " " + left_no_break_token 74 | right_context_no_break = " ".join(right_context) + " " + right_no_break_token 75 | left_context_break = " ".join(left_context) + " " + break_token 76 | right_context_break = " ".join(right_context) + " " + break_token 77 | forward_predict_break = kenlm_forward.process(left_context_break) 78 | forward_predict_no_break = kenlm_forward.process(left_context_no_break) 79 | backward_predict_break = kenlm_backward.process(right_context_break) 80 | backward_predict_no_break = kenlm_backward.process(right_context_no_break) 81 | #print(forward_predict_break,forward_predict_no_break,backward_predict_break,backward_predict_no_break) 82 | score = float(forward_predict_break) - float(forward_predict_no_break) 83 | score += float(backward_predict_break) - float(backward_predict_no_break) 84 | return score 85 | 86 | def check_threshold(tune_set,threshold): 87 | correct_positive = 0 88 | correct_negative = 0 89 | false_positive = 0 90 | false_negative = 0 91 | for item in tune_set: 92 | prediction = item[0] > threshold 93 | if prediction and item[1]: 94 | correct_positive += 1 95 | elif prediction and not item[1]: 96 | false_positive += 1 97 | elif not prediction and not item[1]: 98 | correct_negative += 1 99 | else: 100 | false_negative += 1 101 | #print(item,correct_positive,correct_negative,false_positive,false_negative) 102 | precision = correct_positive / (correct_positive + false_positive + 0.01) 103 | recall = correct_positive / (correct_positive + false_negative + 0.01) 104 | f_measure = 2 * precision * recall / (precision + recall + 0.01) 105 | accuracy = (correct_positive + correct_negative) / len(tune_set) 106 | #print(threshold,accuracy,f_measure,precision,recall,correct_positive,correct_negative,false_positive,false_negative) 107 | return f_measure 108 | 109 | def tune_threshold(tune_file): 110 | tune_fh = open(tune_file,"r") 111 | 112 | # load words from tune file 113 | words = [] 114 | for line in tune_fh: 115 | if remove_punctuation: 116 | words.extend([word for word in line.split() if word != "." and word != "!" and word != "?"]) 117 | else: 118 | words.extend(line.split()) 119 | words.append(break_token) 120 | 121 | # create test instances 122 | tune_set = [] 123 | for i in range(4,len(words)-4): 124 | left_context = [] 125 | right_context = [] 126 | for j in range(1,5): 127 | left_context.insert(0,words[i-j]) 128 | right_context.insert(0,words[i+j]) 129 | #print(left_context) 130 | #print(words[i]) 131 | #print(right_context) 132 | 133 | if words[i] == break_token: 134 | left_no_break_token = words[i+1] 135 | right_no_break_token = words[i-1] 136 | else: 137 | left_no_break_token = words[i] 138 | right_no_break_token = words[i] 139 | score = score_context(left_context,left_no_break_token, right_context,right_no_break_token) 140 | tune_set.append([score, words[i] == break_token]) 141 | tune_fh.close() 142 | 143 | #print(len(tune_set)) 144 | best_threshold = 0 145 | best_score = 0 146 | # grid search for best threshold 147 | for threshold in range(0,15): 148 | score = check_threshold(tune_set,threshold) 149 | if score > best_score: 150 | best_score = score 151 | best_threshold = threshold 152 | 153 | # binary search for better threshold 154 | for i in range(1,10): 155 | higher = best_threshold + 1/(2**i) 156 | lower = best_threshold - 1/(2**i) 157 | for variant in [higher,lower]: 158 | score = check_threshold(tune_set,variant) 159 | if score > best_score: 160 | best_score = score 161 | best_threshold = variant 162 | 163 | print(best_score,best_threshold) 164 | return best_threshold 165 | 166 | def runtime_scoring(): 167 | for line in sys.stdin: 168 | #print( 0/0) 169 | #print(line.rstrip()) 170 | try: 171 | (left_sentence,right_sentence) = line.rstrip().split("\t") 172 | except: 173 | print("Invalid input") 174 | sys.stdout.flush() 175 | continue 176 | left_words = left_sentence.split() 177 | right_words = right_sentence.split() 178 | 179 | left_context = [] 180 | right_context = [] 181 | for j in range(4): 182 | if j < len(left_words): 183 | left_context.insert(0,left_words[-j-1]) 184 | else: 185 | left_context.insert(0,"___DUMMY___") 186 | if j < len(right_words): 187 | right_context.insert(0,right_words[j]) 188 | else: 189 | right_context.insert(0,"___DUMMY___") 190 | #print(left_context, right_words[0], right_context, left_words[-1]) 191 | score = score_context(left_context, right_words[0], right_context, left_words[-1]) 192 | #print(score,threshold) 193 | #sys.stdout.flush() 194 | print(score < threshold) 195 | sys.stdout.flush() 196 | 197 | 198 | parser = argparse.ArgumentParser(description='Command line tool for sentence joining decisions.') 199 | parser.add_argument('--tune', help='tune the threshold on a sentence-split tune set', action="store_true") 200 | parser.add_argument('--train', help='train the language models, provide sentence-split training set and prefix for models', action="store_true") 201 | parser.add_argument('--apply', help='provide a pair of lines for splitting decisions on STDIN (tab-split, one pair per line)', action="store_true") 202 | parser.add_argument('--text', help='text file for training') 203 | parser.add_argument('--dev', help='text file for tuning') 204 | parser.add_argument('--model', help='prefix for models (expected extensions forward.binlm and backward.binlm)') 205 | parser.add_argument('--kenlm_path', help='prefix for kenlm (expected extensions kenlm_query, kenlm_lmplz and kenlm_build_binary)') 206 | parser.add_argument('--threshold', help='threshold for joining decisions', type=float) 207 | parser.add_argument('--remove-punctuation', help='remove all punctuation from training and tuning text files', action="store_true") 208 | args = parser.parse_args() 209 | 210 | remove_punctuation = False 211 | if args.remove_punctuation: 212 | remove_punctuation = args.remove_punctuation 213 | 214 | # train language models 215 | if args.train: 216 | if not args.text: 217 | print("ERROR: Specify a text file to train language models") 218 | parser.parse_args(["-h"]) 219 | train_models(args.text,args.model) 220 | 221 | # if tune or apply, then load model files 222 | if args.tune or args.apply: 223 | if not args.model: 224 | print("ERROR: Specify a model prefix!") 225 | parser.parse_args(["-h"]) 226 | if args.kenlm_path: 227 | kenlm_query = args.kenlm_path + "/query" 228 | kenlm_lmplz = args.kenlm_path + "/lmplz" 229 | kenlm_build_binary = args.kenlm_path + "/build_binary" 230 | #print(kenlm_query + "\n" + kenlm_lmplz + "\n" + kenlm_build_binary) 231 | kenlm_forward = KenLM([kenlm_query,"-b","-n",args.model + ".forward.binlm"]) 232 | kenlm_backward = KenLM([kenlm_query,"-b","-n",args.model + ".backward.binlm"]) 233 | 234 | # optimize threshold 235 | if args.tune: 236 | if not args.dev: 237 | print("ERROR: Specify a text file for tuning with --dev DEV!") 238 | parser.parse_args(["-h"]) 239 | threshold = tune_threshold(args.dev) 240 | 241 | # apply the model to stdin 242 | if args.apply: 243 | threshold = 7.0 244 | if args.threshold: 245 | threshold = args.threshold 246 | elif os.path.exists(args.model + ".threshold"): 247 | fh = open(args.model + ".threshold", "r") 248 | threshold = float(fh.readlines()[0].rstrip().split(" ")[1]) 249 | runtime_scoring() 250 | 251 | # if no action is specified, complain 252 | if not args.train and not args.tune and not args.apply: 253 | parser.parse_args(["-h"]) 254 | 255 | -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | START=$(date +%s) 5 | 6 | if [ -f /etc/os-release ]; then 7 | # freedesktop.org and systemd 8 | . /etc/os-release 9 | OS=$NAME 10 | VER=$VERSION_ID 11 | elif type lsb_release >/dev/null 2>&1; then 12 | # linuxbase.org 13 | OS=$(lsb_release -si) 14 | VER=$(lsb_release -sr) 15 | elif [ -f /etc/lsb-release ]; then 16 | # For some versions of Debian/Ubuntu without lsb_release command 17 | . /etc/lsb-release 18 | OS=$DISTRIB_ID 19 | VER=$DISTRIB_RELEASE 20 | elif [ -f /etc/debian_version ]; then 21 | # Older Debian/Ubuntu/etc. 22 | OS=Debian 23 | VER=$(cat /etc/debian_version) 24 | elif [ -f /etc/SuSe-release ]; then 25 | # Older SuSE/etc. 26 | OS="" 27 | VER="" 28 | elif [ -f /etc/redhat-release ]; then 29 | # Older Red Hat, CentOS, etc. 30 | OS="" 31 | VER="" 32 | else 33 | # Fall back to uname, e.g. "Linux ", also works for BSD, etc. 34 | OS="" 35 | VER="" 36 | fi 37 | 38 | if [ "$OS" == "" ] ; then 39 | 40 | echo "The operating system is not supported by this script." 41 | 42 | elif [[ "$OS" == *"Debian"* && $VER+0 -lt 9 ]] ; then 43 | 44 | echo "The operating system is not supported by this script." 45 | echo "Debian 9 or higher is required." 46 | 47 | elif [[ "$OS" == *"Ubuntu"* && $VER+0 < 16 ]] ; then 48 | 49 | echo "The operating system is not supported by this script." 50 | echo "Ubuntu 16 or higher is required." 51 | 52 | elif [[ "$OS" == *"CentOS"* && $VER+0 < 7 ]] ; then 53 | 54 | echo "The operating system is not supported by this script." 55 | echo "Ubuntu 16 or higher is required." 56 | else 57 | 58 | MODE=${1:-full} 59 | 60 | echo "###" 61 | echo "### $OS - $VER ###" 62 | echo "###" 63 | 64 | setupTmpDir="setup-tmp" 65 | [ ! -d "$setupTmpDir" ] && mkdir "$setupTmpDir" 66 | cd $setupTmpDir 67 | rm -rf cld3 68 | rm -rf pdf-extract 69 | rm -rf cld3-Java 70 | 71 | if [ "$MODE" != "compile" ]; then 72 | echo "###" 73 | echo "### Install prerequisite programs ###" 74 | echo "###" 75 | if [[ "$OS" == *"Ubuntu"* || "$OS" == *"Debian"* ]] ; then 76 | apt-get update 77 | apt-get install autoconf automake libtool curl make g++ unzip git ant maven poppler-utils wget -y 78 | 79 | if [[ "$OS" == *"Ubuntu"* && $VER+0 < 18 ]] ; then 80 | apt-get install apt-transport-https ca-certificates gnupg software-properties-common -y 81 | wget -qO - https://apt.kitware.com/keys/kitware-archive-latest.asc | apt-key add - 82 | apt-add-repository 'deb https://apt.kitware.com/ubuntu/ xenial main' 83 | apt-get update 84 | fi 85 | apt-get install cmake -y 86 | 87 | if [[ "$OS" == *"Debian"* && $VER+0 -ne 9 ]] ; then 88 | apt install apt-transport-https ca-certificates wget dirmngr gnupg software-properties-common -y 89 | wget -qO - https://adoptopenjdk.jfrog.io/adoptopenjdk/api/gpg/key/public | apt-key add - 90 | add-apt-repository --yes https://adoptopenjdk.jfrog.io/adoptopenjdk/deb/ 91 | apt update 92 | apt install adoptopenjdk-8-hotspot -y 93 | export JAVA_HOME=/usr/lib/jvm/adoptopenjdk-8-hotspot-amd64 94 | else 95 | if [[ "$OS" == *"Ubuntu"* && $VER+0 < 16 ]] ; then 96 | yes "" | add-apt-repository ppa:openjdk-r/ppa 97 | apt-get update 98 | fi 99 | apt-get install openjdk-8-jdk -y 100 | export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64 101 | if [[ "$OS" == *"Ubuntu"* && $VER+0 < 16 ]] ; then 102 | update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 103 | fi 104 | fi 105 | elif [[ "$OS" == *"CentOS"* || "$OS" == *"Amazon Linux"* || "$OS" == *"Fedora"* ]] ; then 106 | yum install epel-release -y 107 | yum install autoconf automake libtool unzip gcc-c++ git ant cmake cmake3 maven poppler-utils -y 108 | yum group install "Development Tools" -y 109 | 110 | alternatives --install /usr/local/bin/cmake cmake /usr/bin/cmake 10 \ 111 | --slave /usr/local/bin/ctest ctest /usr/bin/ctest \ 112 | --slave /usr/local/bin/cpack cpack /usr/bin/cpack \ 113 | --slave /usr/local/bin/ccmake ccmake /usr/bin/ccmake \ 114 | --family cmake 115 | 116 | alternatives --install /usr/local/bin/cmake cmake /usr/bin/cmake3 20 \ 117 | --slave /usr/local/bin/ctest ctest /usr/bin/ctest3 \ 118 | --slave /usr/local/bin/cpack cpack /usr/bin/cpack3 \ 119 | --slave /usr/local/bin/ccmake ccmake /usr/bin/ccmake3 \ 120 | --family cmake 121 | fi 122 | 123 | echo "###" 124 | echo "### Install protobuf ###" 125 | echo "###" 126 | if [ -d "protobuf" ]; then rm -Rf "protobuf"; fi 127 | git clone https://github.com/google/protobuf.git 128 | cd protobuf 129 | ./autogen.sh 130 | ./configure 131 | make 132 | make install 133 | ldconfig 134 | cd .. 135 | fi 136 | 137 | echo "###" 138 | echo "### Build cld3 java wrapper ###" 139 | echo "###" 140 | if [ -d "cld3-Java" ]; then rm -Rf "cld3-Java"; fi 141 | git clone https://github.com/xondre09/cld3-Java.git 142 | git clone https://github.com/google/cld3.git 143 | cp -rp cld3/src/ cld3-Java/src/main/cpp/cld3/ 144 | cd cld3-Java/ 145 | ant jar 146 | 147 | echo "###" 148 | echo "### Install cld3-java.jar in maven repository ###" 149 | echo "###" 150 | mvn install:install-file -Dfile=cld3-java.jar -DgroupId=cld3-java -DartifactId=cld3-java -Dversion=1.0 -Dpackaging=jar 151 | cd .. 152 | 153 | echo "###" 154 | echo "### Build PDFExtract ###" 155 | echo "###" 156 | if [ -d "pdf-extract" ]; then rm -Rf "pdf-extract"; fi 157 | git clone https://github.com/bitextor/pdf-extract.git 158 | cd pdf-extract/ 159 | mvn clean install -DskipTests 160 | cd ../../ 161 | cp $setupTmpDir/pdf-extract/PDFExtract.json . 162 | cp $setupTmpDir/pdf-extract/target/PDFExtract*.jar . 163 | 164 | rm -rf $setupTmpDir 165 | ls -l 166 | fi 167 | 168 | END=$(date +%s) 169 | DIFF=$(( $END - $START )) 170 | echo "###" 171 | echo "### Finish, process took $DIFF seconds ###" 172 | echo "###" 173 | -------------------------------------------------------------------------------- /src/Main.java: -------------------------------------------------------------------------------- 1 | import pdfextract.Common; 2 | import pdfextract.PDFExtract; 3 | 4 | /** 5 | * @author MickeyVI 6 | */ 7 | public class Main { 8 | public static void main(String[] args) { 9 | PDFExtract oExtractor = null; 10 | 11 | // args[0] = "--help"; 12 | try { 13 | Common common = new Common(); 14 | 15 | if (args == null || args.length == 0 || args[0].equals("--help")) { 16 | 17 | /** 18 | * Print out help 19 | */ 20 | common.printHelp(); 21 | System.exit(0); 22 | 23 | } 24 | 25 | String input = "", output = "", batchfile = "", logpath = "", threadcount = "", verbose = "", 26 | keepbrtags = "", getperms = "", configfile = "", timeout = "", kenlmPath = "", sentenceJoinPath = ""; 27 | String key = ""; 28 | 29 | /** 30 | * Get command-line arguments 31 | */ 32 | for (String parm : args) { 33 | 34 | if (parm.startsWith("--")) { 35 | key = parm.substring(2); 36 | if (key.equals("keepbrtags")) { 37 | keepbrtags = "1"; 38 | key = ""; 39 | } else if (key.equals("getperms")) { 40 | getperms = "1"; 41 | key = ""; 42 | } 43 | } else if (parm.startsWith("-")) { 44 | key = parm.substring(1); 45 | if (key.equals("v")) { 46 | verbose = "1"; 47 | key = ""; 48 | } 49 | } else { 50 | if (key.equals("I")) { 51 | input = parm; 52 | } else if (key.equals("O")) { 53 | output = parm; 54 | } else if (key.equals("B")) { 55 | batchfile = parm; 56 | } else if (key.equals("L")) { 57 | logpath = parm; 58 | } else if (key.equals("T")) { 59 | threadcount = parm; 60 | } else if (key.equals("C")) { 61 | configfile = parm; 62 | } else if (key.equals("t")) { 63 | timeout = parm; 64 | }else if (key.equals("K")) { 65 | kenlmPath = parm; 66 | }else if (key.equals("S")) { 67 | sentenceJoinPath = parm; 68 | } 69 | key = ""; 70 | } 71 | 72 | } 73 | common.setVerbose(common.getInt(verbose)); 74 | if (!common.IsEmpty(input) && !common.IsEmpty(output)) { 75 | /** 76 | * Call function to extract single PDF file 77 | */ 78 | try { 79 | //#43 Add new arguments for -K, -S 80 | oExtractor = new PDFExtract(logpath, common.getInt(verbose), configfile, common.getLong(timeout), kenlmPath, sentenceJoinPath); 81 | oExtractor.Extract(input, output, common.getInt(keepbrtags), common.getInt(getperms)); 82 | } catch (Exception e) { 83 | common.print("File: " + input + ", " + e.getMessage()); 84 | } 85 | 86 | } else if (!common.IsEmpty(batchfile)) { 87 | /** 88 | * Call function to extract PDF with batch file 89 | */ 90 | try { 91 | //#43 Add new arguments for -K, -S 92 | oExtractor = new PDFExtract(logpath, common.getInt(verbose), configfile, common.getLong(timeout), kenlmPath, sentenceJoinPath); 93 | oExtractor.Extract(batchfile, common.getInt(threadcount), common.getInt(keepbrtags), 94 | common.getInt(getperms)); 95 | } catch (Exception e) { 96 | common.print("File: " + batchfile + ", " + e.getMessage()); 97 | } 98 | 99 | } else { 100 | common.print("Cannot start extract: Invalid parameters."); 101 | System.exit(0); 102 | } 103 | 104 | } catch (Exception ex) { 105 | System.out.println("Cannot start extract. Error=" + ex.getMessage()); 106 | System.exit(0); 107 | } finally { 108 | if (oExtractor != null) { 109 | try { 110 | oExtractor.shutdownProcess(); 111 | } catch (Exception e) { 112 | e.printStackTrace(); 113 | } 114 | oExtractor = null; 115 | System.gc(); 116 | } 117 | } 118 | } 119 | 120 | /* 121 | * (non-Java-doc) 122 | * 123 | * @see java.lang.Object#Object() 124 | */ 125 | public Main() { 126 | super(); 127 | } 128 | 129 | } -------------------------------------------------------------------------------- /src/pdfextract/Common.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileOutputStream; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.io.PrintWriter; 10 | import java.io.StringWriter; 11 | import java.io.Writer; 12 | import java.text.SimpleDateFormat; 13 | import java.util.Calendar; 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | import java.util.regex.Matcher; 18 | import java.util.regex.Pattern; 19 | 20 | import org.apache.commons.io.FileUtils; 21 | import org.apache.commons.io.FilenameUtils; 22 | 23 | import net.sf.json.JSONArray; 24 | import net.sf.json.JSONObject; 25 | import pdfextract.Config.NormalizeInfo; 26 | 27 | /** 28 | * @author MickeyVI 29 | */ 30 | public class Common { 31 | Object _oLockerFile = new Object(); 32 | private int verbose = 1; 33 | 34 | public static boolean isWindows() { 35 | String os = System.getProperty("os.name").toLowerCase(); 36 | return (os.indexOf("win") >= 0); 37 | } 38 | 39 | public static boolean isMac() { 40 | String os = System.getProperty("os.name").toLowerCase(); 41 | return (os.indexOf("mac") >= 0); 42 | } 43 | 44 | public static boolean isUnix() { 45 | String os = System.getProperty("os.name").toLowerCase(); 46 | return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0); 47 | } 48 | 49 | public String getJarPath() { 50 | String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 51 | 52 | if (applicationDir.endsWith(".jar")) { 53 | String regex = "[/]([^\\/]+\\.jar)"; 54 | Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); 55 | Matcher m = p.matcher(applicationDir); 56 | String jar = ""; 57 | while (m.find()) { 58 | jar = m.group(1); 59 | } 60 | applicationDir = applicationDir.replace(jar, ""); 61 | } 62 | return applicationDir; 63 | } 64 | 65 | public String combine(String path1, String path2) { 66 | File file1 = new File(path1); 67 | File file2 = new File(file1, path2); 68 | String path = file2.getPath(); 69 | if (isWindows()) 70 | path = path.replace("/", "\\"); 71 | else 72 | path = path.replace("\\", "/"); 73 | return path; 74 | } 75 | 76 | public String readFile(String filePath) throws Exception { 77 | String data = ""; 78 | 79 | try { 80 | File file = new File(filePath); 81 | if (file.exists()) { 82 | 83 | @SuppressWarnings("resource") 84 | FileInputStream fin = new FileInputStream(file); 85 | byte fileContent[] = new byte[(int) file.length()]; 86 | fin.read(fileContent); 87 | data = new String(fileContent); 88 | } else 89 | return ""; 90 | } catch (Exception e) { 91 | e.printStackTrace(); 92 | throw e; 93 | } 94 | 95 | // remove bom 96 | data = data.replace("", ""); 97 | data = data.replace("\r\n", "\n"); 98 | data = data.replace("\r", "\n"); 99 | return data.replace("", ""); 100 | 101 | } 102 | 103 | @SuppressWarnings("deprecation") 104 | public List readLines(String filePath) throws Exception { 105 | return FileUtils.readLines(getFile(filePath)); 106 | } 107 | 108 | public void copyFileToFolder(File file, File folder) throws IOException { 109 | String newPath = combine(folder.getPath(), file.getName()); 110 | File fileNew = new File(newPath); 111 | if (fileNew.exists()) { 112 | fileNew.delete(); 113 | } 114 | FileUtils.copyFileToDirectory(file, folder); 115 | } 116 | 117 | public String getStr(Object obj) { 118 | try { 119 | if (obj == null) 120 | return ""; 121 | else 122 | return obj.toString(); 123 | 124 | } catch (Exception e) { 125 | return ""; 126 | } 127 | } 128 | 129 | public Boolean getBool(Object obj) { 130 | try { 131 | if (obj == null) 132 | return false; 133 | else { 134 | if (obj.toString().equals("1") || obj.toString().toLowerCase().trim().equals("true")) 135 | return true; 136 | else 137 | return Boolean.valueOf(obj.toString()); 138 | } 139 | 140 | } catch (Exception e) { 141 | return false; 142 | } 143 | } 144 | 145 | public int getInt(Object obj) { 146 | try { 147 | if (obj == null) 148 | return 0; 149 | else if (obj.equals("")) 150 | return 0; 151 | else 152 | return Integer.parseInt(obj.toString()); 153 | } catch (Exception e) { 154 | return 0; 155 | } 156 | } 157 | 158 | // Error handling #34 159 | public long getLong(Object obj) { 160 | try { 161 | if (obj.equals("")) 162 | return 0; 163 | else 164 | return Long.parseLong(obj.toString()); 165 | } catch (Exception e) { 166 | throw e; 167 | } 168 | } 169 | 170 | public float getFloat(Object obj) { 171 | try { 172 | if (obj == null) 173 | return 0; 174 | else if (obj == "") 175 | return 0; 176 | else 177 | return Float.parseFloat(obj.toString().trim()); 178 | 179 | } catch (Exception e) { 180 | return 0; 181 | } 182 | } 183 | 184 | public double getDouble(Object obj) { 185 | try { 186 | if (obj == null) 187 | return 0; 188 | else if (obj == "") 189 | return 0; 190 | else 191 | return Double.parseDouble(obj.toString().trim()); 192 | 193 | } catch (Exception e) { 194 | return 0; 195 | } 196 | } 197 | 198 | public boolean IsEmpty(Object object) { 199 | if (object == null) 200 | return true; 201 | 202 | if (object.toString().trim().length() == 0) 203 | return true; 204 | 205 | return false; 206 | } 207 | 208 | public boolean IsNull(Object object) { 209 | if (object == null) 210 | return true; 211 | 212 | return false; 213 | } 214 | 215 | public boolean IsExist(java.io.File file) { 216 | if (file != null && file.exists()) { 217 | return true; 218 | } else { 219 | return false; 220 | } 221 | } 222 | 223 | public boolean IsExist(String filepath) { 224 | File file = getFile(filepath); 225 | if (file != null && file.exists()) { 226 | return true; 227 | } else { 228 | return false; 229 | } 230 | } 231 | 232 | public boolean validateFile(String filepath) { 233 | File file = getFile(filepath); 234 | if (file != null && file.exists()) { 235 | if (!file.canWrite()) { 236 | return false; 237 | } 238 | /* Java lies on Windows */ 239 | try { 240 | new FileOutputStream(file, true).close(); 241 | } catch (IOException e) { 242 | return false; 243 | } 244 | return true; 245 | } else { 246 | try { 247 | file.createNewFile(); 248 | file.delete(); 249 | return true; 250 | } catch (Exception e) { 251 | return false; 252 | } 253 | } 254 | } 255 | 256 | public void createDir(String filepath) { 257 | getFile(filepath).mkdirs(); 258 | } 259 | 260 | public File getFile(String filepath) { 261 | return new File(filepath); 262 | } 263 | 264 | public String getExtension(String filepath) { 265 | return FilenameUtils.getExtension(filepath); 266 | } 267 | 268 | public String getName(String filepath) { 269 | return FilenameUtils.getName(filepath); 270 | } 271 | 272 | public String getBaseName(String filepath) { 273 | return FilenameUtils.getBaseName(filepath); 274 | } 275 | 276 | public String getParentPath(String filepath) { 277 | File file = getFile(filepath); 278 | if (file != null && file.getParentFile() != null) { 279 | return file.getParentFile().getPath(); 280 | } else { 281 | return ""; 282 | } 283 | } 284 | 285 | public void printHelp() { 286 | System.out.println("------------------------"); 287 | System.out.println("Arguments"); 288 | System.out.println("------------------------"); 289 | 290 | System.out.print("-I \t\t"); 291 | System.out.println("specifies the path to the source PDF file process for extraction."); 292 | 293 | System.out.print("-O \t"); 294 | System.out.println("specifies the path to the output HTML file after extraction."); 295 | 296 | System.out.print("-B \t\t"); 297 | System.out.println( 298 | "specifies the path to the batch file for processing list of files.\n\t\t\tThe input file and output file are specified on the same line delimited by a tab.\n\t\t\tEach line is delimited by a new line character."); 299 | 300 | System.out.print("-L \t\t"); 301 | System.out.println( 302 | "specifies the path to write the log file to.\n\t\t\tAs it is common for PDF files to have issues when processing\n\t\t\tsuch as being password protected or other forms of restricted permissions,\n\t\t\tthe log file can be written to a specifed location for additional processing.\n\t\t\tIf not specified, then the log file will write to stdout."); 303 | 304 | System.out.print("-T \t"); 305 | System.out.println( 306 | "specifies the number of threads to run concurrently when processing PDF files.\n\t\t\tOne file can be processed per thread. If not specified, then the default valur of 1 thread is used."); 307 | 308 | System.out.print("-v\t\t\t"); 309 | System.out.println("enables Verbose mode."); 310 | 311 | System.out.print("--keepbrtags\t\t"); 312 | System.out.println( 313 | "by default
is not included in the output. \n\t\t\tWhen this argument is specified, then the output will include the
tag after each line."); 314 | System.out.print("-S \t"); 315 | System.out.println("specifies the Sentence Join python script path."); 316 | 317 | System.out.print("-K \t\t"); 318 | System.out.println("specifies the Kenlm path."); 319 | System.out.println("------------------------"); 320 | } 321 | 322 | public void WriteFile(String filePath, String content) throws Exception { 323 | if (IsEmpty(filePath) || IsEmpty(content)) 324 | return; 325 | 326 | try { 327 | File file = new File(filePath); 328 | if (file.getParentFile() != null && (!IsExist(file.getParentFile()) || !file.getParentFile().isDirectory())) 329 | file.getParentFile().mkdirs(); 330 | 331 | FileUtils.writeStringToFile(file, content, "UTF-8", false); 332 | // FileUtils.writeStringToFile(file, content); 333 | } catch (Exception ex) { 334 | throw ex; 335 | } 336 | } 337 | 338 | public String getLogPath() { 339 | String jarPath = getJarPath(); 340 | String logPath = combine(jarPath, "Log"); 341 | 342 | return logPath; 343 | } 344 | 345 | public void writeLog(String path, String message) { 346 | writeLog(path, message, false); 347 | } 348 | 349 | public void writeLog(String path, String message, boolean isError) { 350 | writeLog(path, "", message, isError); 351 | } 352 | 353 | public void writeLog(String path, String inputfile, String message, boolean isError) { 354 | if (verbose == 1) { 355 | synchronized (_oLockerFile) { 356 | 357 | BufferedWriter oBuffer = null; 358 | try { 359 | 360 | // Get current date 361 | Calendar oCal = Calendar.getInstance(); 362 | // 363 | SimpleDateFormat oDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); 364 | String logfilepath = path; 365 | if (isWindows()) 366 | logfilepath = logfilepath.replace("/", "\\"); 367 | else 368 | logfilepath = logfilepath.replace("\\", "/"); 369 | 370 | File file = new File(logfilepath); 371 | if (file.getParent() != null) { 372 | File dir = new File(file.getParent()); 373 | if (!dir.exists()) { 374 | // create directory 375 | dir.mkdirs(); 376 | } 377 | } 378 | 379 | if (!IsEmpty(inputfile)) { 380 | message = "File: " + inputfile + ", " + message; 381 | } 382 | 383 | // Create or append file 384 | FileWriter oFileWriter = new FileWriter(logfilepath, true); 385 | oBuffer = new BufferedWriter(oFileWriter); 386 | String text = oDateTimeFormat.format(oCal.getTime()) + "\t" + (isError ? "ERROR" : "INFO") + "\t" 387 | + message; 388 | // 389 | oBuffer.write(text); 390 | oBuffer.newLine(); 391 | 392 | } catch (Exception ex) { 393 | ex.printStackTrace(); 394 | } finally { 395 | if (oBuffer != null) { 396 | try { 397 | oBuffer.close(); 398 | } catch (IOException ex) { 399 | ex.printStackTrace(); 400 | } 401 | } 402 | } 403 | } 404 | } 405 | } 406 | 407 | public void copyFile(String sorucePath, String targetPath) throws Exception { 408 | copyFile(getFile(sorucePath), getFile(targetPath)); 409 | } 410 | 411 | public void copyFile(File sourceFile, File targetFile) throws Exception { 412 | if (!sourceFile.exists()) { 413 | throw new Exception("File does not exist"); 414 | } 415 | 416 | if (targetFile.isDirectory()) { 417 | String filename = sourceFile.getName(); 418 | String targetFilePath = combine(targetFile.getPath(), filename); 419 | targetFile = new File(targetFilePath); 420 | } 421 | 422 | if (targetFile.exists()) 423 | targetFile.delete(); 424 | FileUtils.copyFile(sourceFile, targetFile); 425 | 426 | } 427 | 428 | public void moveFile(String sourcePath, String targetPath) throws Exception { 429 | moveFile(getFile(sourcePath), getFile(targetPath)); 430 | } 431 | 432 | public void moveFile(File sourceFile, File targetFile) throws Exception { 433 | if (!sourceFile.exists()) { 434 | throw new Exception("File does not exist"); 435 | } 436 | 437 | if (targetFile.isDirectory()) { 438 | String filename = sourceFile.getName(); 439 | String targetFilePath = combine(targetFile.getPath(), filename); 440 | targetFile = new File(targetFilePath); 441 | } 442 | 443 | if (targetFile.exists()) 444 | targetFile.delete(); 445 | FileUtils.moveFile(sourceFile, targetFile); 446 | 447 | } 448 | 449 | public void deleteFile(String filePath) { 450 | deleteFile(getFile(filePath)); 451 | } 452 | 453 | public void deleteFile(File file) { 454 | file.delete(); 455 | } 456 | 457 | public void checkPermissions(String path) { 458 | try { 459 | File file = getFile(path); 460 | file.setExecutable(true); 461 | file.setReadable(true); 462 | file.setWritable(true); 463 | } catch (Exception e) { 464 | } 465 | } 466 | 467 | public void print(String message) { 468 | print("", message); 469 | } 470 | 471 | public void print(String file, String message) { 472 | if (verbose == 1) { 473 | if (!IsEmpty(file)) { 474 | message = "File: " + file + ", " + message; 475 | } 476 | System.out.println(message); 477 | } 478 | } 479 | 480 | public void setVerbose(int val) { 481 | verbose = val; 482 | } 483 | 484 | public HashMap getSearchReplaceList() { 485 | HashMap list = new HashMap(); 486 | 487 | String searchReplacePath = combine(getJarPath(), "search-replace.tab"); 488 | if (IsExist(searchReplacePath)) { 489 | // 490 | try { 491 | List lines = readLines(searchReplacePath); 492 | 493 | for (int i = 0, len = lines.size(); i < len; i++) { 494 | String[] cols = lines.get(i).split("\t"); 495 | if (cols.length < 2) { 496 | continue; 497 | } 498 | list.put(cols[0], cols[1]); 499 | } 500 | 501 | } catch (Exception e) { 502 | 503 | } 504 | } 505 | 506 | return list; 507 | } 508 | 509 | public String getConfigPath() { 510 | return combine(getJarPath(), "PDFExtract.json"); 511 | } 512 | 513 | public String replaceText(HashMap hash, String text) { 514 | String rtext = text; 515 | if (hash != null && hash.size() > 0) { 516 | for (@SuppressWarnings("rawtypes") 517 | Map.Entry me : hash.entrySet()) { 518 | String search = me.getKey().toString(); 519 | String replace = me.getValue().toString(); 520 | 521 | // rtext = rtext.replaceAll(Pattern.quote(search), replace); 522 | rtext = rtext.replaceAll(search, replace); 523 | } 524 | } 525 | 526 | return rtext; 527 | } 528 | 529 | public String replaceText(List normalizeList, String text) { 530 | String rtext = text; 531 | if (normalizeList != null && normalizeList.size() > 0) { 532 | for (NormalizeInfo normalize : normalizeList) { 533 | String search = normalize.search; 534 | String replace = normalize.replace; 535 | 536 | // rtext = rtext.replaceAll(Pattern.quote(search), replace); 537 | rtext = rtext.replaceAll(search, replace); 538 | } 539 | } 540 | 541 | return rtext; 542 | } 543 | 544 | public String getStackTrace(UnsatisfiedLinkError e2) { 545 | String text = ""; 546 | Writer writer = null; 547 | try { 548 | writer = new StringWriter(); 549 | PrintWriter printWriter = new PrintWriter(writer); 550 | e2.printStackTrace(printWriter); 551 | text = writer.toString(); 552 | } catch (Exception e) { 553 | 554 | } finally { 555 | if (writer != null) { 556 | try { 557 | writer.close(); 558 | } catch (IOException e) { 559 | 560 | } 561 | } 562 | } 563 | return text; 564 | } 565 | 566 | public String getStackTrace(Exception exception) { 567 | String text = ""; 568 | Writer writer = null; 569 | try { 570 | writer = new StringWriter(); 571 | PrintWriter printWriter = new PrintWriter(writer); 572 | exception.printStackTrace(printWriter); 573 | text = writer.toString(); 574 | } catch (Exception e) { 575 | 576 | } finally { 577 | if (writer != null) { 578 | try { 579 | writer.close(); 580 | } catch (IOException e) { 581 | 582 | } 583 | } 584 | } 585 | return text; 586 | } 587 | 588 | public String getOutputError(Exception e) { 589 | 590 | StringBuffer html = new StringBuffer(""); 591 | html.append("" + "\n"); 592 | html.append("" + "\n"); 593 | html.append("" + "\n"); 594 | html.append("" + "\n"); 597 | html.append("" + "\n"); 598 | html.append("" + "\n"); 599 | html.append("" + "\n"); 602 | html.append("" + "\n"); 603 | html.append("" + "\n"); 604 | html.append("" + "\n"); 605 | 606 | return html.toString(); 607 | } 608 | 609 | public JSONObject getJSONFormat(String sData) { 610 | if (sData == null || sData.trim().length() == 0) 611 | return null; 612 | else 613 | return JSONObject.fromObject(sData); 614 | } 615 | 616 | public String getJSONValue(JSONObject json, String name) { 617 | if (json != null && json.has(name)) 618 | return json.getString(name); 619 | else 620 | return null; 621 | } 622 | 623 | public String getJSONValue(JSONObject json, String parentname, String name) { 624 | if (json != null && json.has(parentname)) { 625 | JSONObject jobj = json.getJSONObject(parentname); 626 | 627 | if (jobj != null && jobj.has(name)) { 628 | return jobj.getString(name); 629 | } else { 630 | return null; 631 | } 632 | } else 633 | return null; 634 | } 635 | 636 | public JSONObject getJSONObject(JSONObject json, String name) { 637 | if (json != null && json.has(name)) 638 | return json.getJSONObject(name); 639 | else 640 | return null; 641 | } 642 | 643 | public JSONObject getJSONObject(JSONObject json, String parentname, String name) { 644 | if (json != null && json.has(parentname)) { 645 | JSONObject jobj = json.getJSONObject(parentname); 646 | 647 | if (jobj != null && jobj.has(name)) { 648 | return jobj.getJSONObject(name); 649 | } else { 650 | return null; 651 | } 652 | } else 653 | return null; 654 | } 655 | 656 | public JSONArray getJSONArray(JSONObject json, String name) { 657 | if (json != null && json.has(name)) 658 | return json.getJSONArray(name); 659 | else 660 | return null; 661 | } 662 | 663 | public JSONArray getJSONArray(JSONObject json, String parentname, String name) { 664 | if (json != null && json.has(parentname)) { 665 | JSONObject jobj = json.getJSONObject(parentname); 666 | 667 | if (jobj != null && jobj.has(name)) { 668 | return jobj.getJSONArray(name); 669 | } else { 670 | return null; 671 | } 672 | } else 673 | return null; 674 | } 675 | 676 | } -------------------------------------------------------------------------------- /src/pdfextract/Config.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | import org.apache.commons.lang.StringUtils; 8 | 9 | import net.sf.json.JSONArray; 10 | import net.sf.json.JSONObject; 11 | 12 | /** 13 | * @author MickeyVI 14 | */ 15 | public class Config { 16 | 17 | private Common common = new Common(); 18 | private String _path = ""; 19 | private ConfigInfo _config = new ConfigInfo(); 20 | 21 | public Config(String path) throws Exception { 22 | _path = path; 23 | load(); 24 | } 25 | public Config(String path, String kenlmPath, String sentenceJoinPath) throws Exception { 26 | _path = path; 27 | load(kenlmPath, sentenceJoinPath); 28 | } 29 | 30 | private List getNormalizeList(JSONArray jArray) { 31 | List list = new ArrayList<>(); 32 | if (jArray != null) { 33 | for (int j = 0, jlen = jArray.size(); j < jlen; j++) { 34 | 35 | JSONArray jNormalize = (JSONArray) jArray.get(j); 36 | 37 | String left = jNormalize.getString(0); 38 | String right = jNormalize.getString(1); 39 | 40 | if (!common.IsEmpty(left) && right.length() > 0) { 41 | NormalizeInfo norm = new NormalizeInfo(); 42 | norm.search = left; 43 | norm.replace = right; 44 | list.add(norm); 45 | } 46 | } 47 | } 48 | return list; 49 | } 50 | 51 | private List getJoinWordsList(JSONArray jArray) { 52 | List list = new ArrayList<>(); 53 | if (jArray != null) { 54 | for (int j = 0, jlen = jArray.size(); j < jlen; j++) { 55 | 56 | JSONArray jNormalize = (JSONArray) jArray.get(j); 57 | 58 | String front = jNormalize.getString(0); 59 | String back = jNormalize.getString(1); 60 | String replace = jNormalize.getString(2); 61 | 62 | JoinWordInfo joinw = new JoinWordInfo(); 63 | joinw.front = front; 64 | joinw.back = back; 65 | joinw.joinText = replace; 66 | list.add(joinw); 67 | } 68 | } 69 | return list; 70 | } 71 | 72 | private List getEOFList(JSONArray jArray) { 73 | List list = new ArrayList<>(); 74 | if (jArray != null) { 75 | for (int j = 0, jlen = jArray.size(); j < jlen; j++) { 76 | 77 | JSONArray jEOF = (JSONArray) jArray.get(j); 78 | 79 | String front = jEOF.getString(0); 80 | String back = jEOF.getString(1); 81 | 82 | EOFInfo eofi = new EOFInfo(); 83 | eofi.front = front; 84 | eofi.back = back; 85 | list.add(eofi); 86 | } 87 | } 88 | return list; 89 | } 90 | 91 | private void load() throws Exception { 92 | load(null, null); 93 | } 94 | //#43 Add new arguments for -K, -S 95 | private void load(String kenlmPath, String sentenceJoinPath) throws Exception { 96 | if (!common.IsExist(_path)) { 97 | return; 98 | } 99 | 100 | String sConfig = common.readFile(_path); 101 | 102 | if (common.IsEmpty(sConfig)) { 103 | return; 104 | } 105 | 106 | JSONObject json = common.getJSONFormat(sConfig); 107 | JSONArray languages = common.getJSONArray(json, "language"); 108 | 109 | _config = new ConfigInfo(); 110 | 111 | if (!StringUtils.isEmpty(sentenceJoinPath) && common.IsExist(sentenceJoinPath)) { 112 | _config.sentenceJoinScript = sentenceJoinPath; 113 | }else { 114 | String sentenceJoinScript = common.getJSONValue(json, "script", "sentence_join"); 115 | _config.sentenceJoinScript = sentenceJoinScript; 116 | } 117 | if (!StringUtils.isEmpty(kenlmPath) && common.IsExist(kenlmPath)) { 118 | _config.kenlmPath = kenlmPath; 119 | } else { 120 | String sKenlmPath = common.getJSONValue(json, "script", "kenlm_path"); 121 | _config.kenlmPath = sKenlmPath; 122 | } 123 | 124 | for (int i = 0, len = languages.size(); i < len; i++) { 125 | JSONObject config = languages.getJSONObject(i); 126 | String lang = common.getJSONValue(config, "name"); 127 | JSONObject langConfigs = common.getJSONObject(config, "config"); 128 | 129 | JSONArray joinWords = common.getJSONArray(langConfigs, "join_words"); 130 | JSONArray absoluteEOF = common.getJSONArray(langConfigs, "absolute_eof"); 131 | JSONArray normalize = common.getJSONArray(langConfigs, "normalize"); 132 | JSONArray repair = common.getJSONArray(langConfigs, "repair"); 133 | String sentenceJoinModel = common.getJSONValue(langConfigs, "sentencejoin_model"); 134 | 135 | LangInfo langInfo = new LangInfo(); 136 | langInfo.language = lang; 137 | langInfo.joinWords.addAll(getJoinWordsList(joinWords)); 138 | langInfo.absoluteEOF.addAll(getEOFList(absoluteEOF)); 139 | langInfo.normalize.addAll(getNormalizeList(normalize)); 140 | langInfo.repair.addAll(getNormalizeList(repair)); 141 | langInfo.sentenceJoinModel = sentenceJoinModel; 142 | 143 | _config.langConfig.put(lang, langInfo); 144 | } 145 | } 146 | 147 | public LangInfo get(String lang) { 148 | if (_config != null && _config.langConfig != null) { 149 | LangInfo langInfo = _config.langConfig.get(lang); 150 | return langInfo; 151 | } 152 | return null; 153 | } 154 | 155 | public String getSentenceJoinScript() { 156 | if (_config != null && _config.sentenceJoinScript != null) { 157 | return _config.sentenceJoinScript; 158 | } 159 | return null; 160 | } 161 | 162 | public String getKenlmPath() { 163 | if (_config != null && _config.kenlmPath != null) { 164 | return _config.kenlmPath; 165 | } 166 | return null; 167 | } 168 | 169 | public static class ConfigInfo { 170 | public HashMap langConfig = new HashMap<>(); 171 | public String sentenceJoinScript = null; 172 | public String kenlmPath = null; 173 | 174 | } 175 | 176 | public static class LangInfo { 177 | public String language = ""; 178 | public List joinWords = new ArrayList<>(); 179 | public List absoluteEOF = new ArrayList<>(); 180 | public List normalize = new ArrayList<>(); 181 | public List repair = new ArrayList<>(); 182 | public String sentenceJoinModel = ""; 183 | } 184 | 185 | public static class NormalizeInfo { 186 | public String search = ""; 187 | public String replace = ""; 188 | } 189 | 190 | public static class JoinWordInfo { 191 | public String front = ""; 192 | public String back = ""; 193 | public String joinText = ""; 194 | } 195 | 196 | public static class EOFInfo { 197 | public String front = ""; 198 | public String back = ""; 199 | } 200 | } -------------------------------------------------------------------------------- /src/pdfextract/DetectLanguage.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import cz.vutbr.fit.knot.NNetLanguageIdentifierWrapper; 7 | import cz.vutbr.fit.knot.NNetLanguageIdentifierWrapper.Result; 8 | 9 | /** 10 | * @author MickeyVI 11 | */ 12 | public class DetectLanguage { 13 | 14 | NNetLanguageIdentifierWrapper identifier = null; 15 | Result[] result; 16 | 17 | String defaultLang = ""; 18 | int numLangs = 5; 19 | 20 | public DetectLanguage() { 21 | try { 22 | identifier = new NNetLanguageIdentifierWrapper(0, 1000); 23 | } catch (java.lang.UnsatisfiedLinkError | Exception e) { 24 | identifier = null; 25 | throw e; 26 | } 27 | } 28 | 29 | public List find(String text) { 30 | 31 | List resultlist = new ArrayList(); 32 | 33 | if (identifier != null) { 34 | result = identifier.findTopNMostFreqLangs(text, numLangs); 35 | if (result != null && result.length > 0) { 36 | for (Result prop : result) { 37 | if (prop.proportion > 0) { 38 | resultlist.add(new LanguageResult(prop.language, prop.proportion * 100, prop.isReliable)); 39 | } 40 | } 41 | } 42 | } 43 | 44 | return resultlist; 45 | } 46 | 47 | public class LanguageResult { 48 | public String language = ""; 49 | public float percent = 0; 50 | public boolean reliable = false; 51 | 52 | public LanguageResult(String language_, float percent_, boolean _realiable) { 53 | language = language_; 54 | percent = percent_; 55 | reliable = _realiable; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/pdfextract/HTMLObject.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | /** 8 | * @author MickeyVI 9 | */ 10 | public class HTMLObject { 11 | 12 | public static class BoxObject { 13 | public String color = ""; 14 | public float top; 15 | public float bottom; 16 | public float left; 17 | public float right; 18 | public float height; 19 | public float width; 20 | public String html; 21 | } 22 | 23 | public static class TextObject extends BoxObject { 24 | public String text = ""; 25 | public float fontsize = 0; 26 | public String fontfamily = ""; 27 | public String fontweight = ""; 28 | public String fontstyle = ""; 29 | public boolean islink = false; 30 | public float wordspacing = 0; 31 | public String class_ = ""; 32 | public boolean deleted = false; 33 | public String lang = ""; 34 | } 35 | 36 | public static class PageObject { 37 | public int pageno = 0; 38 | public float width = 0; 39 | public float height = 0; 40 | public List texts = new ArrayList(); 41 | public String language = ""; 42 | } 43 | 44 | public static class DocumentObject { 45 | public List pages = new ArrayList<>(); 46 | public float width = 0; 47 | public float height = 0; 48 | public String language = ""; 49 | public List langList = new ArrayList<>(); 50 | public List warningList = new ArrayList<>(); 51 | public AccessPermission permission = new AccessPermission(); 52 | public HashMap style = new HashMap(); 53 | } 54 | 55 | public static class LangObject { 56 | public String name = ""; 57 | public float percent = 0; 58 | public int count = 0; 59 | } 60 | 61 | public static class StyleObject { 62 | public String id = ""; 63 | public float size = 0; 64 | public String family = ""; 65 | public String color = ""; 66 | } 67 | 68 | public static class WarnObject { 69 | public WarnObject(String method_, String detail_) { 70 | method = method_; 71 | detail = detail_; 72 | 73 | } 74 | 75 | public WarnObject(String method_, String detail_, String solution_) { 76 | method = method_; 77 | solution = solution_; 78 | detail = detail_; 79 | 80 | } 81 | 82 | public String method = ""; 83 | public String solution = ""; 84 | public String detail = ""; 85 | } 86 | 87 | public static class AccessPermission { 88 | public boolean isEncrytped = false; 89 | public boolean canAssembly = false; 90 | public boolean canCopy = false; 91 | public boolean canPrint = false; 92 | public boolean canPrintDegraded = false; 93 | public boolean canModified = false; 94 | public boolean canModifyAnnotations = false; 95 | public boolean canFillInForm = false; 96 | public boolean canScreenReader = false; 97 | public String verbose = ""; 98 | } 99 | } -------------------------------------------------------------------------------- /src/pdfextract/PDFExtract.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.ByteArrayInputStream; 5 | import java.io.ByteArrayOutputStream; 6 | import java.io.InputStream; 7 | import java.io.InputStreamReader; 8 | import java.nio.charset.StandardCharsets; 9 | import java.util.ArrayList; 10 | import java.util.Collections; 11 | import java.util.Comparator; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | import java.util.Set; 16 | import java.util.UUID; 17 | import java.util.concurrent.ExecutorService; 18 | import java.util.concurrent.Executors; 19 | import java.util.concurrent.TimeUnit; 20 | import java.util.concurrent.atomic.AtomicReference; 21 | import java.util.regex.Matcher; 22 | import java.util.regex.Pattern; 23 | 24 | import org.apache.commons.io.IOUtils; 25 | import org.apache.commons.lang.StringUtils; 26 | 27 | import com.google.common.collect.Lists; 28 | import com.itextpdf.text.pdf.PdfEncryptor; 29 | import com.itextpdf.text.pdf.PdfReader; 30 | 31 | import pdfextract.Config.EOFInfo; 32 | import pdfextract.Config.JoinWordInfo; 33 | import pdfextract.Config.LangInfo; 34 | import pdfextract.Config.NormalizeInfo; 35 | import pdfextract.DetectLanguage.LanguageResult; 36 | import pdfextract.HTMLObject.DocumentObject; 37 | import pdfextract.HTMLObject.LangObject; 38 | import pdfextract.HTMLObject.PageObject; 39 | import pdfextract.HTMLObject.StyleObject; 40 | import pdfextract.HTMLObject.TextObject; 41 | import pdfextract.HTMLObject.WarnObject; 42 | import pdfextract.SentenceJoin.WorkerStatus; 43 | 44 | /** 45 | * @author MickeyVI 46 | */ 47 | public class PDFExtract { 48 | /** 49 | * Set for build with runnable or not 50 | */ 51 | private final boolean runnable = true; 52 | 53 | private String logPath = ""; 54 | private boolean writeLogFile = true; 55 | 56 | private Pattern patternPageOpen = Pattern.compile("]*>(.+?)<\\/a>.*"); 71 | private Pattern patternWord = Pattern.compile("]*>(.*?)<\\/text>"); 72 | 73 | private Common common = new Common(); 74 | private ExecutorService executor; 75 | 76 | private PDFToHtml pdf = null; 77 | private String paraMarker = "LSMARKERLS:PARA"; 78 | private int maxWordsJoin = 5; 79 | 80 | private Object _objectWorker = new Object(); 81 | private HashMap _hashSentenceJoin = new HashMap<>(); 82 | private Config config = null; 83 | 84 | private void initial(String logFilePath, int verbose, String configFile, long timeout) throws Exception { 85 | initial(logFilePath, verbose, configFile, timeout, null, null); 86 | } 87 | private void initial(String logFilePath, int verbose, String configFile, long timeout, String kenlmPath, String sentenceJoinPath) throws Exception { 88 | common.setVerbose(verbose); 89 | if (common.IsEmpty(logFilePath)) { 90 | writeLogFile = false; 91 | } else { 92 | 93 | if (common.IsEmpty(common.getExtension(logFilePath))) { 94 | logFilePath += ".log"; 95 | } 96 | 97 | /** 98 | * Validate log file 99 | */ 100 | boolean logFileValid = common.validateFile(logFilePath); 101 | if (!logFileValid) { 102 | throw new Exception("Invalid log file path or permission denied."); 103 | } 104 | 105 | writeLogFile = true; 106 | 107 | logPath = logFilePath; 108 | 109 | if (runnable) 110 | common.print("Log File: " + logPath); 111 | } 112 | 113 | try { 114 | if (common.IsEmpty(configFile) || !common.IsExist(configFile)) { 115 | configFile = common.getConfigPath(); 116 | } 117 | config = new Config(configFile, kenlmPath, sentenceJoinPath); 118 | } catch (Exception e) { 119 | throw new Exception("initial failed. " + e.getMessage()); 120 | } 121 | 122 | pdf = new PDFToHtml(timeout); 123 | 124 | } 125 | 126 | /** 127 | * Initializes a newly created PDFExtract object. 128 | * 129 | * @throws Exception 130 | */ 131 | public PDFExtract() throws Exception { 132 | initial("", 0, "", 0); 133 | } 134 | 135 | /** 136 | * Initializes a newly created PDFExtract object. 137 | * 138 | * @param configFile The path for configuration file 139 | * @throws Exception 140 | */ 141 | public PDFExtract(String configFile) throws Exception { 142 | initial("", 0, configFile, 0); 143 | } 144 | 145 | /** 146 | * Initializes a newly created PDFExtract object. 147 | * 148 | * @param timeout The maximum time wait in seconds for poppler extract 149 | * @throws Exception 150 | */ 151 | public PDFExtract(long timeout) throws Exception { 152 | initial("", 0, "", timeout); 153 | } 154 | 155 | /** 156 | * Initializes a newly created PDFExtract object. 157 | * 158 | * @param configFile The path for configuration file 159 | * @param timeout The maximum time wait in seconds for poppler extract 160 | * @throws Exception 161 | */ 162 | public PDFExtract(String configFile, long timeout) throws Exception { 163 | initial("", 0, configFile, timeout); 164 | } 165 | 166 | /** 167 | * Initializes a newly created PDFExtract object. 168 | * 169 | * @param logFilePath The path to write the log file to. 170 | * @param configFile The path for configuration file 171 | * @param timeout The maximum time wait in seconds for poppler extract 172 | * @throws Exception 173 | */ 174 | public PDFExtract(String logFilePath, String configFile, long timeout) throws Exception { 175 | initial(logFilePath, 0, configFile, timeout); 176 | } 177 | 178 | /** 179 | * Initializes a newly created PDFExtract object. 180 | * 181 | * @param logFilePath The path to write the log file to. 182 | * @param verbose Print the information to stdout (1=print, 0=silence) 183 | * @param configFile The path for configuration file 184 | * @param timeout The maximum time wait in seconds for poppler extract 185 | * @throws Exception 186 | */ 187 | public PDFExtract(String logFilePath, int verbose, String configFile, long timeout) throws Exception { 188 | initial(logFilePath, verbose, configFile, timeout); 189 | } 190 | //#43 Add new arguments for -K, -S 191 | public PDFExtract(String logFilePath, int verbose, String configFile, long timeout, String kenlmPath, String sentenceJoinPath) throws Exception { 192 | initial(logFilePath, verbose, configFile, timeout, kenlmPath, sentenceJoinPath); 193 | } 194 | 195 | /** 196 | * PDFExtract is a PDF parser that converts and extracts PDF content into a HTML 197 | * format that is optimized for easy alignment across multiple language sources. 198 | * 199 | * @param inputFile The path to the source PDF file process for extraction 200 | * @param outputFile The path to the output HTML file after extraction 201 | * @param keepBrTags By default
202 | * is not included in the output. When this argument is 203 | * specified, then the output will include the
204 | * tag after each line. 205 | * @param getPermission By default the permissions is not included in the 206 | * output. When this argument is specified, then the output 207 | * will include permissions tag into header section. 208 | */ 209 | public void Extract(String inputFile, String outputFile, int keepBrTags, int getPermission) throws Exception { 210 | 211 | String outputPath = ""; 212 | UUID uuid = UUID.randomUUID(); 213 | try { 214 | if (writeLogFile) { 215 | if (runnable) 216 | common.print(inputFile, "Start extract"); 217 | common.writeLog(logPath, inputFile, "Start extract", false); 218 | } else { 219 | common.print(inputFile, "Start extract"); 220 | } 221 | 222 | /** 223 | * Check input file exists 224 | */ 225 | if (!common.IsExist(inputFile)) { 226 | throw new Exception("Input file does not exist."); 227 | } 228 | 229 | /** 230 | * Check output file not empty 231 | */ 232 | if (common.IsEmpty(outputFile)) { 233 | throw new Exception("Output file cannot be empty."); 234 | } 235 | 236 | /** 237 | * Get output directory from outputFile and create it if not exists 238 | */ 239 | outputPath = common.getParentPath(outputFile); 240 | if (!common.IsEmpty(outputPath) && !common.IsExist(outputPath)) { 241 | common.createDir(outputPath); 242 | } 243 | 244 | if (runnable) { 245 | /** 246 | * Check input file permission 247 | */ 248 | common.checkPermissions(inputFile); 249 | } 250 | 251 | /** 252 | * Check input file extension 253 | */ 254 | if (!common.getExtension(inputFile).toLowerCase().equals("pdf")) { 255 | throw new Exception("Input file extension is not pdf."); 256 | } 257 | 258 | StringBuffer htmlBuffer = new StringBuffer(""); 259 | AtomicReference refDoc = new AtomicReference(new DocumentObject()); 260 | 261 | if (getPermission == 1) { 262 | /** 263 | * get pdf access permission 264 | */ 265 | getAccessPermissions(inputFile, refDoc); 266 | } 267 | 268 | /** 269 | * Call function to convert PDF to HTML 270 | */ 271 | htmlBuffer = convertPdfToHtml(inputFile); 272 | // common.writeLog(logPath, htmlBuffer.toString(), false); 273 | 274 | getHtmlObject(htmlBuffer, refDoc); 275 | 276 | /** 277 | * Call function to repair & adjustment 278 | */ 279 | repairAndAdjustment(refDoc); 280 | 281 | /** 282 | * Call function to do language id 283 | */ 284 | languageId(refDoc); 285 | 286 | /** 287 | * Call function to join sentence 288 | */ 289 | sentenceJoin(uuid.toString(), refDoc); 290 | 291 | /** 292 | * Call function to final repair 293 | */ 294 | finalRepair(refDoc); 295 | 296 | /** 297 | * Call function to generate html output 298 | */ 299 | htmlBuffer = generateOutput(refDoc, keepBrTags, getPermission); 300 | 301 | /** 302 | * Write to output file. 303 | */ 304 | common.WriteFile(outputFile, htmlBuffer.toString()); 305 | 306 | if (writeLogFile) { 307 | if (runnable) 308 | common.print(inputFile, "Extract success. -> " + outputFile + ""); 309 | common.writeLog(logPath, inputFile, "Extract success. -> " + outputFile + "", false); 310 | } else { 311 | common.print(inputFile, "Extract success. -> " + outputFile + ""); 312 | } 313 | 314 | } catch (Exception e) { 315 | 316 | if (!common.IsEmpty(outputFile)) { 317 | common.WriteFile(outputFile, common.getOutputError(e)); 318 | } 319 | 320 | String message = e.getMessage(); 321 | if (writeLogFile) { 322 | common.writeLog(logPath, inputFile, "Error: " + message, true); 323 | } else { 324 | if (!runnable) 325 | common.print(inputFile, "Error: " + message); 326 | } 327 | 328 | throw e; 329 | } finally { 330 | // Fix issue #57 Sentence join fails when using a batch file: Checking the model has been being used or not before terminate the model. 331 | shutdownProcess(uuid.toString()); 332 | } 333 | } 334 | 335 | /** 336 | * PDFExtract is a PDF parser that converts and extracts PDF content into a HTML 337 | * format that is optimized for easy alignment across multiple language sources. 338 | * 339 | * @param inputStream Stream data as ByteArray for extraction 340 | * @param keepBrTags By default
341 | * is not included in the output. When this argument is 342 | * specified, then the output will include the
343 | * tag after each line. 344 | * 345 | * @return ByteArrayOutputStream Stream Out 346 | */ 347 | public ByteArrayOutputStream Extract(ByteArrayInputStream inputStream, int keepBrTags, int getPermission) 348 | throws Exception { 349 | UUID uuid = UUID.randomUUID(); 350 | try { 351 | if (writeLogFile) { 352 | if (runnable) 353 | common.print("Input Stream", "Start extract"); 354 | common.writeLog(logPath, "Input Stream", "Start extract", false); 355 | } else { 356 | common.print("Input Stream", "Start extract"); 357 | } 358 | 359 | /** 360 | * Check input stream can be read ? 361 | */ 362 | if (inputStream.available() <= 0) { 363 | throw new Exception("Input Stream does not exist."); 364 | } 365 | 366 | StringBuffer htmlBuffer; 367 | AtomicReference refDoc = new AtomicReference(new DocumentObject()); 368 | 369 | if (getPermission == 1) { 370 | /** 371 | * get pdf access permission 372 | */ 373 | getAccessPermissions(inputStream, refDoc); 374 | } 375 | 376 | /** 377 | * Call function to paint html box 378 | */ 379 | htmlBuffer = convertPdfToHtml(inputStream); 380 | getHtmlObject(htmlBuffer, refDoc); 381 | 382 | /** 383 | * Call function to repair & adjustment 384 | */ 385 | repairAndAdjustment(refDoc); 386 | 387 | /** 388 | * Call function to do language id 389 | */ 390 | languageId(refDoc); 391 | 392 | /** 393 | * Call function to join sentence 394 | */ 395 | sentenceJoin(uuid.toString(), refDoc); 396 | 397 | /** 398 | * Call function to generate html output 399 | */ 400 | htmlBuffer = generateOutput(refDoc, keepBrTags, getPermission); 401 | 402 | /** 403 | * Write output stream 404 | */ 405 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 406 | IOUtils.write(htmlBuffer.toString(), outputStream, "UTF-8"); 407 | 408 | if (writeLogFile) { 409 | if (runnable) 410 | common.print("Input Stream", "Extract success."); 411 | common.writeLog(logPath, "Input Stream", "Extract success.", false); 412 | } else { 413 | common.print("Input Stream", "Extract success."); 414 | } 415 | 416 | return outputStream; 417 | } catch (Exception e) { 418 | 419 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 420 | IOUtils.write(common.getOutputError(e), outputStream, "UTF-8"); 421 | 422 | String message = e.getMessage(); 423 | if (writeLogFile) { 424 | common.writeLog(logPath, "Input Stream", "Error: " + message, true); 425 | } else { 426 | common.print("Input Stream", "Error: " + message); 427 | } 428 | 429 | throw e; 430 | } finally { 431 | // Fix issue #57 Sentence join fails when using a batch file: Checking the model has been being used or not before terminate the model. 432 | shutdownProcess(uuid.toString()); 433 | } 434 | } 435 | 436 | /** 437 | * PDFExtract is a PDF parser that converts and extracts PDF content into a HTML 438 | * format that is optimized for easy alignment across multiple language sources. 439 | * 440 | * @param batchFile The path to the batch file for processing list of files. 441 | * The input file and output file are specified on the same 442 | * line delimited by a tab. Each line is delimited by a new 443 | * line character. 444 | * @param threadCount The number of threads to run concurrently when processing 445 | * PDF files. One file can be processed per thread. If not 446 | * specified, then the default valur of 1 thread is used. 447 | * @param keepBrTags By default
448 | * is not included in the output. When this argument is 449 | * specified, then the output will include the
450 | * tag after each line. 451 | * 452 | */ 453 | public void Extract(String batchFile, int threadCount, int keepBrTags, int getPermission) throws Exception { 454 | try { 455 | if (writeLogFile) { 456 | if (runnable) 457 | common.print("Start extract batch file: " + batchFile); 458 | common.writeLog(logPath, "Start extract batch file: " + batchFile); 459 | } else { 460 | common.print("Start extract batch file: " + batchFile); 461 | } 462 | 463 | /** 464 | * Check input file exists 465 | */ 466 | if (!common.IsExist(batchFile)) { 467 | throw new Exception("Input batch file does not exist."); 468 | } 469 | 470 | if (threadCount == 0) 471 | threadCount = 1; 472 | int maxThreadCount = threadCount; 473 | 474 | /** 475 | * Read batch file 476 | */ 477 | List lines = common.readLines(batchFile); 478 | executor = Executors.newFixedThreadPool(maxThreadCount); 479 | 480 | int ind = 0, len = lines.size(); 481 | while (ind < len) { 482 | String line = lines.get(ind); 483 | 484 | /** 485 | * Skip the empty line 486 | */ 487 | if (common.IsEmpty(line)) { 488 | ind++; 489 | continue; 490 | } 491 | 492 | AddThreadExtract(ind, line, keepBrTags, getPermission); 493 | ind++; 494 | } 495 | executor.shutdown(); 496 | executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); 497 | 498 | } catch (Exception e) { 499 | String message = e.getMessage(); 500 | if (writeLogFile) { 501 | common.writeLog(logPath, message, true); 502 | } else { 503 | common.print("Error: " + e.getMessage()); 504 | } 505 | throw e; 506 | } finally { 507 | if (writeLogFile) { 508 | if (runnable) 509 | common.print("Finish extract batch file: " + batchFile); 510 | common.writeLog(logPath, "Finish extract batch file: " + batchFile); 511 | } else { 512 | common.print("Finish extract batch file: " + batchFile); 513 | } 514 | shutdownProcess(); 515 | } 516 | } 517 | 518 | /** 519 | * Add new thread pdf extract 520 | */ 521 | private void AddThreadExtract(int index, String line, int keepBrTags, int getPermission) { 522 | try { 523 | executor.execute(new Runnable() { 524 | @Override 525 | public void run() { 526 | String inputFile = "", outputFile = ""; 527 | try { 528 | 529 | /** 530 | * Validate line to process 531 | */ 532 | String[] cols = line.split("\t"); 533 | 534 | if (cols == null || cols.length < 2) { 535 | throw new Exception("Invalid batch line: " + line); 536 | } 537 | inputFile = cols[0]; 538 | outputFile = cols[1]; 539 | 540 | /** 541 | * Call function to extract 542 | */ 543 | Extract(inputFile, outputFile, keepBrTags, getPermission); 544 | 545 | } catch (Exception e) { 546 | String message = e.getMessage(); 547 | if (writeLogFile) { 548 | if (runnable) 549 | common.print(inputFile, "Error: " + message); 550 | common.writeLog(logPath, inputFile, "Error: " + message, true); 551 | } else { 552 | if (!runnable) 553 | common.print(inputFile, "Error: " + message); 554 | } 555 | } 556 | } 557 | }); 558 | 559 | } catch (Exception ex) { 560 | String message = ex.toString(); 561 | if (writeLogFile) { 562 | if (runnable) 563 | common.print("Batch line: " + line + ", Error: " + message); 564 | common.writeLog(logPath, "Batch line: " + line + ", Error: " + message, true); 565 | } else { 566 | common.print("Batch line: " + line + ", Error: " + message); 567 | } 568 | } 569 | } 570 | 571 | /** 572 | * Get permissions 573 | */ 574 | private void getAccessPermissions(String inputFile, AtomicReference refDoc) throws Exception { 575 | DocumentObject doc = refDoc.get(); 576 | PdfReader reader = null; 577 | try { 578 | reader = new PdfReader(inputFile); 579 | setAccessPermissions(reader, refDoc); 580 | if (!doc.permission.canCopy) { 581 | pdf.decrypt(reader, inputFile); 582 | } 583 | } catch (Exception e) { 584 | throw e; 585 | } finally { 586 | if (reader != null) { 587 | reader.close(); 588 | reader = null; 589 | } 590 | } 591 | } 592 | 593 | private void getAccessPermissions(InputStream inputStream, AtomicReference refDoc) 594 | throws Exception { 595 | PdfReader reader = null; 596 | try { 597 | reader = new PdfReader(inputStream); 598 | setAccessPermissions(reader, refDoc); 599 | } catch (Exception e) { 600 | throw e; 601 | } finally { 602 | if (reader != null) { 603 | reader.close(); 604 | reader = null; 605 | } 606 | } 607 | } 608 | 609 | private void setAccessPermissions(PdfReader reader, AtomicReference refDoc) { 610 | DocumentObject doc = refDoc.get(); 611 | // 612 | PdfReader.unethicalreading = true; 613 | int permissions = (int) reader.getPermissions(); 614 | // 615 | doc.permission.isEncrytped = reader.isEncrypted(); 616 | doc.permission.canAssembly = PdfEncryptor.isAssemblyAllowed(permissions); 617 | doc.permission.canCopy = PdfEncryptor.isCopyAllowed(permissions); 618 | doc.permission.canPrint = PdfEncryptor.isPrintingAllowed(permissions); 619 | doc.permission.canPrintDegraded = PdfEncryptor.isDegradedPrintingAllowed(permissions); 620 | doc.permission.canModified = PdfEncryptor.isModifyContentsAllowed(permissions); 621 | doc.permission.canModifyAnnotations = PdfEncryptor.isModifyAnnotationsAllowed(permissions); 622 | doc.permission.canFillInForm = PdfEncryptor.isFillInAllowed(permissions); 623 | doc.permission.canScreenReader = PdfEncryptor.isScreenReadersAllowed(permissions); 624 | doc.permission.verbose = PdfEncryptor.getPermissionsVerbose(permissions); 625 | } 626 | 627 | /** 628 | * Convert PDF to HTML file 629 | */ 630 | private StringBuffer convertPdfToHtml(String inputFile) throws Exception { 631 | return pdf.extract(inputFile); 632 | } 633 | 634 | /** 635 | * Convert PDF to HTML file 636 | */ 637 | private StringBuffer convertPdfToHtml(ByteArrayInputStream inputStream) throws Exception { 638 | return pdf.extract(inputStream); 639 | } 640 | 641 | /** 642 | * Get HTML Object Parse data to HTML Object 643 | */ 644 | private void getHtmlObject(StringBuffer htmlBuffer, AtomicReference refDoc) throws Exception { 645 | BufferedReader b_in = null; 646 | DocumentObject doc = refDoc.get(); 647 | 648 | try { 649 | 650 | InputStreamReader i_in = new InputStreamReader(new ByteArrayInputStream(htmlBuffer.toString().getBytes()), 651 | StandardCharsets.UTF_8); 652 | b_in = new BufferedReader(i_in); 653 | String line = ""; 654 | int currentPage = 0; 655 | PageObject page = new PageObject(); 656 | HashMap mapPageWidth = new HashMap(); 657 | HashMap mapPageHeight = new HashMap(); 658 | HashMap mapStyle = new HashMap(); 659 | 660 | while ((line = b_in.readLine()) != null) { 661 | 662 | Matcher mStyleOpen = this.patternStyleOpen.matcher(line); 663 | Matcher patternText = this.patternText.matcher(line); 664 | Matcher mPageOpen = this.patternPageOpen.matcher(line); 665 | 666 | if (patternText.find()) { 667 | 668 | /** 669 | * New text found, call function to get a text object and add into the page 670 | */ 671 | TextObject text = getTextObject(line, mapStyle); 672 | if (!checkLineAdd(page.width, page.height, text)) { 673 | continue; 674 | } 675 | page.texts.add(text); 676 | 677 | } else if (mPageOpen.find()) { 678 | 679 | if (currentPage > 0) { 680 | doc.pages.add(page); 681 | Thread.sleep(50); 682 | } 683 | currentPage++; 684 | page = new PageObject(); 685 | 686 | /** 687 | * New page found, extract page number, width and height of the page 688 | */ 689 | page.pageno = common.getInt(patternPageNo.matcher(line).replaceAll("$1")); 690 | page.height = common.getFloat(patternHeight.matcher(line).replaceAll("$1")); 691 | page.width = common.getFloat(patternWidth.matcher(line).replaceAll("$1")); 692 | 693 | mapPageWidth.put(page.width, common.getInt(mapPageWidth.get(page.width)) + 1); 694 | mapPageHeight.put(page.height, common.getInt(mapPageHeight.get(page.height)) + 1); 695 | 696 | } else if (mStyleOpen.find()) { 697 | 698 | /** 699 | * Collect new style into the list 700 | */ 701 | StyleObject style = new StyleObject(); 702 | style.id = common.getStr(patternId.matcher(line).replaceAll("$1")); 703 | style.size = common.getInt(patternSize.matcher(line).replaceAll("$1")); 704 | style.family = common.getStr(patternFamily.matcher(line).replaceAll("$1")); 705 | style.color = common.getStr(patternColor.matcher(line).replaceAll("$1")); 706 | mapStyle.put(style.id, style); 707 | 708 | } 709 | } 710 | 711 | doc.pages.add(page); 712 | doc.style = mapStyle; 713 | 714 | /** 715 | * Get most width and height of the document 716 | */ 717 | doc.width = getMaxCount(mapPageWidth); 718 | doc.height = getMaxCount(mapPageHeight); 719 | 720 | } finally { 721 | if (b_in != null) { 722 | b_in.close(); 723 | b_in = null; 724 | } 725 | refDoc.set(doc); 726 | } 727 | 728 | } 729 | 730 | /** 731 | * Repair and adjust text with the common rules 732 | */ 733 | private void repairAndAdjustment(AtomicReference refDoc) throws Exception { 734 | 735 | DocumentObject doc = refDoc.get(); 736 | try { 737 | 738 | LangInfo commonInfo = null; 739 | if (config != null) { 740 | commonInfo = config.get("common"); 741 | } 742 | 743 | HashMap mapStyleCount = new HashMap(); 744 | 745 | /** 746 | * Get height + normalize text 747 | */ 748 | for (PageObject page : doc.pages) { 749 | 750 | HashMap mapHeight = new HashMap(); 751 | for (int i = 0, len = page.texts.size(); i < len; i++) { 752 | TextObject text = page.texts.get(i); 753 | 754 | if (common.IsEmpty(text.text)) { 755 | text.deleted = true; 756 | continue; 757 | } 758 | 759 | if (!common.IsEmpty(text.class_)) { 760 | int count = 0; 761 | if (mapStyleCount.containsKey(text.class_)) { 762 | count = mapStyleCount.get(text.class_); 763 | } 764 | mapStyleCount.put(text.class_, count + 1); 765 | } 766 | 767 | if (text.height > 0) { 768 | int count = 0; 769 | if (mapHeight.containsKey(text.height)) { 770 | count = mapHeight.get(text.height); 771 | } 772 | mapHeight.put(text.height, count + 1); 773 | } 774 | if (commonInfo != null) { 775 | text.text = common.replaceText(commonInfo.normalize, text.text).trim(); 776 | } 777 | 778 | 779 | } 780 | 781 | } 782 | 783 | // Get Most Style of Document. 784 | String keyMostStyle = getMaxLangCount(mapStyleCount); 785 | StyleObject mostStyle = doc.style.get(keyMostStyle); 786 | 787 | /** 788 | * Check top to merge line 789 | */ 790 | for (PageObject page : doc.pages) { 791 | 792 | for (int i = 0, len = page.texts.size(); i < len; i++) { 793 | TextObject text = page.texts.get(i); 794 | 795 | if (text.deleted) 796 | continue; 797 | if (common.IsEmpty(text.text)) { 798 | text.deleted = true; 799 | continue; 800 | } 801 | 802 | StringBuffer sb = new StringBuffer(text.text.trim()); 803 | boolean hasUpdated = false; 804 | if (i + 1 < len) { 805 | for (int j = i + 1; j < len; j++) { 806 | TextObject nextText = page.texts.get(j); 807 | 808 | if (text.deleted) 809 | continue; 810 | if (common.IsEmpty(nextText.text)) { 811 | nextText.deleted = true; 812 | continue; 813 | } 814 | 815 | if (!isMergeTop(text, nextText)) { 816 | i = j - 1; 817 | break; 818 | } else { 819 | 820 | // merge 821 | sb.append(" " + nextText.text.trim()); 822 | if (nextText.islink ) { 823 | text.color = mostStyle.color; 824 | text.fontfamily = mostStyle.family; 825 | text.class_ = mostStyle.id; 826 | } 827 | if (nextText.top < text.top) 828 | text.top = nextText.top; 829 | if (nextText.bottom > text.bottom) 830 | text.bottom = nextText.bottom; 831 | // Change font if nextext is larger than text. 832 | if (nextText.text.length() > text.text.length()) { 833 | text.fontfamily = nextText.fontfamily; 834 | text.color = nextText.color; 835 | text.class_ = nextText.class_; 836 | } 837 | text.right = nextText.right; 838 | text.width = text.right - text.left; 839 | text.height = text.bottom - text.top; 840 | nextText.deleted = true; 841 | hasUpdated = true; 842 | 843 | } 844 | } 845 | 846 | if (hasUpdated) { 847 | text.text = sb.toString(); 848 | } 849 | } 850 | 851 | } 852 | } 853 | 854 | /** 855 | * Adding paragraph separator 856 | */ 857 | for (PageObject page : doc.pages) { 858 | List newTexts = new ArrayList(); 859 | float fLineSpace = new Float("-99.0"); 860 | 861 | for (int i = 0, len = page.texts.size(); i < len; i++) { 862 | TextObject text = page.texts.get(i); 863 | 864 | if (text.deleted) 865 | continue; 866 | if (common.IsEmpty(text.text)) 867 | continue; 868 | newTexts.add(text); 869 | 870 | if (i + 1 < len) { 871 | for (int j = i + 1; j < len; j++) { 872 | TextObject nextText = page.texts.get(j); 873 | 874 | if (nextText.deleted) { 875 | continue; 876 | } 877 | 878 | if (common.IsEmpty(nextText.text)) { 879 | continue; 880 | } 881 | 882 | if (text.text.trim().endsWith(",") && isClassChanged(text, nextText)) { 883 | newTexts.add(getNewText(paraMarker)); 884 | fLineSpace = -1.0f; 885 | } 886 | else 887 | if (isTooFar(text, nextText, fLineSpace) 888 | || isFontChanged(text, nextText) 889 | ){ 890 | newTexts.add(getNewText(paraMarker)); 891 | fLineSpace = -1.0f; 892 | }// Separate paragraph if font style is difference. 893 | else if (!text.fontfamily.equals(nextText.fontfamily) 894 | && text.text.length() > 6 895 | && nextText.text.length() > 6) { 896 | newTexts.add(getNewText(paraMarker)); 897 | fLineSpace = -1.0f; 898 | } 899 | else { 900 | if (fLineSpace < 0) 901 | fLineSpace = nextText.top - text.top; 902 | } 903 | break; 904 | } 905 | } else { 906 | newTexts.add(getNewText(paraMarker)); 907 | } 908 | 909 | } 910 | 911 | page.texts.clear(); 912 | page.texts.addAll(newTexts); 913 | 914 | } 915 | 916 | /** 917 | * Merge sentence 918 | */ 919 | List joinList = new ArrayList<>(); 920 | List eofList = new ArrayList<>(); 921 | 922 | if (config != null && config.get("common") != null) { 923 | joinList = config.get("common").joinWords; 924 | eofList = config.get("common").absoluteEOF; 925 | } 926 | 927 | for (PageObject page : doc.pages) { 928 | 929 | for (int i = 0, len = page.texts.size(); i < len; i++) { 930 | TextObject text = page.texts.get(i); 931 | 932 | if (text.deleted) 933 | continue; 934 | if (text.text.equals(paraMarker)) 935 | continue; 936 | 937 | boolean isJoin = false; 938 | if (i + 1 < len) { 939 | for (int j = i + 1; j < len; j++) { 940 | TextObject nextText = page.texts.get(j); 941 | 942 | if (nextText.deleted) 943 | continue; 944 | if (nextText.text.equals(paraMarker)) 945 | break; 946 | if (!text.lang.equals(nextText.lang)) 947 | break; 948 | 949 | boolean isEOF = false; 950 | // absolute_eof 951 | for (EOFInfo rule : eofList) { 952 | if (!common.IsEmpty(rule.front) && !common.IsEmpty(rule.back)) { 953 | if (text.text.matches(rule.front) && nextText.text.matches(rule.back)) 954 | isEOF = true; 955 | } else if (!common.IsEmpty(rule.front)) { 956 | if (text.text.matches(rule.front)) 957 | isEOF = true; 958 | } else if (!common.IsEmpty(rule.back)) { 959 | if (nextText.text.matches(rule.back)) 960 | isEOF = true; 961 | } 962 | 963 | if (isEOF) { 964 | isJoin = false; 965 | break; 966 | } 967 | } 968 | 969 | if (!isEOF) { 970 | // join_words 971 | for (JoinWordInfo rule : joinList) { 972 | if (!common.IsEmpty(rule.front) && !common.IsEmpty(rule.back)) { 973 | if (text.text.matches(rule.front) && nextText.text.matches(rule.back)) 974 | isJoin = true; 975 | } else if (!common.IsEmpty(rule.front)) { 976 | if (text.text.matches(rule.front)) 977 | isJoin = true; 978 | } else if (!common.IsEmpty(rule.back)) { 979 | if (nextText.text.matches(rule.back)) 980 | isJoin = true; 981 | } 982 | 983 | if (isJoin) { 984 | text.text += rule.joinText + nextText.text; 985 | nextText.deleted = true; 986 | break; 987 | } 988 | } 989 | } 990 | 991 | if (!isJoin) { 992 | i = j - 1; 993 | break; 994 | } 995 | } 996 | } 997 | 998 | } 999 | } 1000 | 1001 | } finally { 1002 | refDoc.set(doc); 1003 | } 1004 | } 1005 | 1006 | /** 1007 | * Detect language + normalize text with language rules 1008 | */ 1009 | private void languageId(AtomicReference refDoc) { 1010 | DocumentObject doc = refDoc.get(); 1011 | try { 1012 | DetectLanguage detectLang = null; 1013 | try { 1014 | detectLang = new DetectLanguage(); 1015 | } catch (java.lang.UnsatisfiedLinkError e) { 1016 | doc.warningList.add(new WarnObject("languageId", common.getStackTrace(e))); 1017 | } catch (java.lang.Exception e) { 1018 | doc.warningList.add(new WarnObject("languageId", common.getStackTrace(e))); 1019 | } 1020 | 1021 | if (detectLang == null) 1022 | return; 1023 | 1024 | List normalizeList = new ArrayList<>(); 1025 | LangInfo langInfo = new LangInfo(); 1026 | 1027 | // language id 1028 | HashMap mapLang = new HashMap<>(); 1029 | 1030 | List results = null; 1031 | for (PageObject page : doc.pages) { 1032 | 1033 | for (int i = 0, len = page.texts.size(); i < len; i++) { 1034 | TextObject text = page.texts.get(i); 1035 | 1036 | if (text.deleted) 1037 | continue; 1038 | if (text.text.equals(paraMarker)) 1039 | continue; 1040 | 1041 | if (!canDetectLang(text)) { 1042 | continue; 1043 | } 1044 | 1045 | /** 1046 | * Call detect language 1047 | */ 1048 | results = detectLang.find(text.text); 1049 | if (results != null && results.size() > 0) { 1050 | LanguageResult lang = results.get(0); 1051 | if (lang.reliable) { 1052 | text.lang = lang.language; 1053 | 1054 | if (config != null) { 1055 | langInfo = config.get(text.lang); 1056 | if (langInfo != null) { 1057 | normalizeList = langInfo.normalize; 1058 | 1059 | /** 1060 | * Normalize text by language 1061 | */ 1062 | text.text = common.replaceText(normalizeList, text.text); 1063 | } 1064 | } 1065 | 1066 | int count = 0; 1067 | if (mapLang.containsKey(lang.language)) { 1068 | count = mapLang.get(lang.language); 1069 | } 1070 | mapLang.put(lang.language, count + 1); 1071 | } 1072 | } 1073 | } 1074 | } 1075 | 1076 | /** 1077 | * Get most language and document language list 1078 | */ 1079 | doc.language = getMaxLangCount(mapLang); 1080 | doc.langList = getLangList(mapLang); 1081 | 1082 | } catch (Exception e) { 1083 | 1084 | } finally { 1085 | refDoc.set(doc); 1086 | } 1087 | } 1088 | 1089 | /** 1090 | * Sentence Join 1091 | */ 1092 | private void sentenceJoin(String uuid, AtomicReference refDoc) { 1093 | DocumentObject doc = refDoc.get(); 1094 | if (common.IsEmpty(doc.language)) 1095 | return; 1096 | 1097 | try { 1098 | 1099 | for (PageObject page : doc.pages) { 1100 | 1101 | String currentLang = ""; 1102 | List texts = new ArrayList<>(); 1103 | List newTexts = new ArrayList<>(); 1104 | for (int i = 0, len = page.texts.size(); i < len; i++) { 1105 | TextObject text = page.texts.get(i); 1106 | 1107 | if (text.deleted) 1108 | continue; 1109 | 1110 | if (common.IsEmpty(text.lang)) 1111 | text.lang = doc.language; 1112 | 1113 | if (i == 0 || common.IsEmpty(currentLang)) { 1114 | 1115 | // start first chunk 1116 | if (!common.IsEmpty(text.lang)) { 1117 | currentLang = text.lang; 1118 | } else { 1119 | currentLang = doc.language; 1120 | } 1121 | texts.add(text); 1122 | 1123 | } else if (text.text.equals(paraMarker) || (!common.IsEmpty(currentLang) 1124 | && !common.IsEmpty(text.lang) && !text.lang.equals(currentLang))) { 1125 | 1126 | // do sentence join 1127 | if (text.text.equals(paraMarker)) 1128 | newTexts.add(text); 1129 | 1130 | if (!text.lang.equals(currentLang)) { 1131 | newTexts.add(getNewText(paraMarker)); 1132 | } 1133 | 1134 | newTexts.addAll(sentenceJoin(uuid, texts, currentLang)); 1135 | 1136 | // start new chunk 1137 | texts.clear(); 1138 | 1139 | if (!text.text.equals(paraMarker)) { 1140 | texts.add(text); 1141 | if (!common.IsEmpty(text.lang)) { 1142 | currentLang = text.lang; 1143 | } else { 1144 | currentLang = doc.language; 1145 | } 1146 | } else { 1147 | currentLang = ""; 1148 | } 1149 | } else { 1150 | texts.add(text); 1151 | } 1152 | } 1153 | 1154 | if (texts.size() > 0) { 1155 | newTexts.add(getNewText(paraMarker)); 1156 | newTexts.addAll(sentenceJoin(uuid, texts, currentLang)); 1157 | texts.clear(); 1158 | } 1159 | 1160 | 1161 | // Clean Paramaker 1162 | List tempTextJoin = new ArrayList<>(); 1163 | int processingIndex = 0; 1164 | for (int i = 0; i < newTexts.size() - 2 ; i ++ ) { 1165 | 1166 | for (int j = i+1; j < newTexts.size(); j++) { 1167 | if ((paraMarker.equals(newTexts.get(j).text) || newTexts.get(j).deleted) && !newTexts.get(j-1).deleted) { 1168 | processingIndex = j-1; 1169 | 1170 | if (paraMarker.equals(newTexts.get(j).text)) { 1171 | for (int k = j+1; k < newTexts.size(); k++) { 1172 | if (!newTexts.get(k).deleted) { 1173 | TextObject textleft = newTexts.get(processingIndex); 1174 | TextObject textright = newTexts.get(k); 1175 | if (!textleft.lang.equals(textright.lang)){ 1176 | processingIndex = k; 1177 | break; 1178 | } 1179 | tempTextJoin.add(textleft); 1180 | tempTextJoin.add(textright); 1181 | 1182 | tempTextJoin = sentenceJoin(uuid, tempTextJoin, textleft.lang); 1183 | 1184 | if (tempTextJoin.size() > 1) { 1185 | processingIndex = k; 1186 | }else{ 1187 | newTexts.get(processingIndex).text = tempTextJoin.get(0).text; 1188 | newTexts.get(k).deleted = true; 1189 | newTexts.get(j).deleted = true; 1190 | } 1191 | tempTextJoin = new ArrayList(); 1192 | break; 1193 | } 1194 | } 1195 | 1196 | if (processingIndex > j) { 1197 | i = processingIndex - 1; 1198 | break; 1199 | } 1200 | } 1201 | } 1202 | } 1203 | 1204 | } 1205 | 1206 | page.texts.clear(); 1207 | page.texts.addAll(newTexts); 1208 | } 1209 | 1210 | }catch (Exception e){ 1211 | 1212 | e.printStackTrace(); 1213 | }finally { 1214 | refDoc.set(doc); 1215 | } 1216 | } 1217 | 1218 | /** 1219 | * Final repair with the configuration rules 1220 | */ 1221 | private void finalRepair(AtomicReference refDoc) { 1222 | DocumentObject doc = refDoc.get(); 1223 | 1224 | try { 1225 | 1226 | List repairList = new ArrayList<>(); 1227 | if (config.get("common") != null) { 1228 | repairList = config.get("common").repair; 1229 | } 1230 | 1231 | LangInfo langInfo = new LangInfo(); 1232 | 1233 | for (PageObject page : doc.pages) { 1234 | 1235 | for (int i = 0, len = page.texts.size(); i < len; i++) { 1236 | TextObject text = page.texts.get(i); 1237 | 1238 | if (text.deleted) 1239 | continue; 1240 | if (text.text.equals(paraMarker)) 1241 | continue; 1242 | 1243 | text.text = common.replaceText(repairList, text.text); 1244 | 1245 | if (common.IsEmpty(text.lang)) 1246 | continue; 1247 | 1248 | langInfo = config.get(text.lang); 1249 | if (langInfo != null) { 1250 | List langRepairList = langInfo.repair; 1251 | text.text = common.replaceText(langRepairList, text.text); 1252 | } 1253 | 1254 | } 1255 | } 1256 | 1257 | } finally { 1258 | refDoc.set(doc); 1259 | } 1260 | } 1261 | 1262 | /** 1263 | * Generate final output with html format 1264 | */ 1265 | private StringBuffer generateOutput(AtomicReference refDoc, int keepBrTags, int getPermission) { 1266 | 1267 | 1268 | DocumentObject doc = refDoc.get(); 1269 | StringBuffer sbOut = new StringBuffer(); 1270 | boolean isKenlmError = false; 1271 | 1272 | // html 1273 | sbOut.append("\n"); 1274 | 1275 | // header 1276 | sbOut.append("\n"); 1277 | sbOut.append("\n"); 1278 | sbOut.append("\n"); 1279 | 1280 | List noModel = new ArrayList<>(); 1281 | List errorModel = new ArrayList<>(); 1282 | 1283 | for (LangObject lang : doc.langList) { 1284 | // Add row count by language. 1285 | sbOut.append("\n"); 1286 | SentenceJoin sj = _hashSentenceJoin.get(lang.name); 1287 | 1288 | // #51 :To prevent Spurious warnings about sentenceJoin models. 1289 | if (_hashSentenceJoin.containsKey(lang.name) && sj == null) { 1290 | noModel.add(lang.name); 1291 | } else if (null != sj && sj.status() == WorkerStatus.ERROR) { 1292 | isKenlmError = sj.isKenlmError; 1293 | errorModel.add(lang.name); 1294 | } 1295 | } 1296 | 1297 | 1298 | // #54 Accurate the error warning message. 1299 | String scriptPath = config.getSentenceJoinScript(); 1300 | if (StringUtils.isEmpty(scriptPath) || !common.IsExist(scriptPath)) { 1301 | doc.warningList 1302 | .add(new WarnObject("sentenceJoin", "Fail loading Python script sentence-join.py","Please specify/verify the \"sentence_join\" value in the configuration files.")); 1303 | }else { 1304 | 1305 | if (errorModel.size() > 0) { 1306 | 1307 | if (isKenlmError) { 1308 | doc.warningList.add( 1309 | new WarnObject("sentenceJoin", "Fail loading model for language: " + String.join(", ", errorModel) + "" 1310 | , "Please verify the KenLM path on the argument of command-line.")); 1311 | }else { 1312 | doc.warningList.add( 1313 | new WarnObject("sentenceJoin", "Fail loading model for language: " + String.join(", ", errorModel) + "" 1314 | , "Please verify the \"sentencejoin_model\" value of language {" + String.join(", ", errorModel) +"} in configuration file.")); 1315 | } 1316 | 1317 | } 1318 | 1319 | if (noModel.size() > 0) { 1320 | doc.warningList 1321 | .add(new WarnObject("sentenceJoin", "No model for language: " + String.join(", ", noModel) + "" 1322 | , "Please specify the \"sentencejoin_model\" value of language {" + String.join(", ", noModel) +"} in configuration file.")); 1323 | } 1324 | } 1325 | 1326 | 1327 | sbOut.append("\n"); 1328 | if (doc.warningList.size() > 0) { 1329 | sbOut.append("" + "\n"); 1330 | for (WarnObject warnObj : doc.warningList) { 1331 | sbOut.append("" + "\n"); 1332 | sbOut.append("" + warnObj.method + "" + "\n"); 1333 | sbOut.append("
\n"); 1334 | sbOut.append("\t"); 1335 | 1336 | sbOut.append("" + ""); 1339 | sbOut.append("" + "\n"); 1340 | sbOut.append("\t"); 1341 | sbOut.append("" + ""); 1344 | sbOut.append("" + "\n"); 1345 | sbOut.append("
" + "\n"); 1346 | sbOut.append("
" + "\n"); 1347 | } 1348 | sbOut.append("
" + "\n"); 1349 | } 1350 | // End Accurate the error warning message. 1351 | 1352 | if (getPermission == 1) { 1353 | sbOut.append("" + "\n"); 1354 | sbOut.append("" + doc.permission.canAssembly + "" + "\n"); 1355 | sbOut.append("" + doc.permission.canCopy + "" + "\n"); 1356 | sbOut.append("" + doc.permission.canModified + "" + "\n"); 1357 | sbOut.append( 1358 | "" + doc.permission.canModifyAnnotations + "" + "\n"); 1359 | sbOut.append("" + doc.permission.canPrint + "" + "\n"); 1360 | sbOut.append("" + doc.permission.canPrintDegraded + "" + "\n"); 1361 | sbOut.append("" + doc.permission.canFillInForm + "" + "\n"); 1362 | sbOut.append("" + doc.permission.canScreenReader + "" + "\n"); 1363 | sbOut.append("" + "\n"); 1364 | } 1365 | sbOut.append("\n"); 1366 | 1367 | // body 1368 | sbOut.append("\n"); 1369 | for (PageObject page : doc.pages) { 1370 | 1371 | // page 1372 | sbOut.append("
\n"); 1373 | 1374 | int ipara = 1; 1375 | boolean bpara = false; 1376 | 1377 | if (page.texts.size() > 0) { 1378 | 1379 | for (int i = 0, len = page.texts.size(); i < len; i++) { 1380 | TextObject text = page.texts.get(i); 1381 | if (text.deleted) 1382 | continue; 1383 | if (common.IsEmpty(text.text)) 1384 | continue; 1385 | 1386 | if (text.text.equals(paraMarker) && !text.deleted) { 1387 | if (bpara) { 1388 | sbOut.append("

\n"); 1389 | bpara = false; 1390 | } 1391 | 1392 | if (i + 1 < len) { 1393 | 1394 | if (page.texts.get(i + 1).text.equals(paraMarker) && !page.texts.get(i + 1).deleted) 1395 | continue; 1396 | if (common.IsEmpty(page.texts.get(i + 1).text)) 1397 | continue; 1398 | 1399 | String lang = page.texts.get(i + 1).lang; 1400 | String font = page.texts.get(i + 1).fontfamily; 1401 | 1402 | // paragraph 1403 | sbOut.append("

\n"); 1405 | bpara = true; 1406 | } 1407 | } else { 1408 | if (!bpara) { 1409 | // paragraph 1410 | sbOut.append("

\n"); 1412 | bpara = true; 1413 | } 1414 | 1415 | // line 1416 | sbOut.append(text.text.trim()); 1417 | sbOut.append((keepBrTags == 1 ? "
" : "") + "\n"); 1418 | } 1419 | } 1420 | if (ipara > 1) { 1421 | sbOut.append("

\n"); 1422 | } 1423 | } 1424 | 1425 | sbOut.append("
\n"); 1426 | 1427 | } 1428 | sbOut.append("\n"); 1429 | sbOut.append("\n"); 1430 | 1431 | return sbOut; 1432 | 1433 | } 1434 | 1435 | /** 1436 | * Extract text properties into object 1437 | */ 1438 | private TextObject getTextObject(String line, HashMap mapStyle) { 1439 | TextObject obj = new TextObject(); 1440 | 1441 | obj.top = common.getFloat(patternTop.matcher(line).replaceAll("$1")); 1442 | obj.left = common.getFloat(patternLeft.matcher(line).replaceAll("$1")); 1443 | obj.width = common.getFloat(patternWidth.matcher(line).replaceAll("$1")); 1444 | obj.height = common.getFloat(patternHeight.matcher(line).replaceAll("$1")); 1445 | obj.bottom = obj.top + obj.height; 1446 | obj.right = obj.left + obj.width; 1447 | obj.text = common.getStr(patternWord.matcher(line).replaceAll("$1")); 1448 | obj.class_ = common.getStr(patternFont.matcher(line).replaceAll("$1")); 1449 | 1450 | if (mapStyle != null && mapStyle.containsKey(obj.class_)) { 1451 | StyleObject css = mapStyle.get(obj.class_); 1452 | obj.fontsize = css.size; 1453 | obj.fontfamily = css.family; 1454 | obj.color = css.color; 1455 | } 1456 | 1457 | String text = obj.text; 1458 | 1459 | if (patternLink.matcher(text).matches()) { 1460 | obj.islink = true; 1461 | } 1462 | 1463 | text = text.replaceAll("", "_LSBRLS_"); 1464 | text = text.replaceAll("<[^>]*>", ""); 1465 | text = text.replaceAll(" ", " ").replaceAll("\\s{2,100}", " "); 1466 | text = text.replaceAll("_LSBRLS_", "
"); 1467 | obj.text = text; 1468 | 1469 | return obj; 1470 | } 1471 | 1472 | /** 1473 | * Consider to add text object into the page 1474 | */ 1475 | private boolean checkLineAdd(float pageWidth, float pageHeight, TextObject text) { 1476 | if (text.left < 0 || text.top < 0 || text.left > pageWidth || text.top > pageHeight) { 1477 | return false; 1478 | } else { 1479 | return true; 1480 | } 1481 | } 1482 | 1483 | /** 1484 | * Check next font change 1485 | */ 1486 | private boolean isFontChanged(TextObject text, TextObject nextText) { 1487 | if ((text.fontsize != nextText.fontsize && !isEquals(text.height, nextText.height)) 1488 | || (!text.color.equals(nextText.color) && !isEquals(text.top, nextText.top))) { 1489 | return true; 1490 | } else { 1491 | return false; 1492 | } 1493 | } 1494 | 1495 | /** 1496 | * Check next class change 1497 | */ 1498 | private boolean isClassChanged(TextObject text, TextObject nextText) { 1499 | if (!text.class_.equals(nextText.class_)) { 1500 | return true; 1501 | } else { 1502 | return false; 1503 | } 1504 | } 1505 | 1506 | /** 1507 | * Get maximum count of the list 1508 | */ 1509 | private Float getMaxCount(HashMap map) { 1510 | 1511 | if (map == null || map.size() == 0) { 1512 | return 0f; 1513 | } else { 1514 | // #37, Fix to remove sorting for getting max 1515 | Map.Entry maxEntry = null; 1516 | for (Map.Entry entry : map.entrySet()) 1517 | { 1518 | if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) 1519 | { 1520 | maxEntry = entry; 1521 | } 1522 | } 1523 | 1524 | return maxEntry.getKey(); 1525 | } 1526 | } 1527 | 1528 | /** 1529 | * Get maximum language count 1530 | */ 1531 | private String getMaxLangCount(HashMap map) { 1532 | 1533 | if (map == null || map.size() == 0) { 1534 | return ""; 1535 | } else { 1536 | // #37, Fix to remove sorting for getting max 1537 | Map.Entry maxEntry = null; 1538 | for (Map.Entry entry : map.entrySet()) 1539 | { 1540 | if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) 1541 | { 1542 | maxEntry = entry; 1543 | } 1544 | } 1545 | 1546 | return maxEntry.getKey(); 1547 | } 1548 | } 1549 | 1550 | /** 1551 | * Create new text object with value 1552 | */ 1553 | private TextObject getNewText(String val) { 1554 | TextObject t = new TextObject(); 1555 | t.text = val; 1556 | return t; 1557 | } 1558 | 1559 | /** 1560 | * Compare two numbers 1561 | */ 1562 | private boolean isEquals(Float f1, Float f2) { 1563 | if (Math.abs(f1 - f2) <= 8) { 1564 | return true; 1565 | } else { 1566 | return false; 1567 | } 1568 | } 1569 | 1570 | /** 1571 | * Check next text is too far 1572 | * Modify the method for line space and left position to specify paragraph. 1573 | */ 1574 | private boolean isTooFar(TextObject text, TextObject nextText, float fLinespace) { 1575 | boolean bResult; 1576 | float ftempLineSpace = 0.0f; 1577 | if (fLinespace > 0) { 1578 | ftempLineSpace = Math.abs(text.top - nextText.top); 1579 | if ((ftempLineSpace >= 0.7*fLinespace && ftempLineSpace <= 1.30*fLinespace) && 1580 | (text.left - nextText.left < 0 || text.left - nextText.left > 0 )) { 1581 | bResult = true; 1582 | }else if (ftempLineSpace < 0.7*fLinespace || ftempLineSpace > 1.30*fLinespace){ 1583 | bResult = true; 1584 | }else { 1585 | bResult = false; 1586 | } 1587 | }else { 1588 | if ((Math.abs(text.top - nextText.top) > (text.height + nextText.height)*1.5) || !(Math.abs(text.left - nextText.left) <= 100 && Math.abs(text.left - nextText.left) >=0 ) 1589 | // || (Math.abs((text.width + text.left) - (nextText.left + nextText.width)) >= 50 ) 1590 | || (text.text.length() <=10) 1591 | ) { 1592 | bResult = true; 1593 | } else { 1594 | bResult = false; 1595 | } 1596 | } 1597 | return bResult; 1598 | } 1599 | 1600 | /** 1601 | * Consider top position to merge an object 1602 | */ 1603 | private boolean isMergeTop(TextObject text, TextObject nextText) { 1604 | if (isEquals(text.top, nextText.top) && !isFontChanged(text, nextText) && nextText.left - text.right < 200) { 1605 | return true; 1606 | } 1607 | return false; 1608 | } 1609 | 1610 | /** 1611 | * Consider text can detect language or not If it too short sentence, no detect 1612 | */ 1613 | private boolean canDetectLang(TextObject text) { 1614 | String str = text.text; 1615 | str = str.replaceAll( 1616 | "[\\?\\!\\,0-9\\-\\_\\#\\*\\&\\(\\)\\+\\=\\@\\%\\<\\>\\{\\}\\[\\]\\^\\\\\\/\\;\\.{2,100}]*", ""); 1617 | str = str.replaceAll("\\s\\.{2,100}", ""); 1618 | str = str.replaceAll("\\:", " "); 1619 | str = str.replaceAll("[σΦϕ∈†τψη∇π∑∂αβ→∏ε]*", ""); 1620 | str = str.replaceAll("\\s{2,100}", " "); 1621 | str = str.trim(); 1622 | 1623 | int wordlength = str.split(" ", -1).length; 1624 | int charlength = str.replaceAll(" ", "").length(); 1625 | if (wordlength > 10 || charlength > 30) { 1626 | return true; 1627 | } else { 1628 | return false; 1629 | } 1630 | } 1631 | 1632 | /** 1633 | * Collect languages detected in the document and calculate percentage 1634 | * appearance 1635 | */ 1636 | private List getLangList(HashMap map) { 1637 | 1638 | List langList = new ArrayList<>(); 1639 | 1640 | // total 1641 | float total = 0; 1642 | for (Map.Entry hash : map.entrySet()) { 1643 | total += common.getDouble(hash.getValue()); 1644 | } 1645 | 1646 | // calculate percentage 1647 | for (Map.Entry hash : map.entrySet()) { 1648 | float percent = (common.getFloat(hash.getValue()) * 100) / total; 1649 | 1650 | LangObject lang = new LangObject(); 1651 | lang.name = hash.getKey(); 1652 | lang.percent = percent; 1653 | lang.count = hash.getValue(); 1654 | langList.add(lang); 1655 | } 1656 | 1657 | // sort 1658 | Collections.sort(langList, new Comparator() { 1659 | @Override 1660 | public int compare(LangObject l1, LangObject l2) { 1661 | return Float.compare(l2.percent, l1.percent); 1662 | } 1663 | }); 1664 | 1665 | return langList; 1666 | } 1667 | 1668 | /** 1669 | * Get first n words of the line 1670 | */ 1671 | private String getFirstWords(String str) { 1672 | 1673 | String[] words = str.split(" "); 1674 | int wordlength = words.length; 1675 | 1676 | String newStr = ""; 1677 | for (int i = 0; i <= maxWordsJoin && i < wordlength; i++) { 1678 | newStr += " " + words[i]; 1679 | } 1680 | 1681 | return newStr.trim(); 1682 | } 1683 | 1684 | /** 1685 | * Get last n words of the line 1686 | */ 1687 | private String getLastWords(String str) { 1688 | 1689 | String[] words = str.trim().split(" "); 1690 | int wordlength = words.length; 1691 | 1692 | int count = 0; 1693 | String newStr = ""; 1694 | for (int i = wordlength - 1; i >= 0 && count <= maxWordsJoin; i--, count++) { 1695 | newStr = words[i] + " " + newStr; 1696 | } 1697 | 1698 | return newStr.trim(); 1699 | } 1700 | 1701 | /** 1702 | * Get sentence join model for language 1703 | */ 1704 | private String getSentenceJoinModel(String lang) { 1705 | if (config != null && config.get(lang) != null) { 1706 | return config.get(lang).sentenceJoinModel; 1707 | } 1708 | return ""; 1709 | } 1710 | 1711 | /** 1712 | * Execute sentence join by language 1713 | */ 1714 | private List sentenceJoin(String uuid, List texts, String lang) { 1715 | 1716 | List newTexts = new ArrayList<>(); 1717 | try { 1718 | 1719 | if (texts.size() < 2) { 1720 | return texts; 1721 | } 1722 | 1723 | SentenceJoin sj; 1724 | 1725 | synchronized (_objectWorker) { 1726 | 1727 | if (_hashSentenceJoin.containsKey(lang)) { 1728 | sj = _hashSentenceJoin.get(lang); 1729 | // Fix issue #57 Sentence join fails when using a batch file: Set last execute time. 1730 | if (null != sj) { 1731 | sj.get_registerid().add(uuid); 1732 | } 1733 | } else { 1734 | 1735 | String scriptPath = config.getSentenceJoinScript(); 1736 | String sKenlmPath = config.getKenlmPath(); 1737 | String modelPath = getSentenceJoinModel(lang); 1738 | if (common.IsExist(scriptPath) && !common.IsEmpty(modelPath)) { 1739 | // #43 Change Request: Poppler rewrite 1740 | sj = new SentenceJoin(lang, scriptPath, modelPath, sKenlmPath); 1741 | _hashSentenceJoin.put(lang, sj); 1742 | } else { 1743 | sj = null; 1744 | _hashSentenceJoin.put(lang, sj); 1745 | } 1746 | } 1747 | 1748 | // Fix Issue #35 to prevent call start() multiple time in one language id. 1749 | if (sj != null && sj.status() != WorkerStatus.RUNNING && sj.status() != WorkerStatus.LOADING && sj.status() != WorkerStatus.ERROR) { 1750 | sj.start(); 1751 | // Fix issue #57 Sentence join fails when using a batch file: Set last execute time. 1752 | sj.get_registerid().add(uuid); 1753 | } 1754 | } 1755 | 1756 | if (sj != null && sj.status() == WorkerStatus.RUNNING) { 1757 | // Fix issue #57 Sentence join fails when using a batch file: Set last execute time. 1758 | sj.get_registerid().add(uuid); 1759 | for (int i = texts.size() - 1, start = 0; i >= start; i--) { 1760 | TextObject text = texts.get(i); 1761 | 1762 | if (i - 1 >= 0) { 1763 | TextObject prevText = texts.get(i - 1); 1764 | 1765 | String text1 = getLastWords(prevText.text).trim(); 1766 | String text2 = getFirstWords(text.text).trim(); 1767 | 1768 | boolean isJoin = false; 1769 | if (!common.IsEmpty(text1) && !common.IsEmpty(text2) 1770 | && !text1.trim().endsWith(".") 1771 | && !text2.trim().startsWith("•") && !text1.trim().equals(" ") 1772 | && !text2.trim().equals(" ")) { 1773 | isJoin = sj.execute(text1, text2); 1774 | } 1775 | 1776 | if (isJoin) { 1777 | prevText.text = prevText.text.trim() + " " + text.text.trim(); 1778 | text.deleted = true; 1779 | } else { 1780 | newTexts.add(text); 1781 | } 1782 | } else { 1783 | newTexts.add(text); 1784 | } 1785 | 1786 | } 1787 | 1788 | return Lists.reverse(newTexts); 1789 | 1790 | } 1791 | 1792 | } catch (Exception e) { 1793 | common.print("ERROR\tsentenceJoin: " + e.getMessage()); 1794 | } 1795 | 1796 | return texts; 1797 | } 1798 | 1799 | /** 1800 | * Shutdown sentence join process 1801 | */ 1802 | public void shutdownProcess() throws Exception { 1803 | try { 1804 | if (_hashSentenceJoin != null && _hashSentenceJoin.size() > 0) { 1805 | for (Map.Entry hash : _hashSentenceJoin.entrySet()) { 1806 | if (hash.getValue() != null) { 1807 | hash.getValue().stop(); 1808 | hash.getValue().setStatus(WorkerStatus.STOPPED); 1809 | } 1810 | } 1811 | } 1812 | } catch (Exception e) { 1813 | throw e; 1814 | } 1815 | } 1816 | 1817 | // Fix issue #57 Sentence join fails when using a batch file: Checking the model has been being used or not before terminate the model. 1818 | public void shutdownProcess(String uuid) throws Exception { 1819 | try { 1820 | if (_hashSentenceJoin != null && _hashSentenceJoin.size() > 0) { 1821 | for (Map.Entry hash : _hashSentenceJoin.entrySet()) { 1822 | 1823 | 1824 | if (hash.getValue() != null ) { 1825 | Set registerid = hash.getValue().get_registerid(); 1826 | // common.print(hash.getKey() + " " + uuid + " *Before Size:::::::::" + registerid.size()); 1827 | // common.print(hash.getKey() + " " + registerid); 1828 | if (registerid.contains(uuid)) { 1829 | registerid.remove(uuid); 1830 | // common.print(hash.getKey() + " " +"*After Size:::::::::" + registerid.size()); 1831 | if (registerid.size() == 0) { 1832 | hash.getValue().setStatus(WorkerStatus.STOPPED); 1833 | hash.getValue().stop(); 1834 | } 1835 | } 1836 | } 1837 | } 1838 | } 1839 | } catch (Exception e) { 1840 | throw e; 1841 | } 1842 | } 1843 | 1844 | } -------------------------------------------------------------------------------- /src/pdfextract/PDFToHtml.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.File; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.TimeoutException; 9 | 10 | import org.apache.commons.lang.StringUtils; 11 | 12 | import com.itextpdf.text.pdf.PdfEncryptor; 13 | import com.itextpdf.text.pdf.PdfReader; 14 | import com.itextpdf.text.pdf.PdfWriter; 15 | 16 | /** 17 | * @author MickeyVI 18 | */ 19 | public class PDFToHtml { 20 | 21 | Common common = new Common(); 22 | private long timeout = 30; 23 | 24 | public PDFToHtml(long timeout_) { 25 | if (timeout_ > 0) 26 | timeout = timeout_; 27 | } 28 | 29 | /** 30 | * Extract pdf stream to html 31 | */ 32 | public StringBuffer extract(ByteArrayInputStream bIn) throws Exception { 33 | StringBuffer sbuf = new StringBuffer(); 34 | try { 35 | 36 | return sbuf.append(executeCommandByteArrayInputStream(bIn).toString()); 37 | } catch (Exception e) { 38 | return new StringBuffer(); 39 | } 40 | } 41 | 42 | /** 43 | * Extract pdf file to html 44 | */ 45 | public StringBuffer extract(String inputPath) throws Exception { 46 | 47 | StringBuffer sb = null; 48 | 49 | try { 50 | sb = new StringBuffer(); 51 | 52 | String sCommand[] = new String[] { "pdftohtml", "-stdout", "-i", "-noframes", "-xml", "-fontfullname", inputPath}; 53 | 54 | try { 55 | // executeCommand(sCommand); 56 | //#42 Use stdout for pdftohtml 57 | sb.append(executeCommand(sCommand).toString()); 58 | } catch (Exception e) { 59 | String errorMsg = e.getMessage(); 60 | if (errorMsg.contains("Permission Error:")) { 61 | decrypt(inputPath); 62 | sb = new StringBuffer(); 63 | sb.append(executeCommand(sCommand).toString()); 64 | } else { 65 | throw e; 66 | } 67 | } 68 | return sb; 69 | } catch (Exception e) { 70 | throw e; 71 | } 72 | } 73 | 74 | public void decrypt(String file) throws IOException { 75 | decrypt(null, file); 76 | } 77 | 78 | public void decrypt(PdfReader reader, String file) throws IOException { 79 | File fTemp = null; 80 | try { 81 | 82 | if (reader == null) { 83 | reader = new PdfReader(file); 84 | PdfReader.unethicalreading = true; 85 | } 86 | 87 | fTemp = File.createTempFile(new File(file).getName(), ".unlocked"); 88 | fTemp.deleteOnExit(); 89 | 90 | String inputPathUnlocked = fTemp.getPath(); 91 | PdfEncryptor.encrypt(reader, new FileOutputStream(inputPathUnlocked), null, null, 92 | PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_DEGRADED_PRINTING 93 | | PdfWriter.ALLOW_FILL_IN | PdfWriter.ALLOW_MODIFY_ANNOTATIONS 94 | | PdfWriter.ALLOW_MODIFY_CONTENTS | PdfWriter.ALLOW_PRINTING 95 | | PdfWriter.ALLOW_SCREENREADERS, 96 | false); 97 | 98 | common.moveFile(fTemp.getPath(), file); 99 | } catch (Exception e) { 100 | } finally { 101 | if (reader != null) { 102 | reader.close(); 103 | reader = null; 104 | } 105 | if (fTemp != null) 106 | common.deleteFile(fTemp); 107 | } 108 | 109 | } 110 | 111 | /** 112 | * Execute command to extract 113 | */ 114 | private StringBuilder executeCommand(String... command) throws Exception { 115 | 116 | Process proc = null; 117 | boolean bTimeout = false; 118 | StringBuilder sbError = null; 119 | StringBuilder sb = null; 120 | try { 121 | sb = new StringBuilder(); 122 | sbError = new StringBuilder(); 123 | 124 | proc = Runtime.getRuntime().exec(command); 125 | 126 | //#38 Deadlock on stderr from pdftohtml 127 | StreamGobbler errorStreamGobbler = new StreamGobbler("ErrorStream", proc.getErrorStream()); 128 | StreamGobbler inputStreamGobbler = new StreamGobbler("InputStream", proc.getInputStream()); 129 | 130 | Thread tInput = new Thread(inputStreamGobbler); 131 | Thread tError = new Thread(errorStreamGobbler); 132 | tError.start(); 133 | tInput.start(); 134 | 135 | if (!proc.waitFor(timeout, TimeUnit.SECONDS)) { 136 | // timeout - kill the process. 137 | bTimeout = true; 138 | proc.destroyForcibly(); 139 | } 140 | 141 | tError.join(); 142 | tInput.join(); 143 | 144 | errorStreamGobbler.CloseBuffer(); 145 | inputStreamGobbler.CloseBuffer(); 146 | 147 | sbError = errorStreamGobbler.getSbText(); 148 | sb = inputStreamGobbler.getSbText(); 149 | 150 | if (sbError.length() > 0) { 151 | String sTemp = sbError.toString(); 152 | // Skip the warning meesage 153 | if (!proc.isAlive() && !StringUtils.isEmpty(sTemp) && proc.exitValue() != 0) 154 | throw new Exception(sTemp.toString()); 155 | else { 156 | return sb; 157 | } 158 | }else { 159 | // success 160 | return sb; 161 | } 162 | 163 | } catch (IOException e) { 164 | if (bTimeout) { 165 | throw new TimeoutException( 166 | "Timed out waiting for poppler extract pdf reach. (" + timeout + " seconds)"); 167 | } else { 168 | throw e; 169 | } 170 | } catch (Exception e) { 171 | throw e; 172 | } finally { 173 | proc.destroy(); 174 | } 175 | } 176 | 177 | private StringBuilder executeCommandByteArrayInputStream(ByteArrayInputStream bIn) throws Exception { 178 | 179 | Process proc = null; 180 | boolean bTimeout = false; 181 | StringBuilder sbError = null; 182 | StringBuilder sb = null; 183 | try { 184 | sb = new StringBuilder(); 185 | sbError = new StringBuilder(); 186 | 187 | String[] commands = new String[8]; 188 | 189 | commands[0] = "pdftohtml"; 190 | commands[1] = "-xml"; 191 | commands[2] = "-fontfullname"; 192 | commands[3] = "-stdout"; 193 | 194 | // #56 Over 2M of trash files produced while crawling 195 | commands[4] = "-i"; 196 | commands[5] = "-noframes"; 197 | 198 | commands[6] = "-"; 199 | commands[7] = "nonsense"; 200 | 201 | ProcessBuilder procBuilder = new ProcessBuilder(commands); 202 | proc = procBuilder.start(); 203 | 204 | //#38 Deadlock on stderr from pdftohtml 205 | StreamGobbler errorStreamGobbler = new StreamGobbler("ErrorStreamST", proc.getErrorStream()); 206 | StreamGobbler inputStreamGobbler = new StreamGobbler("InputStreamST", proc.getInputStream(), 207 | proc.getOutputStream(), bIn); 208 | 209 | inputStreamGobbler.SetOutputStream(); 210 | Thread tInput = new Thread(inputStreamGobbler); 211 | Thread tError = new Thread(errorStreamGobbler); 212 | tError.start(); 213 | tInput.start(); 214 | 215 | if (!proc.waitFor(timeout, TimeUnit.SECONDS)) { 216 | // timeout - kill the process. 217 | bTimeout = true; 218 | proc.destroyForcibly(); 219 | } 220 | 221 | tError.join(); 222 | tInput.join(); 223 | 224 | errorStreamGobbler.CloseBuffer(); 225 | inputStreamGobbler.CloseBuffer(); 226 | 227 | sbError = errorStreamGobbler.getSbText(); 228 | sb = inputStreamGobbler.getSbText(); 229 | 230 | 231 | if (sbError.length() > 0) { 232 | String sTemp = sbError.toString(); 233 | // Skip the warning meesage 234 | if (!proc.isAlive() && !StringUtils.isEmpty(sTemp) && proc.exitValue() != 0) 235 | throw new Exception(sTemp.toString()); 236 | else { 237 | return sb; 238 | } 239 | }else { 240 | // success 241 | return sb; 242 | } 243 | 244 | } catch (IOException e) { 245 | if (bTimeout) { 246 | throw new TimeoutException( 247 | "Timed out waiting for poppler extract pdf reach. (" + timeout + " seconds)"); 248 | } else { 249 | throw e; 250 | } 251 | } catch (Exception e) { 252 | throw e; 253 | } finally { 254 | proc.destroy(); 255 | } 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /src/pdfextract/SentenceJoin.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | 10 | /** 11 | * @author MickeyVI 12 | */ 13 | public class SentenceJoin { 14 | 15 | private Common common = new Common(); 16 | 17 | private String _sScriptPath = ""; 18 | private String _skenlmPath = ""; 19 | private Process _proc = null; 20 | 21 | private WorkerStatus _workerStatus; 22 | private String _language = ""; 23 | private String _modelPath = ""; 24 | private ExecutorService _executor; 25 | private Object _objectWorker = new Object(); 26 | private StreamGobblerWithOutput _errorStreamGobbler; 27 | private StreamGobblerWithOutput _inputStreamGobbler; 28 | public boolean isKenlmError = false; 29 | private Set _registerid = new HashSet(); 30 | 31 | 32 | /** 33 | * Constructor 34 | */ 35 | public SentenceJoin(String lang, String scriptPath, String modelPath) { 36 | _language = lang; 37 | _sScriptPath = scriptPath; 38 | _modelPath = modelPath; 39 | _executor = Executors.newSingleThreadExecutor(); 40 | } 41 | 42 | public SentenceJoin(String lang, String scriptPath, String modelPath, String sKenlmPath) { 43 | _language = lang; 44 | _sScriptPath = scriptPath; 45 | _modelPath = modelPath; 46 | _skenlmPath = sKenlmPath; 47 | _executor = Executors.newSingleThreadExecutor(); 48 | } 49 | 50 | /** 51 | * Worker Status 52 | */ 53 | public enum WorkerStatus { 54 | STOPPED, LOADING, RUNNING, ERROR 55 | } 56 | 57 | /** 58 | * Get Worker Status 59 | */ 60 | public WorkerStatus status() { 61 | return _workerStatus; 62 | } 63 | 64 | // Set worker Status 65 | public void setStatus(WorkerStatus status) { 66 | this._workerStatus = status; 67 | } 68 | 69 | public Set get_registerid() { 70 | return _registerid; 71 | } 72 | 73 | /** 74 | * Start sentence join process 75 | */ 76 | public void start() throws Exception { 77 | if (_workerStatus == WorkerStatus.RUNNING || _workerStatus == WorkerStatus.LOADING) 78 | return; 79 | if (!common.IsExist(_sScriptPath)) 80 | return; 81 | if (common.IsEmpty(_modelPath)) 82 | return; 83 | 84 | _workerStatus = WorkerStatus.LOADING; 85 | 86 | // fix issue #35 to prevent invalid _workerStatus 87 | try { 88 | StringBuilder sbError = new StringBuilder(); 89 | // Execute command line to start process 90 | String[] commands = new String[4]; 91 | if (!StringUtils.isEmpty(_skenlmPath)){ 92 | commands = new String[6]; 93 | } 94 | 95 | commands[0] = _sScriptPath; 96 | commands[1] = "--apply"; 97 | commands[2] = "--model"; 98 | commands[3] = _modelPath; 99 | 100 | // #43 Poppler rewrite 101 | if (!StringUtils.isEmpty(_skenlmPath)){ 102 | commands[4] = "--kenlm_path"; 103 | commands[5] = _skenlmPath; 104 | } 105 | 106 | ProcessBuilder proc = new ProcessBuilder(commands); 107 | //#50 Set to false to prevent error: This binary file contains Trie with Quantization and array-compressed pointers. 108 | proc.redirectErrorStream(false); // setting true 109 | _proc = proc.start(); 110 | 111 | // Fix issue #36 Deadlock if SentenceJoin writes to stderr 112 | this._inputStreamGobbler = new StreamGobblerWithOutput("InputStreamST", _proc.getInputStream(), _proc.getOutputStream(), "test\teating"); 113 | this._errorStreamGobbler = new StreamGobblerWithOutput("ErrorStreamST", _proc.getErrorStream()); 114 | Thread tInput = new Thread(this._inputStreamGobbler); 115 | Thread tError = new Thread(this._errorStreamGobbler); 116 | 117 | tError.start(); 118 | tInput.start(); 119 | tInput.join(); 120 | 121 | sbError = _errorStreamGobbler.getOutputBuffer(); 122 | 123 | if (sbError.length() > 0) { 124 | // #55 to skip the "This binary file contains trie with quantization and array-compressed pointers." from KenLM. 125 | // and check error with system exit code. 126 | String sTemp = sbError.toString(); 127 | sTemp = sTemp.replaceAll("(This binary file contains trie with quantization and array\\-compressed pointers\\.)(\\n*)", ""); 128 | if (!_proc.isAlive() && !StringUtils.isEmpty(sTemp) && _proc.exitValue() != 0) 129 | throw new Exception(sTemp.toString()); 130 | else { 131 | _workerStatus = WorkerStatus.RUNNING; 132 | } 133 | }else { 134 | // success 135 | _workerStatus = WorkerStatus.RUNNING; 136 | } 137 | _inputStreamGobbler.getSentenceJoin("Someone\tplays football"); 138 | 139 | 140 | } catch (Exception e) { 141 | // If load model not finish. It must go to this error. 142 | // e.printStackTrace(); 143 | // #54 Accurate the error warning message. 144 | if (null != e.getMessage() && e.getMessage().contains("KenLM")) { 145 | isKenlmError = true; 146 | } 147 | _workerStatus = WorkerStatus.ERROR; 148 | throw new Exception("Start sentence join [" + _language + "] failed: " + e.getMessage()); 149 | } 150 | 151 | _executor.shutdown(); 152 | } 153 | 154 | /** 155 | * Stop sentence join process 156 | */ 157 | public void stop() throws Exception { 158 | try { 159 | 160 | if (null != this._inputStreamGobbler) 161 | this._inputStreamGobbler.CloseBuffer(); 162 | 163 | if (null != this._errorStreamGobbler) 164 | this._errorStreamGobbler.CloseBuffer(); 165 | 166 | if (_proc != null) 167 | _proc.destroy(); 168 | _proc = null; 169 | 170 | } catch (Exception e) { 171 | // e.printStackTrace(); 172 | common.print("stop sentence join [" + _language + "] failed. " + e.getMessage()); 173 | } finally { 174 | } 175 | 176 | } 177 | 178 | /** 179 | * Execute sentence join and get result 180 | */ 181 | public boolean execute(String text1, String text2) throws Exception { 182 | 183 | synchronized (_objectWorker) { 184 | try { 185 | String sOutput = ""; 186 | sOutput = _inputStreamGobbler.getSentenceJoin(text1 + "\t" + text2); 187 | return common.getBool(sOutput); 188 | 189 | } catch (Exception e) { 190 | // e.printStackTrace(); 191 | common.print("execute sentence join [" + _language + "] failed. " + text1 + "\t" + text2 + " ," 192 | + e.getMessage()); 193 | } 194 | } 195 | 196 | return false; 197 | } 198 | 199 | } 200 | -------------------------------------------------------------------------------- /src/pdfextract/StreamGobbler.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.ByteArrayInputStream; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.InputStreamReader; 9 | import java.io.OutputStream; 10 | import java.io.OutputStreamWriter; 11 | 12 | import javax.management.monitor.Monitor; 13 | 14 | import org.apache.commons.io.IOUtils; 15 | import org.apache.commons.io.LineIterator; 16 | 17 | public class StreamGobbler extends Thread { 18 | 19 | private StringBuilder sbText; 20 | private BufferedReader bufReader; 21 | private OutputStream outputStream; 22 | private ByteArrayInputStream bInput; 23 | 24 | StreamGobbler(String name, InputStream inStream) { 25 | super(name); 26 | this.bufReader = new BufferedReader(new InputStreamReader(inStream)); 27 | } 28 | 29 | StreamGobbler(String name, InputStream inputStream, OutputStream outputStream, ByteArrayInputStream bIn) { 30 | 31 | super(name); 32 | this.outputStream = outputStream; 33 | this.bInput = bIn; 34 | this.bufReader = new BufferedReader(new InputStreamReader(inputStream)); 35 | } 36 | 37 | @Override 38 | public void run() { 39 | GetInputStream(); 40 | } 41 | 42 | private void GetInputStream() { 43 | try { 44 | 45 | String sLine = ""; 46 | while ((sLine = bufReader.readLine()) != null) { 47 | getSbText().append(sLine); 48 | getSbText().append("\n"); 49 | } 50 | 51 | } catch (Exception e) { 52 | // Ignore error 53 | } 54 | } 55 | 56 | public StringBuilder getSbText() { 57 | if (null == this.sbText) { 58 | this.sbText = new StringBuilder(); 59 | } 60 | return this.sbText; 61 | } 62 | 63 | public void SetOutputStream() throws Exception { 64 | if (null != bInput && null != outputStream) { 65 | try { 66 | byte[] bytes = new byte[2048]; 67 | int index; 68 | while ((index = bInput.read(bytes)) != -1) { 69 | outputStream.write(bytes, 0, index); 70 | } 71 | 72 | } catch (IOException e) { 73 | throw e; 74 | } finally { 75 | try { 76 | this.outputStream.flush(); 77 | this.outputStream.close(); 78 | } catch (IOException e) { 79 | 80 | } 81 | 82 | } 83 | } 84 | } 85 | 86 | public void CloseBuffer() { 87 | try { 88 | if (null != this.bufReader) 89 | bufReader.close(); 90 | } catch (IOException e) { 91 | 92 | } 93 | 94 | try { 95 | if (null != this.bInput) 96 | this.bInput.close(); 97 | } catch (IOException e) { 98 | 99 | } 100 | 101 | try { 102 | if (null != this.outputStream) 103 | this.outputStream.close(); 104 | } catch (IOException e) { 105 | 106 | } 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/pdfextract/StreamGobblerWithOutput.java: -------------------------------------------------------------------------------- 1 | package pdfextract; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.io.OutputStream; 8 | import java.io.PrintWriter; 9 | import java.util.Scanner; 10 | import java.util.stream.Collectors; 11 | 12 | import org.apache.commons.io.IOUtils; 13 | import org.apache.commons.io.LineIterator; 14 | 15 | public class StreamGobblerWithOutput extends Thread{ 16 | InputStream inputStream; 17 | String inputParam; 18 | OutputStream outputStream; 19 | PrintWriter printWriter; 20 | StringBuilder outputBuffer = new StringBuilder(); 21 | BufferedReader bufferedReader; 22 | private boolean sudoIsRequested = true; 23 | boolean isError = false; 24 | 25 | StreamGobblerWithOutput(String name, InputStream inputStream) 26 | { 27 | super(name); 28 | this.inputStream = inputStream; 29 | this.bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 30 | 31 | } 32 | 33 | StreamGobblerWithOutput(String name, InputStream inputStream, OutputStream outputStream, String inputParam) 34 | { 35 | super(name); 36 | this.inputStream = inputStream; 37 | this.outputStream = outputStream; 38 | this.printWriter = new PrintWriter(outputStream); 39 | this.inputParam = inputParam; 40 | this.sudoIsRequested = true; 41 | this.bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 42 | } 43 | 44 | public void run() 45 | { 46 | 47 | if (sudoIsRequested && null != printWriter) 48 | { 49 | // doSleep(5000); 50 | printWriter.println(inputParam); 51 | printWriter.flush(); 52 | } 53 | 54 | try 55 | { 56 | String line = null; 57 | 58 | int i = 0; 59 | while (null != this.bufferedReader && (line = this.bufferedReader.readLine()) != null ) 60 | { 61 | i ++ ; 62 | outputBuffer.append(line + "\n"); 63 | 64 | if (!bufferedReader.ready()) { 65 | break; 66 | } 67 | } 68 | 69 | if (i > 1) { 70 | isError = true; 71 | }else { 72 | isError = false; 73 | } 74 | } 75 | catch (IOException ioe) 76 | { 77 | // ignore error 78 | } 79 | 80 | } 81 | 82 | public String getSentenceJoin(String inputParam) throws Exception { 83 | String sOutput = ""; 84 | if (null != printWriter) 85 | { 86 | // doSleep(5000); 87 | printWriter.println(inputParam); 88 | printWriter.flush(); 89 | 90 | try 91 | { 92 | String line = null; 93 | while ((line = this.bufferedReader.readLine()) != null ) 94 | { 95 | sOutput = line; 96 | if (!bufferedReader.ready()) { 97 | break; 98 | } 99 | } 100 | } 101 | catch (IOException ioe) 102 | { 103 | throw new Exception(ioe.getMessage()); 104 | } 105 | } 106 | 107 | return sOutput; 108 | } 109 | 110 | private void doSleep(long millis) 111 | { 112 | try 113 | { 114 | Thread.sleep(millis); 115 | } 116 | catch (InterruptedException e) 117 | { 118 | // ignore 119 | } 120 | } 121 | 122 | public StringBuilder getOutputBuffer() 123 | { 124 | return outputBuffer; 125 | } 126 | 127 | public void CloseBuffer() { 128 | try { 129 | this.bufferedReader.close(); 130 | } catch (Exception e) { 131 | 132 | } 133 | 134 | try { 135 | this.printWriter.close(); 136 | } catch (Exception e) { 137 | 138 | } 139 | 140 | try { 141 | this.inputStream.close(); 142 | } catch (Exception e) { 143 | 144 | } 145 | 146 | try { 147 | this.outputStream.close(); 148 | } catch (Exception e) { 149 | 150 | } 151 | 152 | try { 153 | this.printWriter.close(); 154 | } catch (Exception e) { 155 | 156 | } 157 | } 158 | 159 | public boolean GetErrorFlag() { 160 | return isError; 161 | } 162 | } 163 | --------------------------------------------------------------------------------