ocr-stream 2.3__tar.gz → 2.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ocr_stream
3
- Version: 2.3
3
+ Version: 2.3.2
4
4
  Summary: Extrair textos de documentos digitalizados e imagens.
5
5
  Author: Bruno Chaves
6
6
  Requires-Python: >=3.11
@@ -12,7 +12,7 @@ Requires-Dist: pandas
12
12
  Requires-Dist: requests>=2.32.4
13
13
  Requires-Dist: opencv-python
14
14
  Requires-Dist: pytesseract
15
- Requires-Dist: convert_stream>=2.3
15
+ Requires-Dist: convert_stream>=2.3.2
16
16
  Requires-Dist: soup_files>=1.4
17
17
 
18
18
  # ocrlib
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env python3
2
+
3
+ from ocr_stream.modules import *
4
+ from ocr_stream.bin_tess import BinTesseract, get_path_tesseract_sys
5
+ from ocr_stream.ocr import TesseractOcr, TextRecognized, DEFAULT_LIB_OCR
6
+ from ocr_stream.recognize import RecognizeImage, RecognizePdf
7
+ from soup_files import File
8
+ from convert_stream import (
9
+ ImageObject, DocumentPdf, ConvertPdfToImages, ColumnsTable, CollectionImages, FindText
10
+ )
11
+ from pandas import DataFrame
12
+ from soup_files import JsonConvert, ProgressBarAdapter, CreatePbar
13
+
14
+
15
+ def read_images(
16
+ images: list[ImageObject], *,
17
+ pbar: ProgressBarAdapter = CreatePbar().get()
18
+ ) -> DocumentPdf:
19
+ pbar.start()
20
+ print()
21
+ max_num = len(images)
22
+ pages = []
23
+ rec = RecognizeImage()
24
+ for idx, image in enumerate(images):
25
+ pbar.update(
26
+ ((idx + 1) / max_num) * 100,
27
+ f'[OCR] {idx + 1} / {max_num}',
28
+ )
29
+ out = rec.image_recognize(image).to_page_pdf()
30
+ pages.append(out)
31
+ tmp_doc = DocumentPdf.create_from_pages(pages)
32
+ print()
33
+ pbar.stop()
34
+ return tmp_doc
35
+
36
+
37
+ def read_document(
38
+ document: DocumentPdf, *,
39
+ dpi: int = 300,
40
+ pbar: ProgressBarAdapter = CreatePbar().get()
41
+ ) -> DocumentPdf:
42
+ pbar.start()
43
+ print()
44
+ convert = ConvertPdfToImages.create(document)
45
+ convert.set_pbar(pbar)
46
+ images = convert.to_images(dpi=dpi)
47
+ print()
48
+ return read_images(images, pbar=pbar)
49
+
50
+
51
+ class SearchableTextImage(object):
52
+ """
53
+ Esta classe serve para armazenar textos filtrados em documentos PDF
54
+ guardando o texto buscado e outros elementos como a página em que o texto foi
55
+ encontrado, linha e o nome do respetivo arquivo.
56
+ """
57
+ def __init__(self, silent: bool = False):
58
+ self.silent = silent
59
+ self.elements: dict[str, list[str]] = {
60
+ ColumnsTable.NUM_LINE.value: [],
61
+ ColumnsTable.TEXT.value: [],
62
+ ColumnsTable.FILE_PATH.value: [],
63
+ }
64
+
65
+ def __repr__(self):
66
+ return f'{__class__.__name__}: {self.elements}'
67
+
68
+ def is_empty(self) -> bool:
69
+ return len(self.elements[ColumnsTable.TEXT.value]) == 0
70
+
71
+ @property
72
+ def first(self) -> dict[str, str]:
73
+ if self.is_empty():
74
+ return {}
75
+ return {
76
+ ColumnsTable.NUM_LINE.value: self.elements[ColumnsTable.NUM_LINE.value][0],
77
+ ColumnsTable.TEXT.value: self.elements[ColumnsTable.TEXT.value][0],
78
+ ColumnsTable.FILE_PATH.value: self.elements[ColumnsTable.FILE_PATH.value][0],
79
+ }
80
+
81
+ @property
82
+ def last(self) -> dict[str, str]:
83
+ if self.is_empty():
84
+ return {}
85
+ return {
86
+ ColumnsTable.NUM_LINE.value: self.elements[ColumnsTable.NUM_LINE.value][-1],
87
+ ColumnsTable.TEXT.value: self.elements[ColumnsTable.TEXT.value][-1],
88
+ ColumnsTable.FILE_PATH.value: self.elements[ColumnsTable.FILE_PATH.value][-1],
89
+ }
90
+
91
+ @property
92
+ def length(self) -> int:
93
+ return len(self.elements[ColumnsTable.TEXT.value])
94
+
95
+ @property
96
+ def files(self) -> list[str]:
97
+ if self.is_empty():
98
+ return []
99
+ return self.elements[ColumnsTable.FILE_PATH.value]
100
+
101
+ def get_item(self, idx: int) -> dict[str, str]:
102
+ try:
103
+ return {
104
+ ColumnsTable.NUM_LINE.value: self.elements[ColumnsTable.NUM_LINE.value][idx],
105
+ ColumnsTable.TEXT.value: self.elements[ColumnsTable.TEXT.value][idx],
106
+ ColumnsTable.FILE_PATH.value: self.elements[ColumnsTable.FILE_PATH.value][idx],
107
+ }
108
+ except Exception as err:
109
+ if not self.silent:
110
+ print(err)
111
+ return {}
112
+
113
+ def add_line(self, text, *, num_line: str, file: str) -> None:
114
+ if not self.silent:
115
+ print('----------------------')
116
+ print(f'{file} => {text}')
117
+ self.elements[ColumnsTable.NUM_LINE.value].append(num_line)
118
+ self.elements[ColumnsTable.TEXT.value].append(text)
119
+ self.elements[ColumnsTable.FILE_PATH.value].append(file)
120
+
121
+ def clear(self) -> None:
122
+ for _k in self.elements.keys():
123
+ self.elements[_k].clear()
124
+
125
+ def to_string(self) -> str:
126
+ """
127
+ Retorna o texto da coluna TEXT em formato de string
128
+ ou 'nas' em caso de erro nas = Not a String
129
+ """
130
+ try:
131
+ return ' '.join(self.elements[ColumnsTable.TEXT.value])
132
+ except Exception as e:
133
+ print(e)
134
+ return 'nas'
135
+
136
+ def to_data_frame(self) -> DataFrame:
137
+ return DataFrame.from_dict(self.elements)
138
+
139
+ def to_file_json(self, file: File):
140
+ """Exporta os dados da busca para arquivo .JSON"""
141
+ dt = JsonConvert.from_dict(self.elements).to_json_data()
142
+ dt.to_file(file)
143
+
144
+ def to_file_excel(self, file: File):
145
+ """Exporta os dados da busca para um arquivo .XLSX"""
146
+ try:
147
+ self.to_data_frame().to_excel(file.absolute())
148
+ except Exception as e:
149
+ print(e)
150
+
151
+
152
+ class FindTextImages(object):
153
+
154
+ def __init__(
155
+ self, collection_images: CollectionImages,
156
+ *,
157
+ rec_img: RecognizeImage = RecognizeImage(),
158
+ pbar: ProgressBarAdapter = CreatePbar().get(),
159
+ ):
160
+ self.collection_images: CollectionImages = collection_images
161
+ self._rec_img: RecognizeImage = rec_img
162
+ self.pbar: ProgressBarAdapter = pbar
163
+
164
+ def find(
165
+ self, text: str,
166
+ separator: str = '\n',
167
+ iqual: bool = False,
168
+ case: bool = False,
169
+ silent: bool = False,
170
+ ) -> SearchableTextImage:
171
+ """
172
+ Filtrar texto retornando a primeira ocorrência do Documento PDF.
173
+ """
174
+ print()
175
+ self.pbar.start()
176
+ _searchable = SearchableTextImage(silent)
177
+
178
+ max_num: int = self.collection_images.length
179
+ for idx, image in enumerate(self.collection_images):
180
+ self.pbar.update(
181
+ ((idx + 1) / max_num) * 100,
182
+ f'[Pesquisando]: {idx + 1} / {max_num} Aguarde...',
183
+ )
184
+ text_str_in_page: str = self._rec_img.image_to_string(image)
185
+
186
+ if (text_str_in_page == 'nas') or (text_str_in_page is None):
187
+ continue
188
+ try:
189
+ fd = FindText(text_str_in_page, separator=separator)
190
+ idx = fd.find_index(text, iqual=iqual, case=case)
191
+ if idx is None:
192
+ continue
193
+ math_text = fd.get_index(idx)
194
+ except Exception as err:
195
+ print(f'{__class__.__name__} {err}')
196
+ else:
197
+ _searchable.add_line(
198
+ math_text,
199
+ num_line=str(idx + 1),
200
+ file=image.name,
201
+ )
202
+ return _searchable
203
+ self.pbar.stop()
204
+ print()
205
+ return _searchable
206
+
207
+ def find_all(
208
+ self, text: str,
209
+ separator: str = '\n',
210
+ iqual: bool = False,
211
+ case: bool = False,
212
+ silent: bool = False,
213
+ ) -> SearchableTextImage:
214
+ """
215
+ Filtrar texto em documento PDF e retorna todas as ocorrências do texto
216
+ encontradas no documento, incluindo o número da linha, página e nome do arquivo
217
+ em cada ocorrência.
218
+ """
219
+ print()
220
+ self.pbar.start()
221
+ _searchable = SearchableTextImage(silent)
222
+ max_num: int = self.collection_images.length
223
+ for idx, image in enumerate(self.collection_images):
224
+ self.pbar.update(
225
+ ((idx + 1) / max_num) * 100,
226
+ f'[Pesquisando]: {idx + 1} / {max_num} Aguarde...',
227
+ )
228
+
229
+ text_str_in_page = self._rec_img.image_to_string(image)
230
+ if (text_str_in_page == 'nas') or (text_str_in_page is None):
231
+ continue
232
+ try:
233
+ _values = text_str_in_page.split(separator)
234
+ for num, item in enumerate(_values):
235
+ if case:
236
+ if iqual:
237
+ if text == item:
238
+ _searchable.add_line(
239
+ item,
240
+ num_line=str(num + 1),
241
+ file=image.name,
242
+ )
243
+ else:
244
+ if text in item:
245
+ _searchable.add_line(
246
+ item,
247
+ num_line=str(num + 1),
248
+ file=image.name,
249
+ )
250
+ else:
251
+ if iqual:
252
+ if text.lower() == item.lower():
253
+ _searchable.add_line(
254
+ item,
255
+ num_line=str(num + 1),
256
+ file=image.name,
257
+ )
258
+ else:
259
+ if text.lower() in item.lower():
260
+ _searchable.add_line(
261
+ item,
262
+ num_line=str(num + 1),
263
+ file=image.name,
264
+ )
265
+ except Exception as e:
266
+ print(f'{__class__.__name__} {e}')
267
+ self.pbar.stop()
268
+ print()
269
+ return _searchable
@@ -2,7 +2,7 @@
2
2
  from __future__ import annotations
