ocr-stream 2.6.8__tar.gz → 2.6.9__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.5
2
2
  Name: ocr_stream
3
- Version: 2.6.8
3
+ Version: 2.6.9
4
4
  Summary: Extrair textos de documentos digitalizados e imagens.
5
5
  Requires-Python: >=3.12
6
6
  Requires-Dist: convert-stream>=2.6.9
@@ -13,7 +13,7 @@ from shutil import which
13
13
  from abc import abstractmethod, ABC
14
14
  from io import BytesIO
15
15
  from typing import TypeVar, NewType, Any, Callable, Iterable, Iterator, TYPE_CHECKING
16
- from types import ModuleType
16
+ from types import ModuleType
17
17
  from dataclasses import dataclass, field
18
18
  from enum import StrEnum
19
19
  import threading
@@ -54,6 +54,7 @@ if not cs.MOD_IMG_OPENCV:
54
54
 
55
55
  import cv2
56
56
 
57
+
57
58
  class FileTesseractNotFoundError(ValueError):
58
59
 
59
60
  def __init__(self, *args: object) -> None:
@@ -74,9 +75,10 @@ Output = None
74
75
  if TYPE_CHECKING:
75
76
  from pytesseract import pytesseract
76
77
 
78
+
77
79
  def load_modules_ocr_stream() -> None:
78
80
  global MOD_PYTESSERACT
79
- global pytesseract, Output
81
+ global pytesseract, Output
80
82
 
81
83
  # Atualiza os caches de descoberta de módulos.
82
84
  importlib.invalidate_caches()
@@ -98,9 +100,11 @@ def load_modules_ocr_stream() -> None:
98
100
  # convert_stream
99
101
  cs.load_modules_convert_stream()
100
102
 
103
+
101
104
  # Carregar módulos
102
105
  load_modules_ocr_stream()
103
106
 
107
+
104
108
  def _get_path_tesseract_unix() -> File | None:
105
109
  out = which("tesseract")
106
110
  if out is None:
@@ -377,10 +381,14 @@ class PyTesseractOcr(TesseractOcrAbstract):
377
381
  _config = f"{self._get_tess_dir_config()} --oem 3 --psm 6"
378
382
 
379
383
  if self.lang is None:
380
- return self.modTess.image_to_string(_im, config=_config) #config=self._get_tess_dir_config())
384
+ return self.modTess.image_to_string(
385
+ _im, config=_config
386
+ ) # config=self._get_tess_dir_config())
381
387
  else:
382
388
  return self.modTess.image_to_string(
383
- _im, lang=self.lang, config=_config #config=self._get_tess_dir_config()
389
+ _im,
390
+ lang=self.lang,
391
+ config=_config, # config=self._get_tess_dir_config()
384
392
  )
385
393
 
386
394
  def to_reconize(self, img: cs.ImageElement) -> OcrBytesRecognized:
@@ -893,6 +901,7 @@ class ReplaceByHashMerge(MergeStrategy):
893
901
  .reset_index(drop=True)
894
902
  )
895
903
 
904
+
896
905
  # ====================================================================#
897
906
  # Processamento de imagem antes de enviar ao Tesseract.
898
907
  # ====================================================================#
@@ -901,7 +910,15 @@ class ReplaceByHashMerge(MergeStrategy):
901
910
  class OcrContrastPreprocessor(cs.ImagePreprocessor):
902
911
  """Realça o contraste e a nitidez dos caracteres para OCR."""
903
912
 
904
- def __init__(self, *, scale: float = 2.0, clip_limit: float = 2.5, sharpen_amount: float = 1.5, sharpen_sigma: float = 1.2, binary: bool = False) -> None:
913
+ def __init__(
914
+ self,
915
+ *,
916
+ scale: float = 2.0,
917
+ clip_limit: float = 2.5,
918
+ sharpen_amount: float = 1.5,
919
+ sharpen_sigma: float = 1.2,
920
+ binary: bool = False,
921
+ ) -> None:
905
922
  super().__init__()
906
923
  if scale <= 0 or clip_limit <= 0 or sharpen_sigma <= 0:
907
924
  raise ValueError("Os parâmetros devem ser maiores que zero.")
@@ -915,24 +932,41 @@ class OcrContrastPreprocessor(cs.ImagePreprocessor):
915
932
  cs._require_opencv()
916
933
 
917
934
  image: np.ndarray = img.to_opencv()
918
- gray: np.ndarray = cs.cv2.cvtColor(image, cs.cv2.COLOR_BGR2GRAY) if image.ndim == 3 else image.copy()
935
+ gray: np.ndarray = (
936
+ cs.cv2.cvtColor(image, cs.cv2.COLOR_BGR2GRAY)
937
+ if image.ndim == 3
938
+ else image.copy()
939
+ )
919
940
 
920
- enlarged: np.ndarray = cs.cv2.resize(gray, None, fx=self.scale, fy=self.scale, interpolation=cs.cv2.INTER_CUBIC)
941
+ enlarged: np.ndarray = cs.cv2.resize(
942
+ gray, None, fx=self.scale, fy=self.scale, interpolation=cs.cv2.INTER_CUBIC
943
+ )
921
944
 
922
945
  clahe = cs.cv2.createCLAHE(clipLimit=self.clip_limit, tileGridSize=(8, 8))
923
946
  enhanced: np.ndarray = clahe.apply(enlarged)
924
947
 
925
948
  blurred: np.ndarray = cs.cv2.GaussianBlur(enhanced, (0, 0), self.sharpen_sigma)
