Coverage for collectra/tasks/ocr.py: 75.64%

78 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1__all__ = ["OCRSuraya", "LineDetectorSurya"] 

2 

3from dotenv import load_dotenv 

4 

5from collectra.tasks.base import Task 

6from collectra.tasks.text_output import TextOutputTask 

7from collectra.types.images import Image, ImageCrop 

8from collectra.types.texts import Text 

9 

10load_dotenv() 

11 

12 

13class OCRSuraya(TextOutputTask): 

14 def __init__(self, name: str, **kwargs) -> None: 

15 """Initialize the task without loading Surya model weights.""" 

16 super().__init__(name, **kwargs) 

17 self.detection_predictor = None 

18 self.recognition_predictor = None 

19 

20 def _init_predictors(self) -> None: 

21 """Load Surya predictors on first use.""" 

22 if self.detection_predictor is not None and self.recognition_predictor is not None: 

23 return 

24 from surya.detection import DetectionPredictor 

25 from surya.foundation import FoundationPredictor 

26 from surya.recognition import RecognitionPredictor 

27 

28 self.detection_predictor = DetectionPredictor() 

29 foundation_predictor = FoundationPredictor() 

30 self.recognition_predictor = RecognitionPredictor(foundation_predictor) 

31 

32 def input_type(self) -> type | tuple: 

33 """Define the expected input types for this LLM task. 

34 

35 Returns: 

36 type | tuple: Tuple of str and Path types for text and file inputs. 

37 """ 

38 return Image 

39 

40 def output_type(self) -> type | tuple: 

41 """Define the expected output types for this LLM task. 

42 

43 Returns: 

44 type | tuple: String type for generated text outputs. 

45 """ 

46 return Text 

47 

48 def run(self, *images: Image) -> list[Text]: 

49 """Recognize text in each image and return Text artefacts.""" 

50 self._init_predictors() 

51 results: list[Text] = [] 

52 for image in images: 

53 if not isinstance(image, Image): 

54 raise TypeError(f"image must be Image, got {type(image)}") 

55 predictions = self.recognition_predictor( 

56 [image.pil()], det_predictor=self.detection_predictor 

57 ) 

58 text = "\n".join(line.text for line in predictions[0].text_lines) 

59 results.append(self.text_output(text)) 

60 return results 

61 

62 

63class LineDetectorSurya(Task): 

64 def __init__( 

65 self, 

66 name: str, 

67 merge_horizontal: bool = False, 

68 min_height: int = 0, 

69 **kwargs, 

70 ) -> None: 

71 """Initialize the task without loading Surya model weights.""" 

72 super().__init__( 

73 name, 

74 merge_horizontal=merge_horizontal, 

75 min_height=min_height or 0, 

76 **kwargs, 

77 ) 

78 self.detection_predictor = None 

79 

80 def _init_predictor(self) -> None: 

81 """Load the Surya detection predictor on first use.""" 

82 if self.detection_predictor is not None: 

83 return 

84 from surya.detection import DetectionPredictor 

85 

86 self.detection_predictor = DetectionPredictor() 

87 

88 def input_type(self) -> type | tuple: 

89 """Define the expected input types for this LLM task. 

90 

91 Returns: 

92 type | tuple: Tuple of str and Path types for text and file inputs. 

93 """ 

94 return Image 

95 

96 def output_type(self) -> type | tuple: 

97 """Define the expected output types for this LLM task. 

98 

99 Returns: 

100 type | tuple: String type for generated text outputs. 

101 """ 

102 return ImageCrop 

103 

104 def run(self, *images: Image) -> list[ImageCrop]: 

105 """Detect text lines and return their image crops.""" 

106 self._init_predictor() 

107 results: list[ImageCrop] = [] 

108 for image in images: 

109 if not isinstance(image, Image): 

110 raise TypeError(f"image must be Image, got {type(image)}") 

111 pil_image = image.pil() 

112 predictions = self.detection_predictor([pil_image]) 

113 

114 # Sort bounding boxes vertically 

115 bounding_boxes = sorted( 

116 [polygon_box.bbox for polygon_box in predictions[0].bboxes], 

117 key=lambda bbox: bbox[1], 

118 ) 

119 

120 if len(bounding_boxes) == 0 or ( 

121 self.min_height and image.height <= self.min_height 

122 ): 

123 crop = image.make_crop(0.5, 0.5, 1.0, 1.0) 

124 results.append(crop) 

125 elif self.merge_horizontal: 

126 bbox = bounding_boxes[0] 

127 top = bbox[1] 

128 bottom = bbox[3] 

129 

130 for bbox in bounding_boxes: 

131 if bbox[1] >= bottom: 

132 crop = image.make_crop_bounding_box( 

133 0, top, image.width, bottom, min_height=self.min_height 

134 ) 

135 results.append(crop) 

136 top = bbox[1] 

137 bottom = bbox[3] 

138 else: 

139 top = min(top, bbox[1]) 

140 bottom = max(bottom, bbox[3]) 

141 

142 crop = image.make_crop_bounding_box(0, top, image.width, bottom) 

143 results.append(crop) 

144 else: 

145 for bbox in bounding_boxes: 

146 crop = image.make_crop_bounding_box( 

147 *bbox, min_height=self.min_height 

148 ) 

149 results.append(crop) 

150 

151 return results