Okay, let's illustrate the Composite pattern in Python for your document recognition project, focusing on scaling coordinates.
The Composite pattern allows you to treat individual objects (like a Cell) and compositions of objects (like a TableRow or a Table) uniformly. Both can be scaled.
Here's how we can structure it:
- Component (
DocumentComponent): An abstract base class defining the common interface for all elements (cells, rows, tables, the whole document). This interface will include methods like get_bounding_box() and scale_coordinates(k).
- Leaf (
Cell): Represents the simplest element in the structure. It has its own bounding box and implements the scale_coordinates method directly.
- Composite (
TableRow, Table, Document): Represents elements that can contain other DocumentComponent objects (either Leaves or other Composites). They implement scale_coordinates by delegating the call to all their children. They also manage their children.
import abc
from typing import List, Tuple, Optional
# Type alias for bounding box (x1, y1, x2, y2)
BoundingBox = Tuple[int, int, int, int]
# --- Component Interface ---
class DocumentComponent(abc.ABC):
"""
Abstract base class for all elements in the document structure.
Defines the common interface.
"""
@abc.abstractmethod
def get_bounding_box(self) -> BoundingBox:
"""Returns the bounding box of this component."""
pass
@abc.abstractmethod
def scale_coordinates(self, k: float):
"""Scales the coordinates of this component and its children by factor k."""
pass
@abc.abstractmethod
def display(self, indent: str = ""):
"""Prints the structure and bounding box."""
pass
# --- Leaf Class ---
class Cell(DocumentComponent):
"""
Represents a leaf node (e.g., a table cell).
It holds its own coordinates.
"""
def __init__(self, x1: int, y1: int, x2: int, y2: int, content: str = ""):
# Ensure coordinates are valid (x1<=x2, y1<=y2) - basic validation
if x1 > x2 or y1 > y2:
raise ValueError("Invalid coordinates: x1 > x2 or y1 > y2")
self._bounding_box: BoundingBox = (x1, y1, x2, y2)
self._content = content # Optional: Store cell content
def get_bounding_box(self) -> BoundingBox:
return self._bounding_box
def scale_coordinates(self, k: float):
"""Scales the cell's own coordinates."""
x1, y1, x2, y2 = self._bounding_box
new_x1 = int(x1 * k)
new_y1 = int(y1 * k)
new_x2 = int(x2 * k)
new_y2 = int(y2 * k)
# Ensure coordinates remain valid after scaling
if new_x1 > new_x2 or new_y1 > new_y2:
# Handle potential issues with scaling near zero or large factors
# For simplicity, we might just clamp or recalculate,
# but let's adjust x2/y2 if needed to maintain order.
print(f"Warning: Scaling resulted in invalid coords for cell '{self._content}'. Adjusting.")
new_x2 = max(new_x1, new_x2)
new_y2 = max(new_y1, new_y2)
self._bounding_box = (new_x1, new_y1, new_x2, new_y2)
# print(f"Scaled cell '{self._content}' to {self._bounding_box}") # Optional debug print
def display(self, indent: str = ""):
print(f"{indent}Cell(Content='{self._content}', Box={self._bounding_box})")
# --- Composite Classes ---
class ContainerComponent(DocumentComponent):
"""
Abstract composite class that holds child components.
"""
def __init__(self):
self._children: List[DocumentComponent] = []
def add_component(self, component: DocumentComponent):
"""Adds a child component."""
self._children.append(component)
def remove_component(self, component: DocumentComponent):
"""Removes a child component."""
self._children.remove(component)
def get_children(self) -> List[DocumentComponent]:
"""Returns the list of children."""
return self._children
def scale_coordinates(self, k: float):
"""
Scales coordinates of all child components.
The container's own bounding box is derived, not explicitly scaled here,
but recalculated based on scaled children.
"""
# print(f"Scaling container children...") # Debug print
for component in self._children:
component.scale_coordinates(k)
def get_bounding_box(self) -> Optional[BoundingBox]:
"""
Calculates the bounding box encompassing all children.
Returns None if there are no children.
"""
if not self._children:
return None # Or return a default like (0,0,0,0) if preferred
# Get bounding boxes of all children
child_boxes = [child.get_bounding_box() for child in self._children if child.get_bounding_box()]
if not child_boxes:
return None # No valid child boxes found
# Find the overall min/max coordinates
min_x1 = min(box[0] for box in child_boxes)
min_y1 = min(box[1] for box in child_boxes)
max_x2 = max(box[2] for box in child_boxes)
max_y2 = max(box[3] for box in child_boxes)
return (min_x1, min_y1, max_x2, max_y2)
def display(self, indent: str = ""):
"""Displays the container and its children."""
bbox = self.get_bounding_box()
print(f"{indent}{self.__class__.__name__}(Box={bbox}):")
for component in self._children:
component.display(indent + " ")
class TableRow(ContainerComponent):
"""
Represents a composite structure (a row containing cells).
"""
def __init__(self, row_id: int = -1):
super().__init__()
self._row_id = row_id # Optional identifier
# Override display for better row representation
def display(self, indent: str = ""):
bbox = self.get_bounding_box()
print(f"{indent}TableRow(ID={self._row_id}, Box={bbox}):")
for component in self._children:
# Ensure children are Cells before calling display, or handle generically
if isinstance(component, Cell):
component.display(indent + " ")
else:
# Fallback for unexpected component types
component.display(indent + " ")
class Table(ContainerComponent):
"""
Represents a composite structure (a table containing rows).
"""
def __init__(self, table_id: str = ""):
super().__init__()
self._table_id = table_id # Optional identifier
# Override display for better table representation
def display(self, indent: str = ""):
bbox = self.get_bounding_box()
print(f"{indent}Table(ID='{self._table_id}', Box={bbox}):")
for component in self._children:
# Ensure children are TableRows before calling display, or handle generically
if isinstance(component, TableRow):
component.display(indent + " ")
else:
# Fallback for unexpected component types
component.display(indent + " ")
class Document(ContainerComponent):
"""
Represents the top-level composite structure (a document containing tables).
"""
def __init__(self, doc_id: str = ""):
super().__init__()
self._doc_id = doc_id # Optional identifier
def display(self, indent: str = ""):
bbox = self.get_bounding_box()
print(f"{indent}Document(ID='{self._doc_id}', Box={bbox}):")
for component in self._children:
# Ensure children are Tables before calling display, or handle generically
if isinstance(component, Table):
component.display(indent + " ")
else:
# Fallback for unexpected component types
component.display(indent + " ")
# --- Example Usage ---
if __name__ == "__main__":
# 1. Create Leaf components (Cells)
cell1 = Cell(10, 20, 50, 40, "Header A")
cell2 = Cell(55, 20, 100, 40, "Header B")
cell3 = Cell(10, 45, 50, 65, "Data 1.1")
cell4 = Cell(55, 45, 100, 65, "Data 1.2")
cell5 = Cell(10, 70, 50, 90, "Data 2.1")
cell6 = Cell(55, 70, 100, 90, "Data 2.2")
# 2. Create Composite components (TableRows)
row1 = TableRow(row_id=0)
row1.add_component(cell1)
row1.add_component(cell2)
row2 = TableRow(row_id=1)
row2.add_component(cell3)
row2.add_component(cell4)
row3 = TableRow(row_id=2)
row3.add_component(cell5)
row3.add_component(cell6)
# 3. Create Composite components (Tables)
table1 = Table(table_id="main_data")
table1.add_component(row1)
table1.add_component(row2)
table1.add_component(row3)
# 4. Create Top-level Composite (Document)
document = Document(doc_id="invoice_001")
document.add_component(table1)
# 5. Display original structure and bounding boxes
print("--- Original Document Structure ---")
document.display()
print("-" * 30)
# 6. Define scaling factor
scale_factor = 1.5
print(f"\n--- Scaling coordinates by {scale_factor} ---")
# 7. Apply scaling to the entire structure via the root component
# The scaling propagates down to all children automatically
document.scale_coordinates(scale_factor)
# 8. Display scaled structure
print("\n--- Scaled Document Structure ---")
document.display()
print("-" * 30)
# Example: Get bounding box of a specific part after scaling
print(f"\nBounding box of Table '{table1._table_id}' after scaling: {table1.get_bounding_box()}")
print(f"Bounding box of Row 1 after scaling: {row2.get_bounding_box()}") # row2 was the second row added
print(f"Bounding box of Cell 'Data 2.2' after scaling: {cell6.get_bounding_box()}")
Explanation:
DocumentComponent: Sets up the blueprint. Any part of your document structure (cell, row, table, page, section, etc.) can inherit from this. get_bounding_box lets you query the spatial extent, and scale_coordinates performs the modification. display is added for visualization.
Cell (Leaf): Holds the actual coordinates (_bounding_box). Its scale_coordinates method directly modifies these coordinates. It doesn't have children.
ContainerComponent (Abstract Composite): Provides common functionality for composites: a list to hold children (_children) and methods to manage them (add_component, remove_component). Its scale_coordinates implementation iterates through its children and calls their scale_coordinates method, achieving the recursive scaling effect. Its get_bounding_box calculates the bounding box that encloses all its children.
TableRow, Table, Document (Concrete Composites): Inherit from ContainerComponent. They represent different levels of hierarchy in your document structure. They can contain other DocumentComponent objects (either Cells or other composites like TableRows). The display methods are overridden slightly to provide context about the specific type (Row, Table, Document).
- Client Code (
if __name__ == "__main__":):
- Builds a sample hierarchy: Document -> Table -> TableRow -> Cell.
- Calls
display() on the root (document) to show the initial state.
- Calls
document.scale_coordinates(1.5). Because Document is a composite, this call triggers scale_coordinates on its children (Table), which in turn triggers it on their children (TableRow), and finally on the Cells.
- Calls
display() again to show the effect of scaling on all coordinates.
This structure allows you to manipulate the document layout uniformly, regardless of whether you're operating on a single cell or an entire table, simply by calling the same methods on the relevant component object.