File size: 11,125 Bytes
d520909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"""
Layout Detection Model Interface

Abstract interface for document layout analysis models.
Detects regions like text blocks, tables, figures, headers, etc.
"""

from abc import abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple

from ..chunks.models import BoundingBox, ChunkType
from .base import (
    BaseModel,
    BatchableModel,
    ImageInput,
    ModelCapability,
    ModelConfig,
)


class LayoutRegionType(str, Enum):
    """Types of layout regions that can be detected."""

    # Text regions
    TEXT = "text"
    TITLE = "title"
    HEADING = "heading"
    PARAGRAPH = "paragraph"
    LIST = "list"

    # Structured regions
    TABLE = "table"
    FIGURE = "figure"
    CHART = "chart"
    FORMULA = "formula"
    CODE = "code"

    # Document structure
    HEADER = "header"
    FOOTER = "footer"
    PAGE_NUMBER = "page_number"
    CAPTION = "caption"
    FOOTNOTE = "footnote"

    # Special elements
    LOGO = "logo"
    SIGNATURE = "signature"
    STAMP = "stamp"
    WATERMARK = "watermark"
    FORM_FIELD = "form_field"
    CHECKBOX = "checkbox"

    # Generic
    UNKNOWN = "unknown"

    def to_chunk_type(self) -> ChunkType:
        """Convert layout region type to chunk type."""
        mapping = {
            LayoutRegionType.TEXT: ChunkType.TEXT,
            LayoutRegionType.TITLE: ChunkType.TITLE,
            LayoutRegionType.HEADING: ChunkType.HEADING,
            LayoutRegionType.PARAGRAPH: ChunkType.PARAGRAPH,
            LayoutRegionType.LIST: ChunkType.LIST,
            LayoutRegionType.TABLE: ChunkType.TABLE,
            LayoutRegionType.FIGURE: ChunkType.FIGURE,
            LayoutRegionType.CHART: ChunkType.CHART,
            LayoutRegionType.FORMULA: ChunkType.FORMULA,
            LayoutRegionType.CODE: ChunkType.CODE,
            LayoutRegionType.HEADER: ChunkType.HEADER,
            LayoutRegionType.FOOTER: ChunkType.FOOTER,
            LayoutRegionType.PAGE_NUMBER: ChunkType.PAGE_NUMBER,
            LayoutRegionType.CAPTION: ChunkType.CAPTION,
            LayoutRegionType.FOOTNOTE: ChunkType.FOOTNOTE,
            LayoutRegionType.LOGO: ChunkType.LOGO,
            LayoutRegionType.SIGNATURE: ChunkType.SIGNATURE,
            LayoutRegionType.STAMP: ChunkType.STAMP,
            LayoutRegionType.WATERMARK: ChunkType.WATERMARK,
            LayoutRegionType.FORM_FIELD: ChunkType.FORM_FIELD,
            LayoutRegionType.CHECKBOX: ChunkType.CHECKBOX,
        }
        return mapping.get(self, ChunkType.TEXT)


@dataclass
class LayoutConfig(ModelConfig):
    """Configuration for layout detection models."""

    min_confidence: float = 0.5
    merge_overlapping: bool = True
    overlap_threshold: float = 0.5
    detect_reading_order: bool = True
    detect_columns: bool = True
    region_types: Optional[List[LayoutRegionType]] = None  # None = detect all

    def __post_init__(self):
        super().__post_init__()
        if not self.name:
            self.name = "layout_detector"


@dataclass
class LayoutRegion:
    """A detected layout region."""

    region_type: LayoutRegionType
    bbox: BoundingBox
    confidence: float
    region_id: str = ""

    # Reading order (0-indexed, -1 if unknown)
    reading_order: int = -1

    # Hierarchy
    parent_id: Optional[str] = None
    child_ids: List[str] = field(default_factory=list)

    # Column information
    column_index: int = 0
    num_columns: int = 1

    # Additional attributes
    attributes: Dict[str, Any] = field(default_factory=dict)

    def __post_init__(self):
        if not self.region_id:
            import hashlib
            content = f"{self.region_type.value}_{self.bbox.xyxy}"
            self.region_id = hashlib.md5(content.encode()).hexdigest()[:12]


@dataclass
class LayoutResult:
    """Complete layout analysis result for a page."""

    regions: List[LayoutRegion] = field(default_factory=list)
    reading_order: List[str] = field(default_factory=list)  # List of region_ids in order
    num_columns: int = 1
    page_orientation: float = 0.0  # Degrees
    image_width: int = 0
    image_height: int = 0
    processing_time_ms: float = 0.0
    model_metadata: Dict[str, Any] = field(default_factory=dict)

    def get_regions_by_type(self, region_type: LayoutRegionType) -> List[LayoutRegion]:
        """Get all regions of a specific type."""
        return [r for r in self.regions if r.region_type == region_type]

    def get_region_by_id(self, region_id: str) -> Optional[LayoutRegion]:
        """Get a region by its ID."""
        for region in self.regions:
            if region.region_id == region_id:
                return region
        return None

    def get_ordered_regions(self) -> List[LayoutRegion]:
        """Get regions in reading order."""
        if not self.reading_order:
            # Fall back to top-to-bottom, left-to-right ordering
            return sorted(
                self.regions,
                key=lambda r: (r.bbox.y_min, r.bbox.x_min)
            )

        ordered = []
        for region_id in self.reading_order:
            region = self.get_region_by_id(region_id)
            if region:
                ordered.append(region)
        return ordered

    def get_tables(self) -> List[LayoutRegion]:
        """Get all table regions."""
        return self.get_regions_by_type(LayoutRegionType.TABLE)

    def get_figures(self) -> List[LayoutRegion]:
        """Get all figure regions."""
        return self.get_regions_by_type(LayoutRegionType.FIGURE)

    def get_text_regions(self) -> List[LayoutRegion]:
        """Get all text-based regions."""
        text_types = {
            LayoutRegionType.TEXT,
            LayoutRegionType.TITLE,
            LayoutRegionType.HEADING,
            LayoutRegionType.PARAGRAPH,
            LayoutRegionType.LIST,
            LayoutRegionType.CAPTION,
            LayoutRegionType.FOOTNOTE,
        }
        return [r for r in self.regions if r.region_type in text_types]