926
- sharpened: np.ndarray = cs.cv2.addWeighted(enhanced, self.sharpen_amount, blurred, 1.0 - self.sharpen_amount, 0)
949
+ sharpened: np.ndarray = cs.cv2.addWeighted(
950
+ enhanced, self.sharpen_amount, blurred, 1.0 - self.sharpen_amount, 0
951
+ )
927
952
 
928
953
  if self.binary:
929
- sharpened = cs.cv2.adaptiveThreshold(sharpened, 255, cs.cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cs.cv2.THRESH_BINARY, 35, 11)
954
+ sharpened = cs.cv2.adaptiveThreshold(
955
+ sharpened,
956
+ 255,
957
+ cs.cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
958
+ cs.cv2.THRESH_BINARY,
959
+ 35,
960
+ 11,
961
+ )
930
962
 
931
963
  success, buffer = cs.cv2.imencode(".png", sharpened)
932
964
  if not success:
933
965
  raise ValueError("Falha ao codificar a imagem processada.")
934
966
 
935
- return cs.ImageElement.create_from_bytes(BytesIO(buffer.tobytes()), lib_image=cs.LibImage.OPENCV)
967
+ return cs.ImageElement.create_from_bytes(
968
+ BytesIO(buffer.tobytes()), lib_image=cs.LibImage.OPENCV
969
+ )
936
970
 
937
971
  def process_binary(self, img: cs.ImageElement) -> cs.ImageElement:
938
972
  """Gera uma imagem binarizada com texto escuro e fundo branco."""
@@ -940,24 +974,40 @@ class OcrContrastPreprocessor(cs.ImagePreprocessor):
940
974
  cs._require_opencv()
941
975
 
942
976
  image: np.ndarray = img.to_opencv()
943
- gray: np.ndarray = cs.cv2.cvtColor(image, cs.cv2.COLOR_BGR2GRAY) if image.ndim == 3 else image.copy()
977
+ gray: np.ndarray = (
978
+ cs.cv2.cvtColor(image, cs.cv2.COLOR_BGR2GRAY)
979
+ if image.ndim == 3
980
+ else image.copy()
981
+ )
944
982
 
945
- enlarged: np.ndarray = cs.cv2.resize(gray, None, fx=self.scale, fy=self.scale, interpolation=cs.cv2.INTER_CUBIC)
983
+ enlarged: np.ndarray = cs.cv2.resize(
984
+ gray, None, fx=self.scale, fy=self.scale, interpolation=cs.cv2.INTER_CUBIC
985
+ )
946
986
 
947
987
  clahe = cs.cv2.createCLAHE(clipLimit=self.clip_limit, tileGridSize=(8, 8))
948
988
  enhanced: np.ndarray = clahe.apply(enlarged)
949
989
 
950
990
  blurred: np.ndarray = cs.cv2.GaussianBlur(enhanced, (0, 0), self.sharpen_sigma)
951
- sharpened: np.ndarray = cs.cv2.addWeighted(enhanced, self.sharpen_amount, blurred, 1.0 - self.sharpen_amount, 0)
991
+ sharpened: np.ndarray = cs.cv2.addWeighted(
992
+ enhanced, self.sharpen_amount, blurred, 1.0 - self.sharpen_amount, 0
993
+ )
952
994
 
953
- binary: np.ndarray = cs.cv2.adaptiveThreshold(sharpened, 255, cs.cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
954
- cs.cv2.THRESH_BINARY, 35, 11)
995
+ binary: np.ndarray = cs.cv2.adaptiveThreshold(
996
+ sharpened,
997
+ 255,
998
+ cs.cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
999
+ cs.cv2.THRESH_BINARY,
1000
+ 35,
1001
+ 11,
1002
+ )
955
1003
 
956
1004
  success, buffer = cs.cv2.imencode(".png", binary)
957
1005
  if not success:
958
1006
  raise ValueError("Falha ao codificar a imagem binarizada.")
959
1007
 
960
- return cs.ImageElement.create_from_bytes(BytesIO(buffer.tobytes()), lib_image=cs.LibImage.OPENCV)
1008
+ return cs.ImageElement.create_from_bytes(
1009
+ BytesIO(buffer.tobytes()), lib_image=cs.LibImage.OPENCV
1010
+ )
961
1011
 
962
1012
 
963
1013
  # ====================================================================#
@@ -1398,7 +1448,7 @@ class ReadOcrState(StateValue[TableData[HeaderOcr]]):
1398
1448
  """Retrato do último progresso (compatibilidade com a API antiga)."""
1399
1449
 
1400
1450
  def __init__(self, on_finish: Callable[[StateValue], Any] = None) -> None:
1401
- super().__init__(on_finish)
1451
+ super().__init__(on_finish=on_finish)
1402
1452
  self.current_element: str | None = None
1403
1453
  self.current_element_num: int = 0
1404
1454
  self.final_element_num: int = 0
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "ocr_stream"
7
- version = "2.6.8"
7
+ version = "2.6.9"
8
8
 
9
9
  description = "Extrair textos de documentos digitalizados e imagens."
10
10
  readme = "README.md"
@@ -539,7 +539,7 @@ wheels = [
539
539
 
540
540
  [[package]]
541
541
  name = "ocr-stream"
542
- version = "2.6.8"
542
+ version = "2.6.9"
543
543
  source = { editable = "." }
544
544
  dependencies = [
545
545
  { name = "convert-stream" },
File without changes
File without changes
File without changes
File without changes