Commit 10fa2cee466ca399d13920a1712ab6c09b900c19

Authored by Nei Jobson da Costa Carneiro
2 parents 3f8c1b91 d7374263
Exists in master

Merge branch 'Correcoes_sobre_1.0.0' into 'master'

Correcoes sobre 1.0.0

Correções, melhoria do INSTALL e inclusão dos arquivos workflow.pdf e workflow.vsd com Workflow de funcionamento da solução.

/usr/local/bin/ocr - Fix issue when pdf page had no images within
INSTALL.txt - Improving instructions, added requirements
workflow.pdf e workflow.vsd - Added script workflow graph

See merge request !1
INSTALL.txt
1   -# Configure o script, alterando as variáveis no arquivo 'usr/local/bin/ocr':
2   - # @BASE_DIRS: Lista de diretórios base para a busca de arquivos --> cada diretório base irá ter sua própria instância do script
3   - # @SUB_DIRS: Subdiretórios de entrada, saída, backup do arquivos originais, temporário e de arquivos com erro
4   - # $MAX_FILES: Número máximo de arquivos a serem processados simultaneamente por diretório de entrada (default: 2)
5   - # $MAX_PGS: Número máximo de páginas que podem ser processadas simultanemante por arquivo de entrada (default: no. de CPUs)
6   - # Essas variáveis controlam o número máximo de instâncias de processos simultâneas = Num. de diretorios X MAX_FILES X MAX_PGS.
7   - # Recomenda-se que o equipamento tenha em torno de 1,5 GB de RAM para cada core de CPU de forma a evitar swap. Se isso não for possível, pode ser reduzido o número de processos ou arquivos simultâneos.
8   -
9   -# Para operação multi instância, basta instalar quantos servidores forem necessários e eles podem ter acesso aos mesmos diretórios de entrada que podem ser compatilhamentos SAMBA/CIFS/Windows ou NFS.
10   -
11   -
12   -# Configuração e instalação do OCR server:
13   -
14   -# Compilando os pré-requisitos: máquina de COMPILAÇÃO APENAS -- (RedHat) --> os requisitos de runtime estão abaixo e são menores
15   - yum -y install autoconf make gcc-java gcc gcc-c++ subversion pkg-config automake libtool yasm cmake git libgcj
16   - yum -y install libtiff-devel libpng-devel openjpeg-devel libjpeg-turbo-devel giflib-devel libwebp-devel zlib-devel libicu-devel pango-devel cairo-devel fontconfig-devel gettext-devel
17   -
18   -# Ubuntu
19   - apt-get install build-essential cmake libtool yasm pkg-config subversion git libgcj14
20   - apt-get install libtiff-dev libpng-dev libopenjpeg-dev libjpeg8-dev libjpeg-turbo8-dev libjpeg-dev libgif-dev zlib1g-dev libicu-dev libpango1.0-dev libcairo2-dev libfontconfig1-dev libgettextpo-dev
21   -
22   - cd /usr/local/src
23   -
24   - for i in \
25   - https://github.com/tesseract-ocr/langdata.git \
26   - https://github.com/DanBloomberg/leptonica.git \
27   - https://github.com/libav/libav.git \
28   - https://github.com/tesseract-ocr/tessdata.git \
29   - https://github.com/tesseract-ocr/tesseract.git \
30   - git://git.freedesktop.org/git/poppler/poppler.git \
31   - git://git.freedesktop.org/git/poppler/test.git \
32   - https://github.com/Flameeyes/unpaper.git \
33   - https://github.com/ocaml/ocaml.git \
34   - https://gitlab.camlcity.org/gerd/lib-findlib.git \
35   - https://github.com/johnwhitington/camlpdf.git \
36   - https://github.com/johnwhitington/cpdf-source.git \
37   - ; do git clone $i; done
38   -
39   - wget http://www.itzgeek.com/msttcore-fonts-2.0-3.noarch.rpm
40   - rpm -Uvh msttcore-fonts-2.0-3.noarch.rpm
41   - rm -f msttcore-fonts-2.0-3.noarch.rpm
42   -
43   - wget https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/pdftk-2.02-src.zip
44   - unzip pdftk-2.02-src.zip
45   - rm -f pdftk-2.02-src.zip
46   -
47   -# Leptonica
48   - cd leptonica && ./autobuild && ./configure && make -j 8 all install && cd ..
  1 +# OCR Server 1.0.1 - (c) Agencia Nacional de Telecomunicacoees
  2 +#
  3 +# This script monitors a set of input directories for PDF files
  4 +# once a new file is detected, it is processes through tesseract OCR
  5 +# in order to generate a new file with a hidden searchable text layer
  6 +#
  7 +# It may be distributed under the conditions of the LGPL v2.1 license.
  8 +#
  9 +# Author: Guilherme Chehab
  10 +#
  11 +# Version History:
  12 +# 0.1 Initial single server version
  13 +# 0.2 Check if page already has the html hidden layer, if so, ignore it
  14 +# 0.3 Solved issues about various image enconding types
  15 +# 0.4 Added a postnormalization step to ensure all output pdf pages have
  16 +# the same size and orientations as the original files
  17 +# 0.5 Used input file renaming as a way to sync multiple parallel instances,
  18 +# that way, it is minimized the risk of same file being OCRed multiple times.
  19 +# 0.6 Added a default handler for unknown image encoding using jpeg encoding
  20 +# 0.7 Solved an issue with files with more than 1000 pages
  21 +# 1.0 First release version
  22 +# 1.0.1 Solving error when file has no images
  23 +#
  24 +# TODO: - Changes get_imgs and OCR processing to enable pages with more than one image -- it
  25 +# would not work on previous versions that assumed #pages = #imgs. Version 1.1 counts them
  26 +# diferently but does not treat it adequately
  27 +#
  28 +# Check software requirements on the comments bellow
  29 +#
  30 +# To configure input dirs change @BASE_DIRS and @SUB_DIRS variables
  31 +#
  32 +#
  33 +# O servidor OCR depende dos seguintes componentes:
  34 +# - Perl 5.10.1, com seguintes módulos:
  35 +# - File::Find::Rule
  36 +# - File::Basename
  37 +# - File::Copy
  38 +# - File::Path
  39 +# - File::Touch
  40 +# - Sys::Syslog
  41 +# - Sys::Hostname
  42 +# - IPC::Open3
  43 +# - IO::Select
  44 +# - POSIX
  45 +# - Tesseract-ocr 3.05, com dicionários inglês e português
  46 +# - Pdftk 2.02
  47 +# - Poppler-utils 0.42.0
  48 +# - Cpdf 3.3
  49 +# - ImageMagick 6.7.2-7
  50 +#
  51 +# Na ausência deles na distribuição do sistema operacional, o uso de versões antigas desses componentes podem comprometer o correto funcionamento do sistema
  52 +# Dessa forma, pode ser necessário compilar os componentes faltantes, assim como as bibliotecas necessárias para o seu correto funcionamento.
  53 +# Esse arquivo contem informações quanto aos procedimentos para instalar e configurar o sistema pressupondo o pior caso, qual seja, a necessidade de compilação dos componentes.
  54 +#
  55 +## ATENÇÃO: se algum componente abaixo não estiver disponível no repositório padrão para o Linux utilizado, deve-se proceder com a compilação da versão mais recente do componente disponibilizado em outros repositórios para que seja instalado no Linux a ser utilizado.
  56 +#
  57 +# Configure o script, alterando as variáveis no arquivo '/usr/local/bin/ocr':
  58 +#
  59 +# @BASE_DIRS: Lista de diretórios base para a busca de arquivos --> cada diretório base irá ter sua própria instância do script
  60 +# @SUB_DIRS: Subdiretórios de entrada, saída, backup do arquivos originais, temporário e de arquivos com erro
  61 +# $MAX_FILES: Número máximo de arquivos a serem processados simultaneamente por diretório de entrada (default: 2)
  62 +# $MAX_PGS: Número máximo de páginas que podem ser processadas simultanemante por arquivo de entrada (default: no. de CPUs)
  63 +# Essas variáveis controlam o número máximo de instâncias de processos simultâneas = Num. de diretorios X MAX_FILES X MAX_PGS.
  64 +# Recomenda-se que o equipamento tenha em torno de 1,5 GB de RAM para cada core de CPU de forma a evitar swap. Se isso não for possível, pode ser reduzido o número de processos ou arquivos simultâneos.
  65 +# A configuração do servidor pode ser dimensionada com base no tempo desejado para processamento de grandes arquivos (> 100 páginas). Cada página tem sua própria thread de processamento, até o limite de $MAX_PGS, cujo default é o no. de cores de CPU. Em média cada página demora em torno de 18 segundos em uma CPU Xeon E5 4670@2.6GHz. Assim, com 16 CPUs, o desempenho agregado é em torno de 1,2 segundos por página.
  66 +#
  67 +# Para operação multi instância, basta instalar quantos servidores forem necessários e eles podem ter acesso aos mesmos diretórios de entrada que podem ser compartilhamentos SAMBA/CIFS/Windows ou NFS.
  68 +#
  69 +#
  70 +# ----------------------- COMPILAÇÃO dos pré requisitos (obs.: os comandos de devem ser executados como root)
  71 +#
  72 +#
  73 +# Compilando os pré-requisitos: máquina de COMPILAÇÃO APENAS
  74 +#
  75 +# RedHat 6.7:
  76 +yum -y install autoconf make gcc-java gcc gcc-c++ subversion pkg-config automake libtool yasm cmake git libgcj
  77 +yum -y install libtiff-devel libpng-devel openjpeg-devel libjpeg-turbo-devel giflib-devel libwebp-devel zlib-devel libicu-devel pango-devel cairo-devel fontconfig-devel gettext-devel
  78 +cd /tmp
  79 +wget http://www.itzgeek.com/msttcore-fonts-2.0-3.noarch.rpm
  80 +rpm -Uvh msttcore-fonts-2.0-3.noarch.rpm
  81 +rm -f msttcore-fonts-2.0-3.noarch.rpm
  82 +
  83 +# Ubuntu 14.04 Server:
  84 +apt-get install build-essential cmake libtool yasm pkg-config subversion git libgcj14
  85 +apt-get install libtiff-dev libpng-dev libopenjpeg-dev libjpeg8-dev libjpeg-turbo8-dev libjpeg-dev libgif-dev zlib1g-dev libicu-dev libpango1.0-dev libcairo2-dev libfontconfig1-dev libgettextpo-dev
  86 +apt-get install
  87 +apt-get install ttf-mscorefonts-installer
  88 +
  89 +# Ambas plataformas:
  90 +cd /usr/local/src
  91 +
  92 +for i in \
  93 + https://github.com/tesseract-ocr/langdata.git \
  94 + https://github.com/DanBloomberg/leptonica.git \
  95 + https://github.com/libav/libav.git \
  96 + https://github.com/tesseract-ocr/tessdata.git \
  97 + https://github.com/tesseract-ocr/tesseract.git \
  98 + git://git.freedesktop.org/git/poppler/poppler.git \
  99 + git://git.freedesktop.org/git/poppler/test.git \
  100 + https://github.com/Flameeyes/unpaper.git \
  101 + https://github.com/ocaml/ocaml.git \
  102 + https://gitlab.camlcity.org/gerd/lib-findlib.git \
  103 + https://github.com/johnwhitington/camlpdf.git \
  104 + https://github.com/johnwhitington/cpdf-source.git \
  105 +; do git clone $i; done
  106 +
  107 +wget https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/pdftk-2.02-src.zip
  108 +unzip pdftk-2.02-src.zip
  109 +rm -f pdftk-2.02-src.zip
  110 +
  111 +# Tesseract, versão 3.05-dev ou superior
  112 +# Bibliotecas para o Tesseract: Leptonica e Libav
  113 +cd leptonica && ./autobuild && ./configure && make -j 8 all install && cd ..
  114 +
  115 +cd libav && ./configure --enable-sram && make -j8 all install && cd ..
