Datasets:
File size: 173,110 Bytes
cd15502 | 1 | {"repo": "Filimoa/open-parse", "n_pairs": 35, "version": "v2_function_scoped", "contexts": {"src/tests/test_doc_parser.py::10": {"resolved_imports": ["src/openparse/__init__.py"], "used_names": ["openparse"], "enclosing_function": "test_parse_doc", "extracted_code": "# Source: src/openparse/__init__.py\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n TextSpan,\n)\n\n\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n TextSpan,\n)\n\n__all__ = [", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1132}, "src/tests/test_doc_parser.py::34": {"resolved_imports": ["src/openparse/__init__.py"], "used_names": ["openparse"], "enclosing_function": "test_parse_tables_with_table_transformers", "extracted_code": "# Source: src/openparse/__init__.py\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n TextSpan,\n)\n\n\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n TextSpan,\n)\n\n__all__ = [", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1132}, "src/tests/test_doc_parser.py::35": {"resolved_imports": ["src/openparse/__init__.py"], "used_names": ["openparse"], "enclosing_function": "test_parse_tables_with_table_transformers", "extracted_code": "# Source: src/openparse/__init__.py\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n\nfrom openparse import processing, version\nfrom openparse.config import config\nfrom openparse.doc_parser import (\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n\n DocumentParser,\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n TextSpan,\n)\n\n\n)\nfrom openparse.pdf import Pdf\nfrom openparse.schemas import (\n Bbox,\n LineElement,\n Node,\n TableElement,\n TextElement,\n TextSpan,\n)\n\n__all__ = [", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1132}, "src/tests/test_schemas.py::374": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["Bbox", "Node", "TextElement"], "enclosing_function": "test_node_bbox", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 11967}, "src/tests/test_schemas.py::91": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["TextSpan"], "enclosing_function": "test_formatted_text_edge_cases", "extracted_code": "# Source: src/openparse/schemas.py\nclass TextSpan(BaseModel):\n text: str\n is_bold: bool\n is_italic: bool\n size: float\n\n @cached_property\n def is_heading(self) -> bool:\n MIN_HEADING_SIZE = 16\n return self.size >= MIN_HEADING_SIZE and self.is_bold\n\n def formatted_text(\n self,\n previous_span: Optional[\"TextSpan\"] = None,\n next_span: Optional[\"TextSpan\"] = None,\n ) -> str:\n \"\"\"Format text considering adjacent spans to avoid redundant markdown symbols.\"\"\"\n formatted = self.text\n\n # Check if style changes at the beginning\n if self.is_bold and (previous_span is None or not previous_span.is_bold):\n formatted = f\"**{formatted}\"\n if self.is_italic and (previous_span is None or not previous_span.is_italic):\n formatted = f\"*{formatted}\"\n\n # Check if style changes at the end\n if self.is_bold and (next_span is None or not next_span.is_bold):\n formatted = f\"{formatted}**\"\n if self.is_italic and (next_span is None or not next_span.is_italic):\n formatted = f\"{formatted}*\"\n\n return formatted\n\n model_config = ConfigDict(frozen=True)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 1198}, "src/tests/test_schemas.py::378": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["Bbox", "Node", "TextElement"], "enclosing_function": "test_node_bbox", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 11967}, "src/tests/test_schemas.py::385": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["Bbox", "Node", "TextElement"], "enclosing_function": "test_node_bbox", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 11967}, "src/tests/test_schemas.py::379": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["Bbox", "Node", "TextElement"], "enclosing_function": "test_node_bbox", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 11967}, "src/tests/test_schemas.py::380": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["Bbox", "Node", "TextElement"], "enclosing_function": "test_node_bbox", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 11967}, "src/tests/test_schemas.py::470": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["bullet_regex", "pytest"], "enclosing_function": "test_bullet_point_detection_match", "extracted_code": "# Source: src/openparse/schemas.py\nbullet_regex = re.compile(\n r\"^(\\s*[\\-•](?!\\*)|\\s*\\*(?!\\*)|\\s*\\d+\\.\\s|\\s*\\([a-zA-Z0-9]+\\)\\s|\\s*[a-zA-Z]\\.\\s)\"\n)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 149}, "src/tests/test_schemas.py::534": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["Bbox", "Node", "TextElement", "consts"], "enclosing_function": "test_text_element_with_bullets", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 11967}, "src/tests/test_schemas.py::513": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["Bbox", "Node", "TextElement", "consts"], "enclosing_function": "test_text_element_with_bullets", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 11967}, "src/tests/test_schemas.py::446": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["pytest"], "enclosing_function": "test_node_overlaps", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "src/tests/test_schemas.py::94": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["TextSpan"], "enclosing_function": "test_formatted_text_edge_cases", "extracted_code": "# Source: src/openparse/schemas.py\nclass TextSpan(BaseModel):\n text: str\n is_bold: bool\n is_italic: bool\n size: float\n\n @cached_property\n def is_heading(self) -> bool:\n MIN_HEADING_SIZE = 16\n return self.size >= MIN_HEADING_SIZE and self.is_bold\n\n def formatted_text(\n self,\n previous_span: Optional[\"TextSpan\"] = None,\n next_span: Optional[\"TextSpan\"] = None,\n ) -> str:\n \"\"\"Format text considering adjacent spans to avoid redundant markdown symbols.\"\"\"\n formatted = self.text\n\n # Check if style changes at the beginning\n if self.is_bold and (previous_span is None or not previous_span.is_bold):\n formatted = f\"**{formatted}\"\n if self.is_italic and (previous_span is None or not previous_span.is_italic):\n formatted = f\"*{formatted}\"\n\n # Check if style changes at the end\n if self.is_bold and (next_span is None or not next_span.is_bold):\n formatted = f\"{formatted}**\"\n if self.is_italic and (next_span is None or not next_span.is_italic):\n formatted = f\"{formatted}*\"\n\n return formatted\n\n model_config = ConfigDict(frozen=True)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 1198}, "src/tests/test_schemas.py::65": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": [], "enclosing_function": "test_formatted_text_no_adjacent", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "src/tests/test_schemas.py::63": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": [], "enclosing_function": "test_formatted_text_no_adjacent", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "src/tests/test_schemas.py::64": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": [], "enclosing_function": "test_formatted_text_no_adjacent", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "src/tests/test_schemas.py::292": {"resolved_imports": ["src/openparse/schemas.py", "src/openparse/__init__.py", "src/openparse/consts.py"], "used_names": ["LineElement", "pytest"], "enclosing_function": "test_line_element_overlaps", "extracted_code": "# Source: src/openparse/schemas.py\nclass LineElement(BaseModel):\n bbox: Tuple[float, float, float, float]\n spans: Tuple[TextSpan, ...]\n style: Optional[str] = None\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_bbox_vals(cls, data: Any) -> Any:\n data[\"bbox\"] = tuple(round(val, 2) for val in data[\"bbox\"])\n return data\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n \"\"\"\n Combine spans into a single text string, respecting markdown syntax.\n \"\"\"\n if not self.spans:\n return \"\"\n\n combined_text = \"\"\n for i, span in enumerate(self.spans):\n previous_span = self.spans[i - 1] if i > 0 else None\n next_span = self.spans[i + 1] if i < len(self.spans) - 1 else None\n combined_text += span.formatted_text(previous_span, next_span)\n\n cleaned_text = self._clean_markdown_formatting(combined_text)\n return cleaned_text\n\n @cached_property\n def is_bold(self) -> bool:\n # ignore last span for formatting, often see weird trailing spans\n spans = self.spans[:-1] if len(self.spans) > 1 else self.spans\n\n return all(span.is_bold for span in spans)\n\n @cached_property\n def is_italic(self) -> bool:\n # ignore last span for formatting, often see weird trailing spans\n spans = self.spans[:-1] if len(self.spans) > 1 else self.spans\n return all(span.is_italic for span in spans)\n\n @cached_property\n def is_heading(self) -> bool:\n # ignore last span for formatting, often see weird trailing spans\n spans = self.spans[:-1] if len(self.spans) > 1 else self.spans\n MIN_HEADING_SIZE = 16\n return all(span.size >= MIN_HEADING_SIZE and span.is_bold for span in spans)\n\n def _clean_markdown_formatting(self, text: str) -> str:\n \"\"\"\n Uses regex to clean up markdown formatting, ensuring symbols don't surround whitespace.\n This will fix issues with bold (** or __) and italic (* or _) markdown where there may be\n spaces between the markers and the text.\n \"\"\"\n patterns = [\n (\n r\"(\\*\\*|__)\\s+\",\n r\"\\1\",\n ), # Remove space after opening bold or italic marker\n (\n r\"\\s+(\\*\\*|__)\",\n r\"\\1\",\n ), # Remove space before closing bold or italic marker\n (r\"(\\*|_)\\s+\", r\"\\1\"), # Remove space after opening italic marker\n (r\"\\s+(\\*|_)\", r\"\\1\"), # Remove space before closing italic marker\n (\n r\"(\\*\\*|__)(\\*\\*|__)\",\n r\"\\1 \\2\",\n ), # Add a space between adjacent identical markers\n ]\n\n cleaned_text = text\n for pattern, replacement in patterns:\n cleaned_text = re.sub(pattern, replacement, cleaned_text)\n\n return cleaned_text\n\n def overlaps(self, other: \"LineElement\", error_margin: float = 0.0) -> bool:\n x_overlap = not (\n self.bbox[0] - error_margin > other.bbox[2] + error_margin\n or other.bbox[0] - error_margin > self.bbox[2] + error_margin\n )\n\n y_overlap = not (\n self.bbox[1] - error_margin > other.bbox[3] + error_margin\n or other.bbox[1] - error_margin > self.bbox[3] + error_margin\n )\n\n return x_overlap and y_overlap\n\n def is_at_similar_height(\n self, other: \"LineElement\", error_margin: float = 0.0\n ) -> bool:\n y_distance = abs(self.bbox[1] - other.bbox[1])\n\n return y_distance <= error_margin\n\n def combine(self, other: \"LineElement\") -> \"LineElement\":\n \"\"\"\n Used for spans\n \"\"\"\n new_bbox = (\n min(self.bbox[0], other.bbox[0]),\n min(self.bbox[1], other.bbox[1]),\n max(self.bbox[2], other.bbox[2]),\n max(self.bbox[3], other.bbox[3]),\n )\n new_spans = tuple(self.spans + other.spans)\n\n return LineElement(bbox=new_bbox, spans=new_spans)\n\n model_config = ConfigDict(frozen=True)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 4091}, "src/tests/processing/test_steps.py::264": {"resolved_imports": ["src/openparse/processing/basic_transforms.py", "src/openparse/__init__.py", "src/openparse/consts.py", "src/openparse/schemas.py"], "used_names": ["CombineNodesSpatially"], "enclosing_function": "test_combine_nodes_spatially_both_small", "extracted_code": "# Source: src/openparse/processing/basic_transforms.py\nclass CombineNodesSpatially(ProcessingStep):\n \"\"\"\n Combines nodes that are close to each other spatially. We assume that elements that are close together on the page are related to each other and therefore should be combined.\n\n This simple heuristic achieves results comparable to deep learning methods we've experimented with. It's also much faster and easier to understand.\n\n Criteria:\n - both_small: Both nodes must be small elements. This is useful for combining small text elements that are close together. Common example is a bulleted list.\n - either_stub: Either node can be a stub. This is useful for combining small text elements like a heading with a larger text element below it.\n \"\"\"\n\n def __init__(\n self,\n x_error_margin: float = 0,\n y_error_margin: float = 0,\n criteria: Literal[\"both_small\", \"either_stub\"] = \"both_small\",\n ):\n self.x_error_margin = x_error_margin\n self.y_error_margin = y_error_margin\n self.criteria = criteria\n\n def process(self, nodes: List[Node]) -> List[Node]:\n combined_nodes: List[Node] = []\n\n while nodes:\n current_node = nodes.pop(0)\n combined = False\n\n for i, target_node in enumerate(combined_nodes):\n criteria_bool = False\n if self.criteria == \"both_small\":\n criteria_bool = current_node.is_small and target_node.is_small\n elif self.criteria == \"either_stub\":\n criteria_bool = current_node.is_stub or target_node.is_stub\n\n if (\n current_node.overlaps(\n target_node, self.x_error_margin, self.y_error_margin\n )\n and criteria_bool\n ):\n new_elements = target_node.elements + current_node.elements\n combined_nodes[i] = Node(elements=new_elements)\n combined = True\n break\n\n if not combined:\n combined_nodes.append(current_node)\n\n return combined_nodes", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 2174}, "src/tests/processing/test_steps.py::377": {"resolved_imports": ["src/openparse/processing/basic_transforms.py", "src/openparse/__init__.py", "src/openparse/consts.py", "src/openparse/schemas.py"], "used_names": ["CombineBullets"], "enclosing_function": "test_combine_bullets_single_node", "extracted_code": "# Source: src/openparse/processing/basic_transforms.py\nclass CombineBullets(ProcessingStep):\n \"\"\"\n Needs to follow CombineNodesSpatially in the pipeline. Bullets are often far enough from the text they belong to that they are in distinct nodes.\n \"\"\"\n\n def process(self, nodes: List[Node]) -> List[Node]:\n combined_nodes = []\n i = 0\n while i < len(nodes):\n current_combination = nodes[i]\n while (\n i + 1 < len(nodes)\n and current_combination.ends_with_bullet\n and nodes[i + 1].starts_with_bullet\n ):\n current_combination += nodes[i + 1]\n i += 1\n combined_nodes.append(current_combination)\n i += 1\n return combined_nodes", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 788}, "src/tests/processing/test_steps.py::401": {"resolved_imports": ["src/openparse/processing/basic_transforms.py", "src/openparse/__init__.py", "src/openparse/consts.py", "src/openparse/schemas.py"], "used_names": ["CombineBullets"], "enclosing_function": "test_combine_bullets_multiple_nodes", "extracted_code": "# Source: src/openparse/processing/basic_transforms.py\nclass CombineBullets(ProcessingStep):\n \"\"\"\n Needs to follow CombineNodesSpatially in the pipeline. Bullets are often far enough from the text they belong to that they are in distinct nodes.\n \"\"\"\n\n def process(self, nodes: List[Node]) -> List[Node]:\n combined_nodes = []\n i = 0\n while i < len(nodes):\n current_combination = nodes[i]\n while (\n i + 1 < len(nodes)\n and current_combination.ends_with_bullet\n and nodes[i + 1].starts_with_bullet\n ):\n current_combination += nodes[i + 1]\n i += 1\n combined_nodes.append(current_combination)\n i += 1\n return combined_nodes", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 788}, "src/tests/processing/test_steps.py::159": {"resolved_imports": ["src/openparse/processing/basic_transforms.py", "src/openparse/__init__.py", "src/openparse/consts.py", "src/openparse/schemas.py"], "used_names": ["RemoveFullPageStubs"], "enclosing_function": "test_page_above_max_area_percentage", "extracted_code": "# Source: src/openparse/processing/basic_transforms.py\nclass RemoveFullPageStubs(ProcessingStep):\n \"\"\"\n Sometimes elements take up entire pages and are not useful for downstream processing.\n \"\"\"\n\n def __init__(self, max_area_pct: float):\n assert 0 <= max_area_pct <= 1, \"max_area_pct must be between 0 and 1.\"\n self.max_area_pct = max_area_pct\n\n def process(self, nodes: List[Node]) -> List[Node]:\n \"\"\"\n Retains multi-page nodes, nodes that occupy less than max_area_pct of the page.\n \"\"\"\n res = []\n for node in nodes:\n node_bbox = node.bbox[0]\n page_area = node_bbox.page_width * node_bbox.page_height\n\n if node.num_pages > 1:\n res.append(node)\n continue\n elif node_bbox.area / page_area < self.max_area_pct:\n res.append(node)\n continue\n elif not node.is_stub:\n res.append(node)\n continue\n return res", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 1017}, "src/tests/processing/test_steps.py::509": {"resolved_imports": ["src/openparse/processing/basic_transforms.py", "src/openparse/__init__.py", "src/openparse/consts.py", "src/openparse/schemas.py"], "used_names": ["Bbox", "LineElement", "Node", "TextElement", "TextSpan", "pytest"], "enclosing_function": "longer_text_node", "extracted_code": "# Source: src/openparse/schemas.py\nclass Bbox(BaseModel):\n page: int\n page_height: float\n page_width: float\n x0: float\n y0: float\n x1: float\n y1: float\n\n @cached_property\n def area(self) -> float:\n return (self.x1 - self.x0) * (self.y1 - self.y0)\n\n @model_validator(mode=\"before\")\n @classmethod\n def x1_must_be_greater_than_x0(cls, data: Any) -> Any:\n if \"x0\" in data and data[\"x1\"] <= data[\"x0\"]:\n raise ValueError(\"x1 must be greater than x0\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def y1_must_be_greater_than_y0(cls, data: Any) -> Any:\n if \"y0\" in data and data[\"y1\"] <= data[\"y0\"]:\n raise ValueError(\"y1 must be greater than y0\")\n return data\n\n def combine(self, other: \"Bbox\") -> \"Bbox\":\n if self.page != other.page:\n raise ValueError(\"Bboxes must be from the same page to combine.\")\n return Bbox(\n page=self.page,\n page_height=self.page_height,\n page_width=self.page_width,\n x0=min(self.x0, other.x0),\n y0=min(self.y0, other.y0),\n x1=max(self.x1, other.x1),\n y1=max(self.y1, other.y1),\n )\n\n model_config = ConfigDict(frozen=True)\n\nclass TextSpan(BaseModel):\n text: str\n is_bold: bool\n is_italic: bool\n size: float\n\n @cached_property\n def is_heading(self) -> bool:\n MIN_HEADING_SIZE = 16\n return self.size >= MIN_HEADING_SIZE and self.is_bold\n\n def formatted_text(\n self,\n previous_span: Optional[\"TextSpan\"] = None,\n next_span: Optional[\"TextSpan\"] = None,\n ) -> str:\n \"\"\"Format text considering adjacent spans to avoid redundant markdown symbols.\"\"\"\n formatted = self.text\n\n # Check if style changes at the beginning\n if self.is_bold and (previous_span is None or not previous_span.is_bold):\n formatted = f\"**{formatted}\"\n if self.is_italic and (previous_span is None or not previous_span.is_italic):\n formatted = f\"*{formatted}\"\n\n # Check if style changes at the end\n if self.is_bold and (next_span is None or not next_span.is_bold):\n formatted = f\"{formatted}**\"\n if self.is_italic and (next_span is None or not next_span.is_italic):\n formatted = f\"{formatted}*\"\n\n return formatted\n\n model_config = ConfigDict(frozen=True)\n\nclass LineElement(BaseModel):\n bbox: Tuple[float, float, float, float]\n spans: Tuple[TextSpan, ...]\n style: Optional[str] = None\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_bbox_vals(cls, data: Any) -> Any:\n data[\"bbox\"] = tuple(round(val, 2) for val in data[\"bbox\"])\n return data\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n \"\"\"\n Combine spans into a single text string, respecting markdown syntax.\n \"\"\"\n if not self.spans:\n return \"\"\n\n combined_text = \"\"\n for i, span in enumerate(self.spans):\n previous_span = self.spans[i - 1] if i > 0 else None\n next_span = self.spans[i + 1] if i < len(self.spans) - 1 else None\n combined_text += span.formatted_text(previous_span, next_span)\n\n cleaned_text = self._clean_markdown_formatting(combined_text)\n return cleaned_text\n\n @cached_property\n def is_bold(self) -> bool:\n # ignore last span for formatting, often see weird trailing spans\n spans = self.spans[:-1] if len(self.spans) > 1 else self.spans\n\n return all(span.is_bold for span in spans)\n\n @cached_property\n def is_italic(self) -> bool:\n # ignore last span for formatting, often see weird trailing spans\n spans = self.spans[:-1] if len(self.spans) > 1 else self.spans\n return all(span.is_italic for span in spans)\n\n @cached_property\n def is_heading(self) -> bool:\n # ignore last span for formatting, often see weird trailing spans\n spans = self.spans[:-1] if len(self.spans) > 1 else self.spans\n MIN_HEADING_SIZE = 16\n return all(span.size >= MIN_HEADING_SIZE and span.is_bold for span in spans)\n\n def _clean_markdown_formatting(self, text: str) -> str:\n \"\"\"\n Uses regex to clean up markdown formatting, ensuring symbols don't surround whitespace.\n This will fix issues with bold (** or __) and italic (* or _) markdown where there may be\n spaces between the markers and the text.\n \"\"\"\n patterns = [\n (\n r\"(\\*\\*|__)\\s+\",\n r\"\\1\",\n ), # Remove space after opening bold or italic marker\n (\n r\"\\s+(\\*\\*|__)\",\n r\"\\1\",\n ), # Remove space before closing bold or italic marker\n (r\"(\\*|_)\\s+\", r\"\\1\"), # Remove space after opening italic marker\n (r\"\\s+(\\*|_)\", r\"\\1\"), # Remove space before closing italic marker\n (\n r\"(\\*\\*|__)(\\*\\*|__)\",\n r\"\\1 \\2\",\n ), # Add a space between adjacent identical markers\n ]\n\n cleaned_text = text\n for pattern, replacement in patterns:\n cleaned_text = re.sub(pattern, replacement, cleaned_text)\n\n return cleaned_text\n\n def overlaps(self, other: \"LineElement\", error_margin: float = 0.0) -> bool:\n x_overlap = not (\n self.bbox[0] - error_margin > other.bbox[2] + error_margin\n or other.bbox[0] - error_margin > self.bbox[2] + error_margin\n )\n\n y_overlap = not (\n self.bbox[1] - error_margin > other.bbox[3] + error_margin\n or other.bbox[1] - error_margin > self.bbox[3] + error_margin\n )\n\n return x_overlap and y_overlap\n\n def is_at_similar_height(\n self, other: \"LineElement\", error_margin: float = 0.0\n ) -> bool:\n y_distance = abs(self.bbox[1] - other.bbox[1])\n\n return y_distance <= error_margin\n\n def combine(self, other: \"LineElement\") -> \"LineElement\":\n \"\"\"\n Used for spans\n \"\"\"\n new_bbox = (\n min(self.bbox[0], other.bbox[0]),\n min(self.bbox[1], other.bbox[1]),\n max(self.bbox[2], other.bbox[2]),\n max(self.bbox[3], other.bbox[3]),\n )\n new_spans = tuple(self.spans + other.spans)\n\n return LineElement(bbox=new_bbox, spans=new_spans)\n\n model_config = ConfigDict(frozen=True)\n\nclass TextElement(BaseModel):\n text: str\n lines: Tuple[LineElement, ...]\n bbox: Bbox\n _embed_text: Optional[str] = None\n variant: Literal[NodeVariant.TEXT] = NodeVariant.TEXT\n\n @computed_field # type: ignore\n @cached_property\n def embed_text(self) -> str:\n if self._embed_text:\n return self._embed_text\n\n return self.text\n\n @cached_property\n def tokens(self) -> int:\n return num_tokens(self.text)\n\n @cached_property\n def is_heading(self) -> bool:\n return all(line.is_heading for line in self.lines)\n\n @cached_property\n def is_bold(self) -> bool:\n return all(line.is_bold for line in self.lines)\n\n @cached_property\n def page(self) -> int:\n return self.bbox.page\n\n @cached_property\n def area(self) -> float:\n return (self.bbox.x1 - self.bbox.x0) * (self.bbox.y1 - self.bbox.y0)\n\n def is_at_similar_height(\n self,\n other: Union[\"TableElement\", \"TextElement\", \"ImageElement\"],\n error_margin: float = 1,\n ) -> bool:\n y_distance = abs(self.bbox.y1 - other.bbox.y1)\n\n return y_distance <= error_margin\n\n def overlaps(\n self,\n other: \"TextElement\",\n x_error_margin: float = 0.0,\n y_error_margin: float = 0.0,\n ) -> bool:\n if self.page != other.page:\n return False\n x_overlap = not (\n self.bbox.x0 - x_error_margin > other.bbox.x1 + x_error_margin\n or other.bbox.x0 - x_error_margin > self.bbox.x1 + x_error_margin\n )\n y_overlap = not (\n self.bbox.y0 - y_error_margin > other.bbox.y1 + y_error_margin\n or other.bbox.y0 - y_error_margin > self.bbox.y1 + y_error_margin\n )\n\n return x_overlap and y_overlap\n\n model_config = ConfigDict(frozen=True)\n\nclass Node(BaseModel):\n id_: str = Field(\n default_factory=lambda: str(uuid.uuid4()),\n description=\"Unique ID of the node.\",\n exclude=True,\n )\n elements: Tuple[Union[TextElement, TableElement, ImageElement], ...] = Field(\n exclude=True, frozen=True\n )\n tokenization_lower_limit: int = Field(\n default=consts.TOKENIZATION_LOWER_LIMIT, frozen=True, exclude=True\n )\n tokenization_upper_limit: int = Field(\n default=consts.TOKENIZATION_UPPER_LIMIT, frozen=True, exclude=True\n )\n coordinate_system: Literal[\"top-left\", \"bottom-left\"] = Field(\n default=consts.COORDINATE_SYSTEM, frozen=True, exclude=True\n ) # controlled globally for now, should be moved into elements\n embedding: Optional[List[float]] = Field(\n default=None, description=\"Embedding of the node.\"\n )\n\n @computed_field # type: ignore\n @cached_property\n def node_id(self) -> str:\n return self.id_\n\n @computed_field # type: ignore\n @cached_property\n def variant(self) -> Set[Literal[\"text\", \"table\", \"image\"]]:\n return {e.variant.value for e in self.elements}\n\n @computed_field # type: ignore\n @cached_property\n def tokens(self) -> int:\n return sum([e.tokens for e in self.elements])\n\n @computed_field # type: ignore\n @cached_property\n def images(self) -> List[ImageElement]:\n return [e for e in self.elements if e.variant == NodeVariant.IMAGE]\n\n @computed_field # type: ignore\n @cached_property\n def bbox(self) -> List[Bbox]:\n elements_by_page = defaultdict(list)\n for element in self.elements:\n elements_by_page[element.bbox.page].append(element)\n\n # Calculate bounding box for each page\n bboxes = []\n for page, elements in elements_by_page.items():\n x0 = min(e.bbox.x0 for e in elements)\n y0 = min(e.bbox.y0 for e in elements)\n x1 = max(e.bbox.x1 for e in elements)\n y1 = max(e.bbox.y1 for e in elements)\n page_height = elements[0].bbox.page_height\n page_width = elements[0].bbox.page_width\n bboxes.append(\n Bbox(\n page=page,\n page_height=page_height,\n page_width=page_width,\n x0=x0,\n y0=y0,\n x1=x1,\n y1=y1,\n )\n )\n\n return bboxes\n\n @computed_field # type: ignore\n @cached_property\n def text(self) -> str:\n sorted_elements = sorted(\n self.elements, key=lambda e: (e.page, -e.bbox.y1, e.bbox.x0)\n )\n\n texts = []\n for i in range(len(sorted_elements)):\n current = sorted_elements[i]\n if i > 0:\n previous = sorted_elements[i - 1]\n relationship = _determine_relationship(previous, current)\n\n if relationship == \"same-line\":\n join_str = \" \"\n elif relationship == \"same-paragraph\":\n join_str = \"\\n\"\n else:\n join_str = consts.ELEMENT_DELIMETER\n\n texts.append(join_str)\n\n texts.append(current.embed_text)\n\n return \"\".join(texts)\n\n @cached_property\n def is_heading(self) -> bool:\n if self.variant != {\"text\"}:\n return False\n if not self.is_stub:\n return False\n\n return all(element.is_heading or element.is_bold for element in self.elements) # type: ignore\n\n @cached_property\n def starts_with_heading(self) -> bool:\n if not self.variant == {\"text\"}:\n return False\n return self.elements[0].is_heading # type: ignore\n\n @cached_property\n def starts_with_bullet(self) -> bool:\n first_line = self.text.split(consts.ELEMENT_DELIMETER)[0].strip()\n if not first_line:\n return False\n return bool(bullet_regex.match(first_line))\n\n @cached_property\n def ends_with_bullet(self) -> bool:\n last_line = self.text.split(consts.ELEMENT_DELIMETER)[-1].strip()\n if not last_line:\n return False\n return bool(bullet_regex.match(last_line))\n\n @cached_property\n def is_stub(self) -> bool:\n return self.tokens < 50\n\n @cached_property\n def is_small(self) -> bool:\n return self.tokens < self.tokenization_lower_limit\n\n @cached_property\n def is_large(self) -> bool:\n return self.tokens > self.tokenization_upper_limit\n\n @cached_property\n def num_pages(self) -> int:\n return len({element.bbox.page for element in self.elements})\n\n @cached_property\n def start_page(self) -> int:\n return min(element.bbox.page for element in self.elements)\n\n @cached_property\n def end_page(self) -> int:\n return max(element.bbox.page for element in self.elements)\n\n @cached_property\n def reading_order(self) -> ReadingOrder:\n \"\"\"\n To sort nodes based on their reading order, we need to calculate an aggregate position for the node. This allows us to:\n\n nodes = sorted(nodes, key=lambda x: x.reading_order)\n\n Returns a tuple of (min_page, y_position, min_x0) to use as sort keys, where y_position is adjusted based on the coordinate system.\n \"\"\"\n min_page = min(element.bbox.page for element in self.elements)\n min_x0 = min(element.bbox.x0 for element in self.elements)\n\n if self.coordinate_system == \"bottom-left\":\n y_position = -min(element.bbox.y0 for element in self.elements)\n else:\n raise NotImplementedError(\n \"Only 'bottom-left' coordinate system is supported.\"\n )\n\n return ReadingOrder(min_page=min_page, y_position=y_position, min_x0=min_x0)\n\n def overlaps(\n self, other: \"Node\", x_error_margin: float = 0.0, y_error_margin: float = 0.0\n ) -> bool:\n for bbox in self.bbox:\n other_bboxes = [\n other_bbox for other_bbox in other.bbox if other_bbox.page == bbox.page\n ]\n\n for other_bbox in other_bboxes:\n x_overlap = not (\n bbox.x0 - x_error_margin > other_bbox.x1 + x_error_margin\n or other_bbox.x0 - x_error_margin > bbox.x1 + x_error_margin\n )\n\n y_overlap = not (\n bbox.y0 - y_error_margin > other_bbox.y1 + y_error_margin\n or other_bbox.y0 - y_error_margin > bbox.y1 + y_error_margin\n )\n\n if x_overlap and y_overlap:\n return True\n\n return False\n\n def to_llama_index(self):\n try:\n from llama_index.core.schema import TextNode as LlamaIndexTextNode\n except ImportError as err:\n raise ImportError(\n \"llama_index is not installed. Please install it with `pip install llama-index`.\"\n ) from err\n return LlamaIndexTextNode(\n id_=self.id_,\n text=self.text,\n embedding=self.embedding,\n metadata={\"bbox\": [b.model_dump(mode=\"json\") for b in self.bbox]},\n excluded_embed_metadata_keys=[\"bbox\"],\n excluded_llm_metadata_keys=[\"bbox\"],\n )\n\n def __lt__(self, other: \"Node\") -> bool:\n if not isinstance(other, Node):\n return NotImplemented\n\n assert (\n self.coordinate_system == other.coordinate_system\n ), \"Coordinate systems must match.\"\n\n return self.reading_order < other.reading_order\n\n def _repr_markdown_(self):\n \"\"\"\n When called in a Jupyter environment, this will display the node as Markdown, which Jupyter will then render as HTML.\n \"\"\"\n markdown_parts = []\n for element in self.elements:\n if element.variant == NodeVariant.TEXT:\n markdown_parts.append(element.text)\n elif element.variant == NodeVariant.IMAGE:\n image_data = element.image\n mime_type = element.image_mimetype\n if mime_type == \"unknown\":\n mime_type = \"image/png\"\n markdown_image = f\"\"\n markdown_parts.append(markdown_image)\n elif element.variant == NodeVariant.TABLE:\n markdown_parts.append(element.text)\n return \"\\n\\n\".join(markdown_parts)\n\n def __add__(self, other: \"Node\") -> \"Node\":\n \"\"\"\n Allows two Node instances to be combined using the '+' operator.\n The combined Node instance will contain elements from both nodes.\n \"\"\"\n if not isinstance(other, Node):\n return NotImplemented()\n\n new_elems = self.elements + other.elements\n return Node(elements=new_elems)", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 17190}, "src/tests/processing/test_steps.py::83": {"resolved_imports": ["src/openparse/processing/basic_transforms.py", "src/openparse/__init__.py", "src/openparse/consts.py", "src/openparse/schemas.py"], "used_names": ["RemoveTextInsideTables"], "enclosing_function": "test_no_tables_in_document", "extracted_code": "# Source: src/openparse/processing/basic_transforms.py\nclass RemoveTextInsideTables(ProcessingStep):\n \"\"\"\n If we're using the table extraction pipeline, we need to remove text that is inside tables to avoid duplication.\n \"\"\"\n\n def process(self, nodes: List[Node]) -> List[Node]:\n # Group all table bounding boxes by page\n tables_by_page = defaultdict(list)\n for node in nodes:\n if node.variant == {\"table\"}:\n for table_element in node.elements:\n tables_by_page[table_element.page].append(table_element.bbox)\n\n updated_nodes = []\n for node in nodes:\n if node.variant == {\"table\"}:\n updated_nodes.append(node)\n continue\n\n new_elements = []\n for element in node.elements:\n should_include = not (\n isinstance(element, TextElement)\n and self.intersects_any_table(\n element.bbox, tables_by_page[element.page]\n )\n )\n if should_include:\n new_elements.append(element)\n\n if new_elements and len(new_elements) != len(node.elements):\n updated_nodes.append(Node(elements=tuple(new_elements)))\n elif len(new_elements) == len(node.elements):\n updated_nodes.append(node)\n\n return updated_nodes\n\n def intersects_any_table(self, text_bbox: Bbox, table_bboxes: List[Bbox]) -> bool:\n return any(\n self.intersects(text_bbox, table_bbox) for table_bbox in table_bboxes\n )\n\n @staticmethod\n def intersects(text_bbox: Bbox, table_bbox: Bbox) -> bool:\n return (\n text_bbox.x1 > table_bbox.x0\n and text_bbox.x0 < table_bbox.x1\n and text_bbox.y1 > table_bbox.y0\n and text_bbox.y0 < table_bbox.y1\n )", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 1920}, "src/tests/processing/test_steps.py::294": {"resolved_imports": ["src/openparse/processing/basic_transforms.py", "src/openparse/__init__.py", "src/openparse/consts.py", "src/openparse/schemas.py"], "used_names": ["CombineNodesSpatially"], "enclosing_function": "test_combine_nodes_one_stub_one_small", "extracted_code": "# Source: src/openparse/processing/basic_transforms.py\nclass CombineNodesSpatially(ProcessingStep):\n \"\"\"\n Combines nodes that are close to each other spatially. We assume that elements that are close together on the page are related to each other and therefore should be combined.\n\n This simple heuristic achieves results comparable to deep learning methods we've experimented with. It's also much faster and easier to understand.\n\n Criteria:\n - both_small: Both nodes must be small elements. This is useful for combining small text elements that are close together. Common example is a bulleted list.\n - either_stub: Either node can be a stub. This is useful for combining small text elements like a heading with a larger text element below it.\n \"\"\"\n\n def __init__(\n self,\n x_error_margin: float = 0,\n y_error_margin: float = 0,\n criteria: Literal[\"both_small\", \"either_stub\"] = \"both_small\",\n ):\n self.x_error_margin = x_error_margin\n self.y_error_margin = y_error_margin\n self.criteria = criteria\n\n def process(self, nodes: List[Node]) -> List[Node]:\n combined_nodes: List[Node] = []\n\n while nodes:\n current_node = nodes.pop(0)\n combined = False\n\n for i, target_node in enumerate(combined_nodes):\n criteria_bool = False\n if self.criteria == \"both_small\":\n criteria_bool = current_node.is_small and target_node.is_small\n elif self.criteria == \"either_stub\":\n criteria_bool = current_node.is_stub or target_node.is_stub\n\n if (\n current_node.overlaps(\n target_node, self.x_error_margin, self.y_error_margin\n )\n and criteria_bool\n ):\n new_elements = target_node.elements + current_node.elements\n combined_nodes[i] = Node(elements=new_elements)\n combined = True\n break\n\n if not combined:\n combined_nodes.append(current_node)\n\n return combined_nodes", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 2174}, "src/tests/tables/pymupdf/test_parse.py::14": {"resolved_imports": ["src/openparse/tables/pymupdf/parse.py"], "used_names": ["output_to_markdown"], "enclosing_function": "test_parse_output_to_markdown", "extracted_code": "# Source: src/openparse/tables/pymupdf/parse.py\ndef output_to_markdown(headers: List[str], rows: List[List[str]]) -> str:\n markdown_output = \"\"\n if headers is not None:\n for header in headers:\n safe_header = \"\" if header is None else header\n markdown_output += \"| \" + safe_header + \" \"\n\n markdown_output += \"|\\n\"\n markdown_output += \"|---\" * len(headers) + \"|\\n\"\n\n for row in rows:\n processed_row = [\n \" \" if cell in [None, \"\"] else cell.replace(\"\\n\", \" \") for cell in row\n ]\n markdown_output += \"| \" + \" | \".join(processed_row) + \" |\\n\"\n\n return markdown_output", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 641}, "src/tests/tables/transformers/test_geometry.py::21": {"resolved_imports": ["src/openparse/tables/table_transformers/geometry.py"], "used_names": ["calc_bbox_intersection", "pytest"], "enclosing_function": "test_calc_bbox_intersection", "extracted_code": "# Source: src/openparse/tables/table_transformers/geometry.py\ndef calc_bbox_intersection(bbox1, bbox2, safety_margin=5.0):\n if safety_margin < 0:\n raise ValueError(\"Safety margin cannot be negative.\")\n\n if (\n bbox1[2] <= bbox1[0]\n or bbox1[3] <= bbox1[1]\n or bbox2[2] <= bbox2[0]\n or bbox2[3] <= bbox2[1]\n ):\n raise ValueError(\"Bounding boxes must have non-zero width and height.\")\n\n # Expand bounding boxes\n x1_expanded_min = min(bbox1[0], bbox2[0]) - safety_margin\n y1_expanded_min = min(bbox1[1], bbox2[1]) - safety_margin\n x2_expanded_max = max(bbox1[2], bbox2[2]) + safety_margin\n y2_expanded_max = max(bbox1[3], bbox2[3]) + safety_margin\n\n # Check if expanded boxes intersect\n if (\n x2_expanded_max <= max(bbox1[0], bbox2[0])\n or x1_expanded_min >= min(bbox1[2], bbox2[2])\n or y2_expanded_max <= max(bbox1[1], bbox2[1])\n or y1_expanded_min >= min(bbox1[3], bbox2[3])\n ):\n return None\n\n # Calculate and return the actual intersection based on original boxes\n x1 = max(bbox1[0], bbox2[0])\n y1 = max(bbox1[1], bbox2[1])\n x2 = min(bbox1[2], bbox2[2])\n y2 = min(bbox1[3], bbox2[3])\n\n # Only return the intersection if it's valid\n if x2 > x1 and y2 > y1:\n return (x1, y1, x2, y2)\n\n return None", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1334}, "src/tests/text/pdf_miner/test_core.py::147": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["CharElement", "_extract_chars"], "enclosing_function": "test_extract_chars", "extracted_code": "# Source: src/openparse/text/pdfminer/core.py\nclass CharElement(BaseModel):\n text: str\n fontname: str\n size: float\n\n @property\n def is_bold(self) -> bool:\n return \"Bold\" in self.fontname or \"bold\" in self.fontname\n\n @property\n def is_italic(self) -> bool:\n return \"Italic\" in self.fontname or \"italic\" in self.fontname\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_size(cls, data: Any) -> Any:\n data[\"size\"] = round(data[\"size\"], 2)\n return data\n\ndef _extract_chars(text_line: LTTextLine) -> List[CharElement]:\n \"\"\"\n The last_fontname variable is used to keep track of the most recent fontname seen as the function iterates through text_line.\n\n This is necessary because LTAnno elements (annotations) do not have their own font and size information; they use the most recently encountered fontname and size from a LTChar element.\n \"\"\"\n\n chars = []\n # take the first LTChar's fontname and size for any LTAnno before them\n last_fontname = next(\n (char.fontname for char in text_line if isinstance(char, LTChar)), \"\"\n )\n last_size = next((char.size for char in text_line if isinstance(char, LTChar)), 0.0)\n\n for char in text_line:\n if not isinstance(char, LTChar) and not isinstance(char, LTAnno):\n continue\n if isinstance(char, LTChar):\n last_fontname = char.fontname\n last_size = char.size\n chars.append(\n CharElement(text=char.get_text(), fontname=last_fontname, size=last_size)\n )\n\n return chars", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 1579}, "src/tests/text/pdf_miner/test_core.py::202": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["CharElement", "_extract_chars"], "enclosing_function": "test_extract_chars_with_ltannos", "extracted_code": "# Source: src/openparse/text/pdfminer/core.py\nclass CharElement(BaseModel):\n text: str\n fontname: str\n size: float\n\n @property\n def is_bold(self) -> bool:\n return \"Bold\" in self.fontname or \"bold\" in self.fontname\n\n @property\n def is_italic(self) -> bool:\n return \"Italic\" in self.fontname or \"italic\" in self.fontname\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_size(cls, data: Any) -> Any:\n data[\"size\"] = round(data[\"size\"], 2)\n return data\n\ndef _extract_chars(text_line: LTTextLine) -> List[CharElement]:\n \"\"\"\n The last_fontname variable is used to keep track of the most recent fontname seen as the function iterates through text_line.\n\n This is necessary because LTAnno elements (annotations) do not have their own font and size information; they use the most recently encountered fontname and size from a LTChar element.\n \"\"\"\n\n chars = []\n # take the first LTChar's fontname and size for any LTAnno before them\n last_fontname = next(\n (char.fontname for char in text_line if isinstance(char, LTChar)), \"\"\n )\n last_size = next((char.size for char in text_line if isinstance(char, LTChar)), 0.0)\n\n for char in text_line:\n if not isinstance(char, LTChar) and not isinstance(char, LTAnno):\n continue\n if isinstance(char, LTChar):\n last_fontname = char.fontname\n last_size = char.size\n chars.append(\n CharElement(text=char.get_text(), fontname=last_fontname, size=last_size)\n )\n\n return chars", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 1579}, "src/tests/text/pdf_miner/test_core.py::245": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["NodeVariant", "Path", "Pdf", "base64", "ingest"], "enclosing_function": "test_parse_pdf_with_images", "extracted_code": "# Source: src/openparse/pdf.py\nclass Pdf:\n \"\"\"\n Simple utility class for working with PDF files. This class wraps the PdfReader and PdfWriter classes from pypdf.\n \"\"\"\n\n def __init__(self, file: Union[str, Path, PdfReader]):\n self.file_path = None\n self.file_metadata = {}\n if isinstance(file, (str, Path)):\n self.file_path = str(file)\n self.file_metadata = file_metadata(file)\n\n self.reader = PdfReader(file) if isinstance(file, (str, Path)) else file\n self.writer = PdfWriter()\n for page in self.reader.pages:\n self.writer.add_page(page)\n\n self.num_pages = len(self.reader.pages)\n\n def extract_layout_pages(self) -> Iterator[LTPage]:\n \"\"\"\n Yields layout objects for each page in the PDF using pdfminer.six.\n \"\"\"\n assert (\n self.file_path is not None\n ), \"PDF file path is required for this method for now.\"\n\n yield from extract_pages(self.file_path)\n\n def save(self, output_pdf: Union[str, Path]) -> None:\n \"\"\"\n Saves the content from the PdfWriter to a new PDF file.\n \"\"\"\n with open(str(output_pdf), \"wb\") as out_pdf:\n self.writer.write(out_pdf)\n\n def extract_pages(self, start_page: int, end_page: int) -> None:\n \"\"\"\n Extracts a range of pages from the PDF and adds them to the PdfWriter.\n \"\"\"\n for page_num in range(start_page - 1, end_page):\n self.writer.add_page(self.reader.pages[page_num])\n\n def to_pymupdf_doc(self):\n \"\"\"\n Transforms the PDF into a PyMuPDF (fitz) document.\n If modifications have been made using PdfWriter, it saves to a temporary file first.\n This function dynamically imports PyMuPDF (fitz), requiring it only if this method is called.\n \"\"\"\n try:\n import fitz # type: ignore\n except ImportError as err:\n raise ImportError(\n \"PyMuPDF (fitz) is not installed. This method requires PyMuPDF.\"\n ) from err\n\n if not self.writer.pages:\n return fitz.open(self.file_path)\n\n byte_stream = io.BytesIO()\n self.writer.write(byte_stream)\n return fitz.open(None, byte_stream)\n\n def _draw_bboxes(\n self,\n bboxes_with_color: List[_BboxWithColor],\n coordinates: Literal[\"top-left\", \"bottom-left\"],\n ):\n try:\n import fitz\n except ImportError as err:\n raise ImportError(\n \"PyMuPDF (fitz) is not installed. This method requires PyMuPDF.\"\n ) from err\n\n pdf = self.to_pymupdf_doc()\n\n for page in pdf:\n page.wrap_contents()\n\n for bbox_with_color in bboxes_with_color:\n bbox = bbox_with_color.bbox\n if bbox.page != page.number:\n continue\n if coordinates == \"bottom-left\":\n bbox = self._flip_coordinates(bbox)\n rect = fitz.Rect(bbox.x0, bbox.y0, bbox.x1, bbox.y1)\n page.draw_rect(\n rect, bbox_with_color.color\n ) # Use the color associated with this bbox\n\n if bbox_with_color.annotation_text:\n page.insert_text(\n rect.top_left,\n str(bbox_with_color.annotation_text),\n fontsize=12,\n )\n return pdf\n\n def display_with_bboxes(\n self,\n nodes: List[Node],\n page_nums: Optional[List[int]] = None,\n annotations: Optional[List[str]] = None,\n ):\n \"\"\"\n Display a single page of a PDF file using IPython.\n Optionally, display a piece of text on top of the bounding box.\n \"\"\"\n try:\n from IPython.display import Image, display # type: ignore\n except ImportError as err:\n raise ImportError(\n \"IPython is required to display PDFs. Please install it with `pip install ipython`.\"\n ) from err\n assert nodes, \"At least one node is required.\"\n\n bboxes = [node.bbox for node in nodes]\n flattened_bboxes = _prepare_bboxes_for_drawing(bboxes, annotations)\n marked_up_doc = self._draw_bboxes(flattened_bboxes, nodes[0].coordinate_system)\n if not page_nums:\n page_nums = list(range(marked_up_doc.page_count))\n for page_num in page_nums:\n page = marked_up_doc[page_num]\n img_data = page.get_pixmap().tobytes(\"png\")\n display(Image(data=img_data))\n\n def export_with_bboxes(\n self,\n nodes: List[Node],\n output_pdf: Union[str, Path],\n annotations: Optional[List[str]] = None,\n ) -> None:\n assert nodes, \"At least one node is required.\"\n\n bboxes = [node.bbox for node in nodes]\n flattened_bboxes = _prepare_bboxes_for_drawing(bboxes, annotations)\n marked_up_doc = self._draw_bboxes(flattened_bboxes, nodes[0].coordinate_system)\n marked_up_doc.save(str(output_pdf))\n\n def _flip_coordinates(self, bbox: Bbox) -> Bbox:\n fy0 = bbox.page_height - bbox.y1\n fy1 = bbox.page_height - bbox.y0\n return Bbox(\n page=bbox.page,\n page_height=bbox.page_height,\n page_width=bbox.page_width,\n x0=bbox.x0,\n y0=fy0,\n x1=bbox.x1,\n y1=fy1,\n )\n\n def to_imgs(self, page_numbers: Optional[List[int]] = None) -> List[Image.Image]:\n doc = self.to_pymupdf_doc()\n images = []\n\n if not doc.is_pdf:\n raise ValueError(\"The document is not in PDF format.\")\n if doc.needs_pass:\n raise ValueError(\"The PDF document is password protected.\")\n\n if page_numbers is None:\n page_numbers = list(range(doc.page_count))\n\n for n in page_numbers:\n page = doc[n]\n pix = page.get_pixmap()\n image = Image.frombytes(\"RGB\", (pix.width, pix.height), pix.samples)\n images.append(image)\n\n return images\n\n\n# Source: src/openparse/schemas.py\nclass NodeVariant(Enum):\n TEXT = \"text\"\n TABLE = \"table\"\n IMAGE = \"image\"\n\n\n# Source: src/openparse/text/pdfminer/core.py\ndef ingest(pdf_input: Pdf) -> List[Union[TextElement, ImageElement]]:\n \"\"\"Parse PDF and return a list of TextElement and ImageElement objects.\"\"\"\n elements = []\n page_layouts = pdf_input.extract_layout_pages()\n\n for page_num, page_layout in enumerate(page_layouts):\n page_width = page_layout.width\n page_height = page_layout.height\n page_elements = []\n for element in page_layout:\n if isinstance(element, LTTextContainer):\n lines = []\n for text_line in element:\n if isinstance(text_line, LTTextLine):\n lines.append(_create_line_element(text_line))\n if not lines:\n continue\n bbox = _get_bbox(lines)\n\n page_elements.append(\n TextElement(\n bbox=Bbox(\n x0=bbox[0],\n y0=bbox[1],\n x1=bbox[2],\n y1=bbox[3],\n page=page_num,\n page_width=page_width,\n page_height=page_height,\n ),\n text=\"\\n\".join(line.text for line in lines),\n lines=tuple(lines),\n )\n )\n elif isinstance(element, LTFigure):\n for e in element:\n if isinstance(e, LTImage):\n mime_type = _get_mime_type(e)\n if mime_type:\n if mime_type == \"image/png\":\n img_data = _process_png_image(e)\n else:\n img_data = e.stream.get_data()\n if img_data:\n base64_string = base64.b64encode(img_data).decode(\n \"utf-8\"\n )\n page_elements.append(\n ImageElement(\n bbox=Bbox(\n x0=e.bbox[0],\n y0=e.bbox[1],\n x1=e.bbox[2],\n y1=e.bbox[3],\n page=page_num,\n page_width=page_width,\n page_height=page_height,\n ),\n image=base64_string,\n image_mimetype=mime_type or \"unknown\",\n text=\"\",\n )\n )\n elements.extend(page_elements)\n return elements", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 9231}, "src/tests/text/pdf_miner/test_core.py::150": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["CharElement", "_extract_chars"], "enclosing_function": "test_extract_chars", "extracted_code": "# Source: src/openparse/text/pdfminer/core.py\nclass CharElement(BaseModel):\n text: str\n fontname: str\n size: float\n\n @property\n def is_bold(self) -> bool:\n return \"Bold\" in self.fontname or \"bold\" in self.fontname\n\n @property\n def is_italic(self) -> bool:\n return \"Italic\" in self.fontname or \"italic\" in self.fontname\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_size(cls, data: Any) -> Any:\n data[\"size\"] = round(data[\"size\"], 2)\n return data\n\ndef _extract_chars(text_line: LTTextLine) -> List[CharElement]:\n \"\"\"\n The last_fontname variable is used to keep track of the most recent fontname seen as the function iterates through text_line.\n\n This is necessary because LTAnno elements (annotations) do not have their own font and size information; they use the most recently encountered fontname and size from a LTChar element.\n \"\"\"\n\n chars = []\n # take the first LTChar's fontname and size for any LTAnno before them\n last_fontname = next(\n (char.fontname for char in text_line if isinstance(char, LTChar)), \"\"\n )\n last_size = next((char.size for char in text_line if isinstance(char, LTChar)), 0.0)\n\n for char in text_line:\n if not isinstance(char, LTChar) and not isinstance(char, LTAnno):\n continue\n if isinstance(char, LTChar):\n last_fontname = char.fontname\n last_size = char.size\n chars.append(\n CharElement(text=char.get_text(), fontname=last_fontname, size=last_size)\n )\n\n return chars", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 1579}, "src/tests/text/pdf_miner/test_core.py::244": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["NodeVariant", "Path", "Pdf", "base64", "ingest"], "enclosing_function": "test_parse_pdf_with_images", "extracted_code": "# Source: src/openparse/pdf.py\nclass Pdf:\n \"\"\"\n Simple utility class for working with PDF files. This class wraps the PdfReader and PdfWriter classes from pypdf.\n \"\"\"\n\n def __init__(self, file: Union[str, Path, PdfReader]):\n self.file_path = None\n self.file_metadata = {}\n if isinstance(file, (str, Path)):\n self.file_path = str(file)\n self.file_metadata = file_metadata(file)\n\n self.reader = PdfReader(file) if isinstance(file, (str, Path)) else file\n self.writer = PdfWriter()\n for page in self.reader.pages:\n self.writer.add_page(page)\n\n self.num_pages = len(self.reader.pages)\n\n def extract_layout_pages(self) -> Iterator[LTPage]:\n \"\"\"\n Yields layout objects for each page in the PDF using pdfminer.six.\n \"\"\"\n assert (\n self.file_path is not None\n ), \"PDF file path is required for this method for now.\"\n\n yield from extract_pages(self.file_path)\n\n def save(self, output_pdf: Union[str, Path]) -> None:\n \"\"\"\n Saves the content from the PdfWriter to a new PDF file.\n \"\"\"\n with open(str(output_pdf), \"wb\") as out_pdf:\n self.writer.write(out_pdf)\n\n def extract_pages(self, start_page: int, end_page: int) -> None:\n \"\"\"\n Extracts a range of pages from the PDF and adds them to the PdfWriter.\n \"\"\"\n for page_num in range(start_page - 1, end_page):\n self.writer.add_page(self.reader.pages[page_num])\n\n def to_pymupdf_doc(self):\n \"\"\"\n Transforms the PDF into a PyMuPDF (fitz) document.\n If modifications have been made using PdfWriter, it saves to a temporary file first.\n This function dynamically imports PyMuPDF (fitz), requiring it only if this method is called.\n \"\"\"\n try:\n import fitz # type: ignore\n except ImportError as err:\n raise ImportError(\n \"PyMuPDF (fitz) is not installed. This method requires PyMuPDF.\"\n ) from err\n\n if not self.writer.pages:\n return fitz.open(self.file_path)\n\n byte_stream = io.BytesIO()\n self.writer.write(byte_stream)\n return fitz.open(None, byte_stream)\n\n def _draw_bboxes(\n self,\n bboxes_with_color: List[_BboxWithColor],\n coordinates: Literal[\"top-left\", \"bottom-left\"],\n ):\n try:\n import fitz\n except ImportError as err:\n raise ImportError(\n \"PyMuPDF (fitz) is not installed. This method requires PyMuPDF.\"\n ) from err\n\n pdf = self.to_pymupdf_doc()\n\n for page in pdf:\n page.wrap_contents()\n\n for bbox_with_color in bboxes_with_color:\n bbox = bbox_with_color.bbox\n if bbox.page != page.number:\n continue\n if coordinates == \"bottom-left\":\n bbox = self._flip_coordinates(bbox)\n rect = fitz.Rect(bbox.x0, bbox.y0, bbox.x1, bbox.y1)\n page.draw_rect(\n rect, bbox_with_color.color\n ) # Use the color associated with this bbox\n\n if bbox_with_color.annotation_text:\n page.insert_text(\n rect.top_left,\n str(bbox_with_color.annotation_text),\n fontsize=12,\n )\n return pdf\n\n def display_with_bboxes(\n self,\n nodes: List[Node],\n page_nums: Optional[List[int]] = None,\n annotations: Optional[List[str]] = None,\n ):\n \"\"\"\n Display a single page of a PDF file using IPython.\n Optionally, display a piece of text on top of the bounding box.\n \"\"\"\n try:\n from IPython.display import Image, display # type: ignore\n except ImportError as err:\n raise ImportError(\n \"IPython is required to display PDFs. Please install it with `pip install ipython`.\"\n ) from err\n assert nodes, \"At least one node is required.\"\n\n bboxes = [node.bbox for node in nodes]\n flattened_bboxes = _prepare_bboxes_for_drawing(bboxes, annotations)\n marked_up_doc = self._draw_bboxes(flattened_bboxes, nodes[0].coordinate_system)\n if not page_nums:\n page_nums = list(range(marked_up_doc.page_count))\n for page_num in page_nums:\n page = marked_up_doc[page_num]\n img_data = page.get_pixmap().tobytes(\"png\")\n display(Image(data=img_data))\n\n def export_with_bboxes(\n self,\n nodes: List[Node],\n output_pdf: Union[str, Path],\n annotations: Optional[List[str]] = None,\n ) -> None:\n assert nodes, \"At least one node is required.\"\n\n bboxes = [node.bbox for node in nodes]\n flattened_bboxes = _prepare_bboxes_for_drawing(bboxes, annotations)\n marked_up_doc = self._draw_bboxes(flattened_bboxes, nodes[0].coordinate_system)\n marked_up_doc.save(str(output_pdf))\n\n def _flip_coordinates(self, bbox: Bbox) -> Bbox:\n fy0 = bbox.page_height - bbox.y1\n fy1 = bbox.page_height - bbox.y0\n return Bbox(\n page=bbox.page,\n page_height=bbox.page_height,\n page_width=bbox.page_width,\n x0=bbox.x0,\n y0=fy0,\n x1=bbox.x1,\n y1=fy1,\n )\n\n def to_imgs(self, page_numbers: Optional[List[int]] = None) -> List[Image.Image]:\n doc = self.to_pymupdf_doc()\n images = []\n\n if not doc.is_pdf:\n raise ValueError(\"The document is not in PDF format.\")\n if doc.needs_pass:\n raise ValueError(\"The PDF document is password protected.\")\n\n if page_numbers is None:\n page_numbers = list(range(doc.page_count))\n\n for n in page_numbers:\n page = doc[n]\n pix = page.get_pixmap()\n image = Image.frombytes(\"RGB\", (pix.width, pix.height), pix.samples)\n images.append(image)\n\n return images\n\n\n# Source: src/openparse/schemas.py\nclass NodeVariant(Enum):\n TEXT = \"text\"\n TABLE = \"table\"\n IMAGE = \"image\"\n\n\n# Source: src/openparse/text/pdfminer/core.py\ndef ingest(pdf_input: Pdf) -> List[Union[TextElement, ImageElement]]:\n \"\"\"Parse PDF and return a list of TextElement and ImageElement objects.\"\"\"\n elements = []\n page_layouts = pdf_input.extract_layout_pages()\n\n for page_num, page_layout in enumerate(page_layouts):\n page_width = page_layout.width\n page_height = page_layout.height\n page_elements = []\n for element in page_layout:\n if isinstance(element, LTTextContainer):\n lines = []\n for text_line in element:\n if isinstance(text_line, LTTextLine):\n lines.append(_create_line_element(text_line))\n if not lines:\n continue\n bbox = _get_bbox(lines)\n\n page_elements.append(\n TextElement(\n bbox=Bbox(\n x0=bbox[0],\n y0=bbox[1],\n x1=bbox[2],\n y1=bbox[3],\n page=page_num,\n page_width=page_width,\n page_height=page_height,\n ),\n text=\"\\n\".join(line.text for line in lines),\n lines=tuple(lines),\n )\n )\n elif isinstance(element, LTFigure):\n for e in element:\n if isinstance(e, LTImage):\n mime_type = _get_mime_type(e)\n if mime_type:\n if mime_type == \"image/png\":\n img_data = _process_png_image(e)\n else:\n img_data = e.stream.get_data()\n if img_data:\n base64_string = base64.b64encode(img_data).decode(\n \"utf-8\"\n )\n page_elements.append(\n ImageElement(\n bbox=Bbox(\n x0=e.bbox[0],\n y0=e.bbox[1],\n x1=e.bbox[2],\n y1=e.bbox[3],\n page=page_num,\n page_width=page_width,\n page_height=page_height,\n ),\n image=base64_string,\n image_mimetype=mime_type or \"unknown\",\n text=\"\",\n )\n )\n elements.extend(page_elements)\n return elements", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 9231}, "src/tests/text/pdf_miner/test_core.py::47": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["CharElement", "TextSpan", "_group_chars_into_spans"], "enclosing_function": "test_group_chars_into_spans", "extracted_code": "# Source: src/openparse/schemas.py\nclass TextSpan(BaseModel):\n text: str\n is_bold: bool\n is_italic: bool\n size: float\n\n @cached_property\n def is_heading(self) -> bool:\n MIN_HEADING_SIZE = 16\n return self.size >= MIN_HEADING_SIZE and self.is_bold\n\n def formatted_text(\n self,\n previous_span: Optional[\"TextSpan\"] = None,\n next_span: Optional[\"TextSpan\"] = None,\n ) -> str:\n \"\"\"Format text considering adjacent spans to avoid redundant markdown symbols.\"\"\"\n formatted = self.text\n\n # Check if style changes at the beginning\n if self.is_bold and (previous_span is None or not previous_span.is_bold):\n formatted = f\"**{formatted}\"\n if self.is_italic and (previous_span is None or not previous_span.is_italic):\n formatted = f\"*{formatted}\"\n\n # Check if style changes at the end\n if self.is_bold and (next_span is None or not next_span.is_bold):\n formatted = f\"{formatted}**\"\n if self.is_italic and (next_span is None or not next_span.is_italic):\n formatted = f\"{formatted}*\"\n\n return formatted\n\n model_config = ConfigDict(frozen=True)\n\n\n# Source: src/openparse/text/pdfminer/core.py\nclass CharElement(BaseModel):\n text: str\n fontname: str\n size: float\n\n @property\n def is_bold(self) -> bool:\n return \"Bold\" in self.fontname or \"bold\" in self.fontname\n\n @property\n def is_italic(self) -> bool:\n return \"Italic\" in self.fontname or \"italic\" in self.fontname\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_size(cls, data: Any) -> Any:\n data[\"size\"] = round(data[\"size\"], 2)\n return data\n\ndef _group_chars_into_spans(chars: Iterable[CharElement]) -> List[TextSpan]:\n spans = []\n current_text = \"\"\n current_style = (False, False, 0.0)\n\n for char in chars:\n char_style = (char.is_bold, char.is_italic, char.size)\n # If the current character is a space, compress multiple spaces and continue loop.\n if char.text.isspace():\n if not current_text.endswith(\" \"):\n current_text += \" \"\n continue\n\n # If style changes and there's accumulated text, add it to spans.\n if char_style != current_style and current_text:\n # Ensure there is at most one space at the end of the text.\n spans.append(\n TextSpan(\n text=current_text.rstrip()\n + (\" \" if current_text.endswith(\" \") else \"\"),\n is_bold=current_style[0],\n is_italic=current_style[1],\n size=current_style[2],\n )\n )\n current_text = char.text\n else:\n current_text += char.text\n current_style = char_style\n\n # After the loop, add any remaining text as a new span.\n if current_text:\n spans.append(\n TextSpan(\n text=current_text.rstrip()\n + (\" \" if current_text.endswith(\" \") else \"\"),\n is_bold=current_style[0],\n is_italic=current_style[1],\n size=current_style[2],\n )\n )\n return spans", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 3247}, "src/tests/text/pdf_miner/test_core.py::56": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["CharElement", "TextSpan", "_group_chars_into_spans"], "enclosing_function": "test_group_chars_into_spans", "extracted_code": "# Source: src/openparse/schemas.py\nclass TextSpan(BaseModel):\n text: str\n is_bold: bool\n is_italic: bool\n size: float\n\n @cached_property\n def is_heading(self) -> bool:\n MIN_HEADING_SIZE = 16\n return self.size >= MIN_HEADING_SIZE and self.is_bold\n\n def formatted_text(\n self,\n previous_span: Optional[\"TextSpan\"] = None,\n next_span: Optional[\"TextSpan\"] = None,\n ) -> str:\n \"\"\"Format text considering adjacent spans to avoid redundant markdown symbols.\"\"\"\n formatted = self.text\n\n # Check if style changes at the beginning\n if self.is_bold and (previous_span is None or not previous_span.is_bold):\n formatted = f\"**{formatted}\"\n if self.is_italic and (previous_span is None or not previous_span.is_italic):\n formatted = f\"*{formatted}\"\n\n # Check if style changes at the end\n if self.is_bold and (next_span is None or not next_span.is_bold):\n formatted = f\"{formatted}**\"\n if self.is_italic and (next_span is None or not next_span.is_italic):\n formatted = f\"{formatted}*\"\n\n return formatted\n\n model_config = ConfigDict(frozen=True)\n\n\n# Source: src/openparse/text/pdfminer/core.py\nclass CharElement(BaseModel):\n text: str\n fontname: str\n size: float\n\n @property\n def is_bold(self) -> bool:\n return \"Bold\" in self.fontname or \"bold\" in self.fontname\n\n @property\n def is_italic(self) -> bool:\n return \"Italic\" in self.fontname or \"italic\" in self.fontname\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_size(cls, data: Any) -> Any:\n data[\"size\"] = round(data[\"size\"], 2)\n return data\n\ndef _group_chars_into_spans(chars: Iterable[CharElement]) -> List[TextSpan]:\n spans = []\n current_text = \"\"\n current_style = (False, False, 0.0)\n\n for char in chars:\n char_style = (char.is_bold, char.is_italic, char.size)\n # If the current character is a space, compress multiple spaces and continue loop.\n if char.text.isspace():\n if not current_text.endswith(\" \"):\n current_text += \" \"\n continue\n\n # If style changes and there's accumulated text, add it to spans.\n if char_style != current_style and current_text:\n # Ensure there is at most one space at the end of the text.\n spans.append(\n TextSpan(\n text=current_text.rstrip()\n + (\" \" if current_text.endswith(\" \") else \"\"),\n is_bold=current_style[0],\n is_italic=current_style[1],\n size=current_style[2],\n )\n )\n current_text = char.text\n else:\n current_text += char.text\n current_style = char_style\n\n # After the loop, add any remaining text as a new span.\n if current_text:\n spans.append(\n TextSpan(\n text=current_text.rstrip()\n + (\" \" if current_text.endswith(\" \") else \"\"),\n is_bold=current_style[0],\n is_italic=current_style[1],\n size=current_style[2],\n )\n )\n return spans", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 3247}, "src/tests/text/pdf_miner/test_core.py::50": {"resolved_imports": ["src/openparse/pdf.py", "src/openparse/schemas.py", "src/openparse/text/pdfminer/core.py"], "used_names": ["CharElement", "TextSpan", "_group_chars_into_spans"], "enclosing_function": "test_group_chars_into_spans", "extracted_code": "# Source: src/openparse/schemas.py\nclass TextSpan(BaseModel):\n text: str\n is_bold: bool\n is_italic: bool\n size: float\n\n @cached_property\n def is_heading(self) -> bool:\n MIN_HEADING_SIZE = 16\n return self.size >= MIN_HEADING_SIZE and self.is_bold\n\n def formatted_text(\n self,\n previous_span: Optional[\"TextSpan\"] = None,\n next_span: Optional[\"TextSpan\"] = None,\n ) -> str:\n \"\"\"Format text considering adjacent spans to avoid redundant markdown symbols.\"\"\"\n formatted = self.text\n\n # Check if style changes at the beginning\n if self.is_bold and (previous_span is None or not previous_span.is_bold):\n formatted = f\"**{formatted}\"\n if self.is_italic and (previous_span is None or not previous_span.is_italic):\n formatted = f\"*{formatted}\"\n\n # Check if style changes at the end\n if self.is_bold and (next_span is None or not next_span.is_bold):\n formatted = f\"{formatted}**\"\n if self.is_italic and (next_span is None or not next_span.is_italic):\n formatted = f\"{formatted}*\"\n\n return formatted\n\n model_config = ConfigDict(frozen=True)\n\n\n# Source: src/openparse/text/pdfminer/core.py\nclass CharElement(BaseModel):\n text: str\n fontname: str\n size: float\n\n @property\n def is_bold(self) -> bool:\n return \"Bold\" in self.fontname or \"bold\" in self.fontname\n\n @property\n def is_italic(self) -> bool:\n return \"Italic\" in self.fontname or \"italic\" in self.fontname\n\n @model_validator(mode=\"before\")\n @classmethod\n def round_size(cls, data: Any) -> Any:\n data[\"size\"] = round(data[\"size\"], 2)\n return data\n\ndef _group_chars_into_spans(chars: Iterable[CharElement]) -> List[TextSpan]:\n spans = []\n current_text = \"\"\n current_style = (False, False, 0.0)\n\n for char in chars:\n char_style = (char.is_bold, char.is_italic, char.size)\n # If the current character is a space, compress multiple spaces and continue loop.\n if char.text.isspace():\n if not current_text.endswith(\" \"):\n current_text += \" \"\n continue\n\n # If style changes and there's accumulated text, add it to spans.\n if char_style != current_style and current_text:\n # Ensure there is at most one space at the end of the text.\n spans.append(\n TextSpan(\n text=current_text.rstrip()\n + (\" \" if current_text.endswith(\" \") else \"\"),\n is_bold=current_style[0],\n is_italic=current_style[1],\n size=current_style[2],\n )\n )\n current_text = char.text\n else:\n current_text += char.text\n current_style = char_style\n\n # After the loop, add any remaining text as a new span.\n if current_text:\n spans.append(\n TextSpan(\n text=current_text.rstrip()\n + (\" \" if current_text.endswith(\" \") else \"\"),\n is_bold=current_style[0],\n is_italic=current_style[1],\n size=current_style[2],\n )\n )\n return spans", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 3247}}} |