ocr-stream 1.1__tar.gz → 1.3__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.

Potentially problematic release.


This version of ocr-stream might be problematic. Click here for more details.

Files changed (28) hide show
  1. ocr_stream-1.3/PKG-INFO +50 -0
  2. ocr_stream-1.3/README.md +33 -0
  3. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream/__init__.py +2 -4
  4. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream/__main__.py +5 -2
  5. ocr_stream-1.3/ocr_stream/_version.py +5 -0
  6. ocr_stream-1.3/ocr_stream/extractors.py +127 -0
  7. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream/models/__init__.py +0 -1
  8. ocr_stream-1.3/ocr_stream/models/m_extractors.py +2 -0
  9. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream/models/m_modules_ocr.py +27 -37
  10. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream/modules_ocr.py +215 -172
  11. ocr_stream-1.3/ocr_stream/utils/__init__.py +16 -0
  12. ocr_stream-1.3/ocr_stream.egg-info/PKG-INFO +50 -0
  13. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream.egg-info/SOURCES.txt +0 -2
  14. ocr_stream-1.3/ocr_stream.egg-info/requires.txt +9 -0
  15. {ocr_stream-1.1 → ocr_stream-1.3}/pyproject.toml +12 -10
  16. ocr_stream-1.1/PKG-INFO +0 -57
  17. ocr_stream-1.1/README.md +0 -29
  18. ocr_stream-1.1/ocr_stream/_version.py +0 -5
  19. ocr_stream-1.1/ocr_stream/extractors.py +0 -108
  20. ocr_stream-1.1/ocr_stream/models/m_extractors.py +0 -39
  21. ocr_stream-1.1/ocr_stream/utils/__init__.py +0 -13
  22. ocr_stream-1.1/ocr_stream.egg-info/PKG-INFO +0 -57
  23. ocr_stream-1.1/ocr_stream.egg-info/not-zip-safe +0 -1
  24. ocr_stream-1.1/ocr_stream.egg-info/requires.txt +0 -9
  25. ocr_stream-1.1/setup.py +0 -52
  26. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream.egg-info/dependency_links.txt +0 -0
  27. {ocr_stream-1.1 → ocr_stream-1.3}/ocr_stream.egg-info/top_level.txt +0 -0
  28. {ocr_stream-1.1 → ocr_stream-1.3}/setup.cfg +0 -0
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: ocr_stream
3
+ Version: 1.3
4
+ Summary: Extrair textos de documentos digitalizados e imagens.
5
+ Author: Bruno Chaves
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: PyPDF2
9
+ Requires-Dist: PyMuPDF
10
+ Requires-Dist: reportlab
11
+ Requires-Dist: openpyxl
12
+ Requires-Dist: pandas
13
+ Requires-Dist: Pillow>=11.3.0
14
+ Requires-Dist: opencv-python
15
+ Requires-Dist: convert_stream
16
+ Requires-Dist: soup_files
17
+
18
+ # ocrlib
19
+
20
+ # Uso simples
21
+
22
+
23
+ from ocr_stream import File, TextRecognized, RecognizeImage, RecognizePdf
24
+
25
+ # passo 1:
26
+ # instânciar o objeto para reconhecer texto, utilizando o caminho do tesseract
27
+
28
+ tess: File = File('/usr/bin/tesseract') # Substitua pelo tesseract do seu sistema
29
+ ocr = RecognizeImage.create(path_tesseract=tess)
30
+
31
+ # passo 2:
32
+ # instânciar um arquivo de imagem para extrair o texto.
33
+ image: File = File('path/to/file.png')
34
+
35
+ # passo 3:
36
+ # extrair o texto
37
+ text: str = ocr.image_to_string(image)
38
+ print(text)
39
+
40
+ # passo 4 opcional:
41
+ # você pode salvar um arquivo PDF com o texto extraido
42
+ output_file: File = File('path/to/save.pdf')
43
+ recognized: TextRecognized = ocr.image_recognize(image)
44
+ recognized.to_document().to_file_pdf(output_file)
45
+
46
+ # passo 5 opcional:
47
+ # você pode salvar uma planilha com o texto da imagem
48
+ output_excel: File = File('path/to/file.xlsx')
49
+ recognized: TextRecognized = ocr.image_recognize(image)
50
+ recognized.to_document().to_excel(output_excel)
@@ -0,0 +1,33 @@
1
+ # ocrlib
2
+
3
+ # Uso simples
4
+
5
+
6
+ from ocr_stream import File, TextRecognized, RecognizeImage, RecognizePdf
7
+
8
+ # passo 1:
9
+ # instânciar o objeto para reconhecer texto, utilizando o caminho do tesseract
10
+
11
+ tess: File = File('/usr/bin/tesseract') # Substitua pelo tesseract do seu sistema
12
+ ocr = RecognizeImage.create(path_tesseract=tess)
13
+
14
+ # passo 2:
15
+ # instânciar um arquivo de imagem para extrair o texto.
16
+ image: File = File('path/to/file.png')
17
+
18
+ # passo 3:
19
+ # extrair o texto
20
+ text: str = ocr.image_to_string(image)
21
+ print(text)
22
+
23
+ # passo 4 opcional:
24
+ # você pode salvar um arquivo PDF com o texto extraido
25
+ output_file: File = File('path/to/save.pdf')
26
+ recognized: TextRecognized = ocr.image_recognize(image)
27
+ recognized.to_document().to_file_pdf(output_file)
28
+
29
+ # passo 5 opcional:
30
+ # você pode salvar uma planilha com o texto da imagem
31
+ output_excel: File = File('path/to/file.xlsx')
32
+ recognized: TextRecognized = ocr.image_recognize(image)
33
+ recognized.to_document().to_excel(output_excel)
@@ -1,10 +1,8 @@
1
1
  #!/usr/bin/env python3