49 116  
50 117 # Tesseract
51   - cd tesseract && ./autogen.sh && ./configure && make -j 8 all install && cd ..
52   - cp -avR tessdata/* /usr/local/share/tessdata/
  118 +cd tesseract && ./autogen.sh && ./configure && make -j 8 all install && cd ..
  119 +cp -avR tessdata/* /usr/local/share/tessdata/
53 120  
54   -# libav
55   - cd libav && ./configure --enable-sram && make -j8 all install && cd ..
  121 +# cpdf, versão 3.3 ou superior
  122 +cd ocaml && ./configure && make world.opt && make install && cd ..
  123 +mkdir -p /usr/local/man/man5
  124 +cd lib-findlib && ./configure && make all && make install && cd ..
  125 +cd camlpdf && sed -i.bak s/\(uint32\)/\(uint32_t\)/g flatestubs.c && make && make install && cd ..
  126 +cd cpdf-source && make all && make install && cp cpdf /usr/local/bin && cd ..
56 127  
57   -# cpdf
58   - cd ocaml && ./configure && make world.opt && make install && cd ..
59   - mkdir -p /usr/local/man/man5
60   - cd lib-findlib && ./configure && make all && make install && cd ..
61   - cd camlpdf && sed -i.bak s/\(uint32\)/\(uint32_t\)/g flatestubs.c && make && make install && cd ..
62   - cd cpdf-source && make all && make install && cp cpdf /usr/local/bin && cd ..
  128 +# pdftk, versão 2.02 ou superior
  129 +cd pdftk-2.02-dist/pdftk && make -f Makefile.Redhat all install && cd ../..
63 130  
64   -# pdftk
65   - cd pdftk-2.02-dist/pdftk && make -f Makefile.Redhat all install && cd ../..
  131 +# poppler-utils, versão 0.42.0 ou superior
  132 +cd poppler && ./autogen.sh && LIBOPENJPEG_LIBS=-l/usr/local/lib/libopenjp2.so LIBOPENJPEG_CFLAGS=-I/usr/local/include ./configure --enable-libopenjpeg=openjpeg2 && make all install && cd ..
66 133  
67   -# poppler
68   - cd poppler && ./autogen.sh && LIBOPENJPEG_LIBS=-l/usr/local/lib/libopenjp2.so LIBOPENJPEG_CFLAGS=-I/usr/local/include ./configure --enable-libopenjpeg=openjpeg2 && make all install && cd ..
  134 +# ----------------------- INSTALAÇÃO (obs.: os comandos de devem ser executados como root)
69 135  
  136 +## Comandos adicionais para configuração do módulo:
  137 +
70 138 # Criação do usuário
71   - adduser ocr
  139 +adduser ocr
72 140  
73 141 # Copie os arquivos ocr ocr-init* para o /home/ocr e, conforme o sistema operacional
74   - cp /home/ocr/ocr /usr/local/bin
75   - cp /home/ocr/ocr-init-rh /etc/init.d/ocr (OU)
76   - cp /home/ocr/ocr-init-Ubuntu /etc/init/ocr
  142 +cp /home/ocr/ocr /usr/local/bin
  143 +cp /home/ocr/ocr-init-rh /etc/init.d/ocr (OU)
  144 +cp /home/ocr/ocr-init-Ubuntu /etc/init/ocr
77 145  
78   -# Auto start (RedHat)
79   - chkconfig --add ocr
80   - chkconfig --level 2345 ocr on
  146 +# Auto start (RedHat 6.7)
  147 +chkconfig --add ocr
  148 +chkconfig --level 2345 ocr on
81 149  
82   -# Auto start (Ubuntu)
83   - update-rd.d ocr defaults
  150 +# Auto start (Ubuntu 14.04)
  151 +update-rd.d ocr defaults
84 152  
85 153 # Create pkg
86   - cd /home/ocr
87   - tar cvozf pkg-ocr.tgz /usr/local/bin /usr/local/lib* /usr/local/man/ /usr/local/sbin/ /usr/local/share/ /usr/local/etc /usr/local/include/ /home/ocr/ocr* /etc/init.d/ocr /etc/rc*.d/*ocr
88   - su
  154 +cd /home/ocr
  155 +tar cvozf pkg-ocr.tgz /usr/local/bin /usr/local/lib* /usr/local/man/ /usr/local/sbin/ /usr/local/share/ /usr/local/etc /usr/local/include/ /home/ocr/ocr* /etc/init.d/ocr /etc/rc*.d/*ocr
  156 +su
89 157  
90 158 # Copie o pacote para os outros servidores e extraia com:
91   - cd /
92   - tar xovzf pkg-ocr.tgz
  159 +cd /
  160 +tar xovzf pkg-ocr.tgz
93 161  
94   -# Instalando pré-requisitos RUNTIME
95   - yum -y install perl-File-Find-Rule-Perl perl-File-Touch libtiff libpng openjpeg-libs libjpeg-turbo giflib zlib libicu pango cairo fontconfig ImageMagick gettext libwebp
96   - yum -y install libtiff libpng openjpeg libjpeg-turbo giflib libwebp zlib libicu pango cairo fontconfig gettext
  162 +# Instalando pré-requisitos RUNTIME em servidores adicionais
97 163  
98   -# Ubuntu
99   - apt-get install libfile-find-rule-perl libfile-find-rule-perl-perl libtiff5 libpng12-0 libopenjpeg2 libjpeg-turbo8 libgif4 zlib1g libicu52 libpango1.0-0 libcairo2 fontconfig imagemagick gettext libwebp5 # libgcj14
100   - apt-get install libtiff5 libpng12-0 libopenjpeg2 libjpeg8 libjpeg-turbo8 libjpeg8 zlib1g libpango1.0-0 libcairo2 libfontconfig1 libgettextpo0
  164 +# Redhat 6.7
  165 +yum -y install perl-File-Find-Rule-Perl perl-File-Touch libtiff libpng openjpeg-libs libjpeg-turbo giflib zlib libicu pango cairo fontconfig ImageMagick gettext libwebp
  166 +yum -y install libtiff libpng openjpeg libjpeg-turbo giflib libwebp zlib libicu pango cairo fontconfig gettext
  167 +
  168 +# Ubuntu 14.04
  169 +apt-get install libfile-find-rule-perl libfile-find-rule-perl-perl libtiff5 libpng12-0 libopenjpeg2 libjpeg-turbo8 libgif4 zlib1g libicu52 libpango1.0-0 libcairo2 fontconfig imagemagick gettext libwebp5 # libgcj14
  170 +apt-get install libtiff5 libpng12-0 libopenjpeg2 libjpeg8 libjpeg-turbo8 libjpeg8 zlib1g libpango1.0-0 libcairo2 libfontconfig1 libgettextpo0
101 171  
102 172 # Inicie o serviço com
103   - service ocr start
104 173 \ No newline at end of file
  174 +service ocr start
105 175 \ No newline at end of file
... ...
usr/local/bin/ocr
1 1 #! /usr/bin/perl -w
2 2 #
3   -# OCR Server 1.0 - (c) Agência Nacional de Telecomunicações
  3 +# OCR Server 1.0.1 - (c) Agencia Nacional de Telecomunicacoes
4 4 #
5 5 # This script monitors a set of input directories for PDF files
6 6 # once a new file is detected, it is processes through tesseract OCR
... ... @@ -21,6 +21,11 @@
21 21 # 0.6 Added a default handler for unknown image encoding using jpeg encoding
22 22 # 0.7 Solved an issue with files with more than 1000 pages
23 23 # 1.0 First release version
  24 +# 1.0.1 Solving error when file has no images
  25 +#
  26 +# TODO: - Changes get_imgs and OCR processing to enable pages with more than one image -- it
  27 +# would not work on previous versions that assumed #pages = #imgs. Version 1.1 counts them
  28 +# diferently but does not treat it adequately
24 29 #
25 30 # Check software requirements on the comments bellow
26 31 #
... ... @@ -288,10 +293,9 @@ sub ocr {
288 293  
289 294 my ($pages, @pg_w, @pg_h, @pg_r);
290 295 $pages = get_pages ($tmp_file, \@pg_w, \@pg_h, \@pg_r);
291   -
292   - my (@img_w, @img_h, @img_t);
293   - $pages = get_imgs ( $tmp_file, \@img_w, \@img_h, \@img_t);
294 296  
  297 + my ($imgs,@page_img, @img_w, @img_h, @img_t);
  298 + $imgs = get_imgs ( $tmp_file, \@page_img, \@img_w, \@img_h, \@img_t);
295 299  
296 300 for ( my $i=0; $i< $pages; $i++ ) {
297 301 my $pg = sprintf ("pg_%06d", $i+1);
... ... @@ -308,18 +312,21 @@ sub ocr {
308 312 $pids{$pid}=$pg;
309 313 } else {
310 314 $0 = "ocr $in_name (".($i+1)."/$pages)" if(!$DEBUG);
311   - print "\t\t${in_file}: ".(${i}+1)." / $pages: $pg_w[$i] x $pg_h[$i] - $pg_r[$i] & $img_w[$i] x $img_h[$i], $img_t[$i]\n" if $DEBUG;
312 315  
313   - if (! defined $img_t[$i] ) {
  316 + if (is_ocred ("${tmpdir}/${pg}.pdf")) {
314 317 move ("${tmpdir}/${pg}.pdf","${tmpdir}/${pg}-cpdf.pdf");
  318 + print "\t\t${in_file}: ".(${i}+1)." / $pages: Page already has text layer, ignoring page\n" if $DEBUG;
315 319 exit 0;
316 320 }
317 321  
318   - if (is_ocred ("${tmpdir}/${pg}.pdf")) {
  322 + if (! defined $img_t[$i] ) {
319 323 move ("${tmpdir}/${pg}.pdf","${tmpdir}/${pg}-cpdf.pdf");
  324 + print "\t\t${in_file}: ".(${i}+1)." / $pages: Undefined image type on page, ignoring page\n" if $DEBUG;
320 325 exit 0;
321 326 }
322 327  
  328 + print "\t\t${in_file}: ".(${i}+1)." / $pages: $pg_w[$i] x $pg_h[$i] - $pg_r[$i] & $img_w[$i] x $img_h[$i], $img_t[$i]\n" if $DEBUG;
  329 +
323 330 undef $cmd;
324 331  
325 332 if ($img_t[$i] eq "gray") {
... ... @@ -462,8 +469,8 @@ sub get_pages {
462 469 }
463 470  
464 471 sub get_imgs {
465   - my ($in_file, $w, $h, $t) = @_;
466   - my ($dumb, $i, $width, $height, $type);
  472 + my ($in_file, $page_img, $w, $h, $t) = @_;
  473 + my ($dumb, $i, $page, $width, $height, $type);
467 474  
468 475 my ($exit, $cmd, @lines, @err) = exec_cmd("${PDFIMAGES} -list \"${in_file}\"");
469 476  
... ... @@ -471,15 +478,16 @@ sub get_imgs {
471 478 chomp $line;
472 479 $line =~ s/^ {1,}//;
473 480 if ( $line =~ /image|mask/ ) {
474   - ($i , $dumb, $dumb, $width, $height, $type) = split / {1,}/,$line;
475   - @$w[$i-1] = $width;
476   - @$h[$i-1] = $height;
477   - @$t[$i-1] = ( $type eq "-" ? "rgb" : $type );
478   - @$t[$i-1] = ( $type eq "icc" ? "rgb" : $type );
479   - @$t[$i-1] = ( $type eq "index" ? "rgb" : $type );
  481 + ($page, $i , $dumb, $width, $height, $type) = split / {1,}/,$line;
  482 + @$page_img[$page-1]=$i;
  483 + @$w[$page-1] = $width;
  484 + @$h[$page-1] = $height;
  485 + @$t[$page-1] = ( $type eq "-" ? "rgb" : $type );
  486 + @$t[$page-1] = ( $type eq "icc" ? "rgb" : $type );
  487 + @$t[$page-1] = ( $type eq "index" ? "rgb" : $type );
480 488 }
481 489 }
482   - return $i;
  490 + return $i+1;
483 491 }
484 492  
485 493 sub get_rotation {
... ...
workflow.pdf 0 → 100644
No preview for this file type
workflow.vsd 0 → 100644
No preview for this file type