class LayoutModel(BatchableModel):
    """
    Abstract base class for layout detection models.

    Implementations should detect:
    - Document regions (text, tables, figures, etc.)
    - Reading order
    - Column structure
    - Region hierarchy
    """

    def __init__(self, config: Optional[LayoutConfig] = None):
        super().__init__(config or LayoutConfig(name="layout"))
        self.config: LayoutConfig = self.config

    def get_capabilities(self) -> List[ModelCapability]:
        caps = [ModelCapability.LAYOUT_DETECTION]
        if self.config.detect_reading_order:
            caps.append(ModelCapability.READING_ORDER)
        return caps

    @abstractmethod
    def detect(
        self,
        image: ImageInput,
        **kwargs
    ) -> LayoutResult:
        """
        Detect layout regions in an image.

        Args:
            image: Input document image
            **kwargs: Additional parameters

        Returns:
            LayoutResult with detected regions
        """
        pass

    def process_batch(
        self,
        inputs: List[ImageInput],
        **kwargs
    ) -> List[LayoutResult]:
        """Process multiple images."""
        return [self.detect(img, **kwargs) for img in inputs]

    def detect_tables(
        self,
        image: ImageInput,
        **kwargs
    ) -> List[LayoutRegion]:
        """
        Detect only table regions.

        Convenience method that filters layout detection results.
        """
        result = self.detect(image, **kwargs)
        return result.get_tables()

    def detect_figures(
        self,
        image: ImageInput,
        **kwargs
    ) -> List[LayoutRegion]:
        """Detect only figure regions."""
        result = self.detect(image, **kwargs)
        return result.get_figures()


class ReadingOrderModel(BaseModel):
    """
    Abstract base class for reading order determination.

    Some implementations may be separate from layout detection,
    requiring a specialized model for complex layouts.
    """

    def get_capabilities(self) -> List[ModelCapability]:
        return [ModelCapability.READING_ORDER]

    @abstractmethod
    def determine_order(
        self,
        regions: List[LayoutRegion],
        image: Optional[ImageInput] = None,
        **kwargs
    ) -> List[str]:
        """
        Determine reading order for a list of regions.

        Args:
            regions: Layout regions to order
            image: Optional image for visual cues
            **kwargs: Additional parameters

        Returns:
            List of region_ids in reading order
        """
        pass


class HeuristicReadingOrderModel(ReadingOrderModel):
    """
    Simple heuristic-based reading order model.

    Uses geometric analysis for column detection and ordering.
    Suitable for simple document layouts.
    """

    def __init__(self, config: Optional[ModelConfig] = None):
        super().__init__(config or ModelConfig(name="heuristic_reading_order"))

    def load(self) -> None:
        self._is_loaded = True

    def unload(self) -> None:
        self._is_loaded = False

    def determine_order(
        self,
        regions: List[LayoutRegion],
        image: Optional[ImageInput] = None,
        column_threshold: float = 0.3,
        **kwargs
    ) -> List[str]:
        """
        Determine reading order using heuristics.

        Strategy:
        1. Detect columns based on x-coordinate clustering
        2. Within each column, sort top-to-bottom
        3. Process columns left-to-right
        """
        if not regions:
            return []

        # Detect columns based on x-coordinate overlap
        columns = self._detect_columns(regions, column_threshold)

        # Sort regions within each column (top to bottom)
        ordered_ids = []
        for column in columns:
            column_regions = sorted(column, key=lambda r: r.bbox.y_min)
            ordered_ids.extend(r.region_id for r in column_regions)

        return ordered_ids

    def _detect_columns(
        self,
        regions: List[LayoutRegion],
        threshold: float
    ) -> List[List[LayoutRegion]]:
        """Detect columns by x-coordinate clustering."""
        if not regions:
            return []

        # Sort by x_min
        sorted_regions = sorted(regions, key=lambda r: r.bbox.x_min)

        columns = []
        current_column = [sorted_regions[0]]

        for region in sorted_regions[1:]:
            # Check if region overlaps horizontally with current column
            prev_region = current_column[-1]

            # Calculate horizontal overlap
            overlap_start = max(region.bbox.x_min, prev_region.bbox.x_min)
            overlap_end = min(region.bbox.x_max, prev_region.bbox.x_max)

            if overlap_end > overlap_start:
                # Has horizontal overlap - same column
                current_column.append(region)
            else:
                # No overlap - new column
                columns.append(current_column)
                current_column = [region]

        columns.append(current_column)
        return columns