2
2
 
3
- from .models.m_modules_ocr import (
4
- LibraryOCR,
5
- )
6
-
3
+ from .models.m_modules_ocr import LibraryOCR
7
4
  from .modules_ocr import TextRecognized
5
+ from .utils import File, Directory, InputFiles, UserFileSystem
8
6
  from .extractors import RecognizeImage, RecognizePdf
9
7
  from ._version import __version__, __modify_data__
10
8
 
@@ -5,8 +5,7 @@
5
5
  Configuração instalação:
6
6
  ------------------------------------------------------------
7
7
  $ pip3 install -r requirements.txt
8
- $ pip3 install https://gitlab.com/bschaves/pdflib/-/archive/V1.0/pdflib-V1.0.zip
9
-
8
+
10
9
  ------------------------------------------------------------
11
10
  Referências:
12
11
  ------------------------------------------------------------
@@ -22,6 +21,7 @@ https://github.com/h/pytesseract
22
21
  pyocr
23
22
  https://gitlab.gnome.org/World/OpenPaperwork/pyocr
24
23
  """
24
+
25
25
  import sys, os
26
26
  this_file = os.path.abspath(os.path.relpath(__file__))
27
27
  dir_of_project = os.path.dirname(this_file)
@@ -30,14 +30,17 @@ sys.path.insert(0, dir_of_project)
30
30
  from convert_stream import print_title
31
31
  from ocr_stream import __version__, __modify_data__
32
32
 
33
+
33
34
  def test():
34
35
  # /usr/bin/tesseract
35
36
  # /usr/share/tesseract-ocr/5/tessdata
36
37
  pass
37
38
 
39
+
38
40
  def main():
39
41
  print_title(f' ocrlib Versão: {__version__} | Atualização: {__modify_data__} ')
40
42
  test()
41
43
 
44
+
42
45
  if __name__ == '__main__':
43
46
  main()
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+
4
+ __version__ = '1.3'
5
+ __modify_data__ = '2025-07-06'
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+ from typing import List
4
+ from ocr_stream.utils import (
5
+ File, Directory, ImageObject,
6
+ DataFrame, PageDocumentPdf,
7
+ DocumentPdf, PdfStream, LibraryPDF,
8
+ )
9
+ from ocr_stream.models import LibraryOCR
10
+ from ocr_stream.modules_ocr import ModuleOcr, TextRecognized, BinaryTesseract
11
+ from convert_stream import LibImageToPDF, ConvertPdfToImage, CreatePbar
12
+ from soup_files import ProgressBarAdapter
13
+
14
+
15
+ class RecognizeImage(object):
16
+ """
17
+ Reconhecer textos em imagens com pytesseract|pyocr usando o tesseract
18
+ """
19
+
20
+ def __init__(self, module_ocr):
21
+ super().__init__()
22
+ self.module_ocr: ModuleOcr = module_ocr
23
+
24
+ def image_content_data(self, img: ImageObject | File) -> DataFrame:
25
+ """
26
+ Retorna uma tabela estruturada com os dados reconhecidos da imagem.
27
+
28
+ Este método extrai as informações contidas em uma imagem e as organiza em
29
+ um DataFrame com colunas como o texto detectado, coordenadas da caixa delimitadora,
30
+ nível do OCR e confiabilidade, entre outras.
31
+
32
+ Parâmetros:
33
+ img (ImageObject | File): A imagem a ser processada, podendo ser um objeto
34
+ `ImageObject` ou um arquivo `File`.
35
+
36
+ Retorna:
37
+ DataFrame: Uma tabela contendo os dados reconhecidos na imagem.
38
+
39
+ Lança:
40
+ ValueError: Se o tipo do parâmetro `img` não for `ImageObject` ou `File`.
41
+
42
+ @param img: Imagem a ser processada, podendo ser uma instância de `ImageObject`
43
+ ou um arquivo `File`.
44
+ @type img: ImageObject | File
45
+
46
+ @rtype: pandas.DataFrame
47
+ @return: Um DataFrame com os dados reconhecidos na imagem.
48
+
49
+ @raise ValueError: Caso o tipo de `img` não seja `ImageObject` nem `File`.
50
+ """
51
+ if isinstance(img, File):
52
+ return self.module_ocr.image_content_data(ImageObject.create_from_file(img))
53
+ elif isinstance(img, ImageObject):
54
+ return self.module_ocr.image_content_data(img)
55
+ else:
56
+ raise ValueError(f'{__class__.__name__}\nUse: ImageObject() ou File(), não {type(img)}')
57
+
58
+ def image_recognize(self, img: ImageObject | File) -> TextRecognized:
59
+ if isinstance(img, File):
60
+ return self.module_ocr.image_recognize(ImageObject.create_from_file(img))
61
+ elif isinstance(img, ImageObject):
62
+ return self.module_ocr.image_recognize(img)
63
+ else:
64
+ raise ValueError(f'{__class__.__name__}\nUse: ImageObject() ou File(), não {type(img)}')
65
+
66
+ def image_to_string(self, img: ImageObject | File) -> str:
67
+ if isinstance(img, File):
68
+ return self.module_ocr.imag_to_string(ImageObject.create_from_file(img))
69
+ elif isinstance(img, ImageObject):
70
+ return self.module_ocr.imag_to_string(img)
71
+ else:
72
+ raise ValueError(f'{__class__.__name__}\nUse: ImageObject() ou File(), não {type(img)}')
73
+
74
+ @classmethod
75
+ def create(
76
+ cls,
77
+ library_ocr: LibraryOCR = LibraryOCR.PYTESSERACT,
78
+ *,
79
+ binary_tess: BinaryTesseract = BinaryTesseract(),
80
+ ) -> RecognizeImage:
81
+ #
82
+ module_ocr = ModuleOcr.create(library_ocr, binary_tess=binary_tess)
83
+ return cls(module_ocr)
84
+
85
+
86
+ class RecognizePdf(object):
87
+ def __init__(
88
+ self,
89
+ recognize_image: RecognizeImage, *,
90
+ pbar: ProgressBarAdapter = CreatePbar().get()
91
+ ):
92
+ self.recognize_image: RecognizeImage = recognize_image
93
+ self.pdf_to_image: ConvertPdfToImage = ConvertPdfToImage.create()
94
+ self.pbar: ProgressBarAdapter = pbar
95
+
96
+ def recognize_page_pdf(self, page: PageDocumentPdf) -> PageDocumentPdf:
97
+ """
98
+ Converte a página em Imagem, reconhece o texto com OCR e
99
+ retorna uma nova página com o texto reconhecido.
100
+ """
101
+ img: ImageObject = self.pdf_to_image.from_page_pdf(page)
102
+ text_recognized: TextRecognized = self.recognize_image.image_recognize(img)
103
+ return text_recognized.to_page_pdf()
104
+
105
+ def recognize_document(self, doc: DocumentPdf) -> DocumentPdf:
106
+ new_pages: List[PageDocumentPdf] = []
107
+
108
+ for n, page in enumerate(doc.get_pages()):
109
+ self.pbar.update(
110
+ ((n+1)/doc.get_num_pages()) * 100,
111
+ f'Reconhecendo página PDF [{n+1} de {doc.get_num_pages()}]',
112
+ )
113
+ recognized_page: PageDocumentPdf = self.recognize_page_pdf(page)
114
+ new_pages.append(recognized_page)
115
+ return DocumentPdf(pages=new_pages)
116
+
117
+ @classmethod
118
+ def create(
119
+ cls,
120
+ library_ocr=LibraryOCR.PYTESSERACT,
121
+ *,
122
+ binary_tess: BinaryTesseract = BinaryTesseract(),
123
+ pbar: ProgressBarAdapter = CreatePbar().get(),
124
+ ) -> RecognizePdf:
125
+ #
126
+ recognize_image = RecognizeImage.create(library_ocr, binary_tess=binary_tess)
127
+ return cls(recognize_image, pbar=pbar)
@@ -1,3 +1,2 @@
1
1
  #!/usr/bin/env python3
2
2
  from .m_modules_ocr import LibraryOCR, ABCTextRecognized, ABCModuleOcr
3
- from .m_extractors import ABCRecognizeImage
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env python3
2
+
@@ -8,71 +8,61 @@ from pandas import DataFrame
8
8
  from soup_files import File, Directory
9
9
  from convert_stream import ImageObject, DocumentPdf, PageDocumentPdf, LibraryImage
10
10
 
11
+
11
12
  class LibraryOCR(Enum):
12
13
  PYTESSERACT = 'pytesseract'
13
14
  PYOCR = 'pyocr'
14
-
15
-
15
+
16
+
16
17
  class ABCTextRecognized(ABC):
17
- def __init__(self, bytes_recognized:bytes):
18
+ def __init__(self, bytes_recognized: bytes):
18
19
  super().__init__()
19
- self.bytes_recognized:bytes = bytes_recognized
20
-
20
+ self.bytes_recognized: bytes = bytes_recognized
21
+
21
22
  @abstractmethod
22
23
  def to_string(self) -> str:
23
24
  pass
24
-
25
+
25
26
  @abstractmethod
26
27
  def to_page_pdf(self) -> PageDocumentPdf:
27
28
  pass
28
-
29
+
29
30
  @abstractmethod
30
31
  def to_document(self) -> DocumentPdf:
31
32
  pass
32
-
33
+
33
34
  @abstractmethod
34
- def to_dataframe(self, column:str='TEXT') -> DataFrame:
35
+ def to_dataframe(self, separator: str = '\n', column_text: str = 'TEXT') -> DataFrame:
35
36
  pass
36
-
37
+
37
38
  @abstractmethod
38
- def to_dict(self) -> Dict[str, List[str]]:
39
+ def to_dict(self, separator: str = '\n', column_text: str = 'TEXT') -> Dict[str, List[str]]:
39
40
  pass
40
-
41
+
42
+
41
43
  #======================================================================#
42
44
  # Abstração para o módulo que extrai o texto das imagens (OCR)
43
45
  # pode ser implementado com pytesseract ou outros.
44
46
  #======================================================================#
47
+
48
+
45
49
  class ABCModuleOcr(ABC):
46
- def __init__(self, *, cmd_executable:File, lang:str=None, tess_data_dir:Directory=None):
47
- self.cmd_executable:File = cmd_executable
48
- self.lang:str = lang
49
- self.tess_data_dir:Directory = tess_data_dir
50
- self.current_library_ocr:LibraryOCR = None
51
-
50
+
51
+ def __init__(self, *, cmd_executable: File, lang: str = None, tess_data_dir: Directory = None):
52
+ self.cmd_executable: File = cmd_executable
53
+ self.lang: str = lang
54
+ self.tess_data_dir: Directory = tess_data_dir
55
+ self.current_library_ocr: LibraryOCR = None
56
+
52
57
  @abstractmethod
53
- def image_recognize(self, img:ImageObject) -> ABCTextRecognized:
58
+ def image_recognize(self, img: ImageObject) -> ABCTextRecognized:
54
59
  pass
55
-
60
+
56
61
  @abstractmethod
57
62
  def image_content_data(self, img: ImageObject) -> DataFrame:
58
63
  pass
59
-
64
+
60
65
  @abstractmethod
61
- def imag_to_string(self, img:ImageObject) -> str:
62
- pass
63
-
64
- @classmethod
65
- def create(
66
- cls,
67
- library_ocr:LibraryOCR=LibraryOCR.PYTESSERACT,
68
- *,
69
- path_tesseract:File,
70
- lang:str=None,
71
- tess_data_dir:Directory=None,
72
- ) -> ABCModuleOcr:
66
+ def imag_to_string(self, img: ImageObject) -> str:
73
67
  pass
74
-
75
-
76
-
77
68
 
78
-