3
3
  import os
4
4
  from shutil import which
5
- from soup_files import File, Directory, KERNEL_TYPE
5
+ from soup_files import File, KERNEL_TYPE
6
6
 
7
7
 
8
8
  def __get_path_tesseract_unix() -> File | None:
@@ -93,5 +93,3 @@ class BinTesseract(object):
93
93
  if self.__path_tesseract is None:
94
94
  return False
95
95
  return self.__path_tesseract.exists()
96
-
97
-
@@ -17,7 +17,8 @@ MOD_PYOCR: bool = False
17
17
  try:
18
18
  from pytesseract import pytesseract, Output
19
19
  MOD_PYTESSERACT = True
20
- except:
20
+ except Exception as err:
21
+ print(err)
21
22
  pytesseract = None
22
23
  Output = None
23
24
 
@@ -25,7 +26,8 @@ try:
25
26
  import pyocr
26
27
  import pyocr.tesseract
27
28
  MOD_PYOCR = True
28
- except:
29
+ except Exception as err:
30
+ print(err)
29
31
  pyocr = object
30
32
  #pyocr.tesseract = object
31
33
 
@@ -6,20 +6,21 @@ from abc import abstractmethod, ABC
6
6
  from typing import Union
7
7
  from io import BytesIO
8
8
  from pandas import DataFrame
9
- from soup_files import File, Directory
9
+ from soup_files import File
10
10
  from convert_stream import (
11
- ImageObject, DocumentPdf, PageDocumentPdf, MapText, ColumnsTable,
12
- get_hash_from_bytes, DEFAULT_LIB_IMAGE, LibImage
11
+ ImageObject, DocumentPdf, PageDocumentPdf, DEFAULT_LIB_IMAGE, LibImage
13
12
  )
13
+ from convert_stream.mod_types import get_void_metadata
14
+ from convert_stream.mod_types.table_types import ColumnBody
14
15
  from ocr_stream.modules import (
15
- LibOcr, ModuleOcr, DEFAULT_LIB_OCR, MOD_PYOCR, MOD_PYTESSERACT,
16
- pytesseract, Output, pyocr,
16
+ LibOcr, DEFAULT_LIB_OCR, pytesseract, Output, pyocr,
17
17
  )
18
18
  from ocr_stream.bin_tess import BinTesseract
19
19
 
20
20
  try:
21
21
  import pyocr.tesseract
22
- except:
22
+ except Exception as err:
23
+ print(err)
23
24
  pyocr = None
24
25
 
25
26
 
@@ -30,6 +31,7 @@ class TextRecognized(object):
30
31
  """
31
32
 
32
33
  def __init__(self, bytes_recognized: bytes):
34
+ self.metadata: dict[str, str | None] = get_void_metadata()
33
35
  self.bytes_recognized: bytes = bytes_recognized
34
36
  self.list_bad_char: list[str] = [
35
37
  ':', ',', ';', '$', '=',
@@ -51,21 +53,11 @@ class TextRecognized(object):
51
53
  def to_document(self) -> DocumentPdf:
52
54
  return DocumentPdf(BytesIO(self.bytes_recognized))
53
55
 
54
- def to_map(self, separator: str = '\n') -> MapText:
55
- text = self.to_string()
56
- if (text is None) or (text == '') or (text == 'nas'):
57
- return MapText([])
58
- try:
59
- return MapText(text.split(separator))
60
- except Exception as err:
61
- print(err)
62
- return MapText([])
63
-
64
- def to_dict(self, separator: str = '\n') -> dict[str, list[str]]:
65
- return self.to_map(separator).map_elements
56
+ def to_dict(self, separator: str = '\n') -> dict[str, ColumnBody]:
57
+ return self.to_page_pdf().to_dict(separator=separator)
66
58
 
67
59
  def to_dataframe(self, separator='\n') -> DataFrame:
68
- return self.to_map(separator).to_data()
60
+ return DataFrame.from_dict(self.to_dict(separator=separator))
69
61
 
70
62
 
71
63
  class ABCOcrTesseract(ABC):
@@ -166,8 +158,6 @@ class IPyOcr(ABCOcrTesseract):
166
158
  self.lang = lang
167
159
  else:
168
160
  self.lang = langs[0]
169
-
170
- # Ex: Will use tool 'libtesseract'
171
161
  print(f"Will use tool {self._pyOcr.get_name()}")
172
162
 
173
163
  def to_string(self, img: Union[File, ImageObject]) -> str:
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env python3
2
2
  from __future__ import annotations
3
- from convert_stream import ImageObject, LibImage, DocumentPdf, PageDocumentPdf, ConvertPdfToImages, PdfStream
3
+ from convert_stream import ImageObject, DocumentPdf, PageDocumentPdf, ConvertPdfToImages
4
4
  from ocr_stream.bin_tess import BinTesseract
5
- from ocr_stream.modules import LibOcr, DEFAULT_LIB_OCR, ModuleOcr
5
+ from ocr_stream.modules import LibOcr, DEFAULT_LIB_OCR
6
6
  from ocr_stream.ocr import TesseractOcr, TextRecognized
7
7
  from pandas import DataFrame
8
8
  from soup_files import File, ProgressBarAdapter, CreatePbar
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ocr_stream
3
- Version: 2.3
3
+ Version: 2.3.2
4
4
  Summary: Extrair textos de documentos digitalizados e imagens.
5
5
  Author: Bruno Chaves
6
6
  Requires-Python: >=3.11
@@ -12,7 +12,7 @@ Requires-Dist: pandas
12
12
  Requires-Dist: requests>=2.32.4
13
13
  Requires-Dist: opencv-python
14
14
  Requires-Dist: pytesseract
15
- Requires-Dist: convert_stream>=2.3
15
+ Requires-Dist: convert_stream>=2.3.2
16
16
  Requires-Dist: soup_files>=1.4
17
17
 
18
18
  # ocrlib
@@ -5,5 +5,5 @@ pandas
5
5
  requests>=2.32.4
6
6
  opencv-python
7
7
  pytesseract
8
- convert_stream>=2.3
8
+ convert_stream>=2.3.2
9
9
  soup_files>=1.4
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ocr_stream"
7
- version = "2.3"
7
+ version = "2.3.2"
8
8
  authors = [
9
9
  { name="Bruno Chaves"},
10
10
  ]
@@ -21,7 +21,7 @@ dependencies = [
21
21
  "requests>=2.32.4",
22
22
  "opencv-python",
23
23
  "pytesseract",
24
- "convert_stream>=2.3",
24
+ "convert_stream>=2.3.2",
25
25
  "soup_files>=1.4",
26
26
  ]
27
27
 
@@ -1,51 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- from ocr_stream.modules import *
4
- from ocr_stream.bin_tess import BinTesseract, get_path_tesseract_sys
5
- from ocr_stream.ocr import TesseractOcr, TextRecognized, DEFAULT_LIB_OCR
6
- from ocr_stream.recognize import RecognizeImage, RecognizePdf
7
- from soup_files import File, Directory, InputFiles, LibraryDocs, CreatePbar, ProgressBarAdapter
8
- from convert_stream import ImageObject, PdfStream, DocumentPdf, ConvertPdfToImages
9
-
10
-
11
- def read_images(
12
- images: list[ImageObject], *,
13
- pbar: ProgressBarAdapter = CreatePbar().get()
14
- ) -> DocumentPdf:
15
- pbar.start()
16
- print()
17
- max_num = len(images)
18
- pages = []
19
- rec = RecognizeImage()
20
- for idx, image in enumerate(images):
21
- pbar.update(
22
- ((idx + 1) / max_num) * 100,
23
- f'[OCR] {idx + 1} / {max_num}',
24
- )
25
- out = rec.image_recognize(image).to_page_pdf()
26
- pages.append(out)
27
- tmp_doc = DocumentPdf.create_from_pages(pages)
28
- print()
29
- pbar.stop()
30
- return tmp_doc
31
-
32
-
33
- def read_document(
34
- document: DocumentPdf, *,
35
- dpi: int = 300,
36
- pbar: ProgressBarAdapter = CreatePbar().get()
37
- ) -> DocumentPdf:
38
- pbar.start()
39
- print()
40
- convert = ConvertPdfToImages.create(document)
41
- convert.set_pbar(pbar)
42
- images = convert.to_images(dpi=dpi)
43
- print()
44
- return read_images(images, pbar=pbar)
45
-
46
-
47
-
48
-
49
-
50
-
51
-
File without changes
File without changes