| """ |
| Unstructured document layout inference. |
| |
| Uses Unstructured API for document analysis. |
| """ |
| import asyncio |
| import os |
|
|
| import unstructured_client |
| from unstructured_client.models import operations, shared |
|
|
| from base import BaseInference, create_argument_parser, parse_args_with_extra |
|
|
| CATEGORY_MAP = { |
| "NarrativeText": "paragraph", |
| "ListItem": "paragraph", |
| "Title": "heading1", |
| "Address": "paragraph", |
| "Header": "header", |
| "Footer": "footer", |
| "UncategorizedText": "paragraph", |
| "Formula": "equation", |
| "FigureCaption": "caption", |
| "Table": "table", |
| "PageBreak": "paragraph", |
| "Image": "figure", |
| "PageNumber": "paragraph", |
| "CodeSnippet": "paragraph" |
| } |
|
|
|
|
| class UnstructuredInference(BaseInference): |
| """Unstructured document layout inference.""" |
| |
| def __init__( |
| self, |
| save_path, |
| input_formats=None, |
| concurrent_limit=None, |
| sampling_rate=1.0, |
| request_timeout=600, |
| random_seed=None, |
| group_by_document=False, |
| file_ext_mapping=None |
| ): |
| """Initialize the UnstructuredInference class. |
| |
| Args: |
| save_path (str): the json path to save the results |
| input_formats (list, optional): the supported file formats. |
| concurrent_limit (int, optional): maximum number of concurrent API requests |
| sampling_rate (float, optional): fraction of files to process (0.0-1.0) |
| request_timeout (float, optional): timeout in seconds for API requests |
| random_seed (int, optional): random seed for reproducible sampling |
| group_by_document (bool, optional): group per-page results into document-level |
| file_ext_mapping (str or dict, optional): file extension mapping for grouping |
| """ |
| super().__init__( |
| save_path, |
| input_formats, |
| concurrent_limit, |
| sampling_rate, |
| request_timeout, |
| random_seed, |
| group_by_document, |
| file_ext_mapping |
| ) |
|
|
| self.api_key = os.getenv("UNSTRUCTURED_API_KEY") or "" |
| self.url = os.getenv("UNSTRUCTURED_URL") or "" |
|
|
| if not self.api_key or not self.url: |
| raise ValueError("Please set the environment variables for Unstructured") |
|
|
| self.languages = ["eng", "kor"] |
| self.get_coordinates = True |
| self.infer_table_structure = True |
|
|
| self.client = unstructured_client.UnstructuredClient( |
| api_key_auth=self.api_key, |
| server_url=self.url, |
| ) |
|
|
| def post_process(self, data): |
| """Post-process Unstructured API response to standard format.""" |
| processed_dict = {} |
| for input_key in data.keys(): |
| output_data = data[input_key] |
|
|
| |
| if isinstance(output_data, dict) and "result" in output_data: |
| output_data = output_data["result"] |
|
|
| processed_dict[input_key] = {"elements": []} |
|
|
| id_counter = 0 |
| for elem in output_data: |
| transcription = elem["text"] |
| category = CATEGORY_MAP.get(elem["type"], "paragraph") |
| |
| if elem["metadata"]["coordinates"] is None: |
| continue |
|
|
| xy_coord = [{"x": x, "y": y} for x, y in elem["metadata"]["coordinates"]["points"]] |
|
|
| if category == "table": |
| transcription = elem["metadata"]["text_as_html"] |
|
|
| data_dict = { |
| "coordinates": xy_coord, |
| "category": category, |
| "id": id_counter, |
| "content": { |
| "text": str(transcription) if category != "table" else "", |
| "html": transcription if category == "table" else "", |
| "markdown": "" |
| } |
| } |
| processed_dict[input_key]["elements"].append(data_dict) |
| id_counter += 1 |
|
|
| return self._merge_processed_data(processed_dict) |
|
|
| def _partition_document(self, filepath): |
| """Partition document using Unstructured API.""" |
| with open(filepath, "rb") as f: |
| data = f.read() |
|
|
| req = operations.PartitionRequest( |
| partition_parameters=shared.PartitionParameters( |
| files=shared.Files(content=data, file_name=str(filepath)), |
| strategy=shared.Strategy.HI_RES, |
| pdf_infer_table_structure=self.infer_table_structure, |
| coordinates=self.get_coordinates, |
| languages=self.languages, |
| ), |
| ) |
|
|
| res = self.client.general.partition(request=req) |
| return res.elements |
|
|
| async def _call_api_async(self, filepath, *args, **kwargs): |
| """Make the actual async API call for a file.""" |
| loop = asyncio.get_event_loop() |
| return await loop.run_in_executor(None, self._partition_document, filepath) |
|
|
| def _call_api_sync(self, filepath, *args, **kwargs): |
| """Make the actual sync API call for a file.""" |
| return self._partition_document(filepath) |
|
|
|
|
| if __name__ == "__main__": |
| parser = create_argument_parser("Unstructured document layout inference") |
| args = parse_args_with_extra(parser) |
|
|
| unstructured_inference = UnstructuredInference( |
| args.save_path, |
| input_formats=args.input_formats, |
| concurrent_limit=args.concurrent, |
| sampling_rate=args.sampling_rate, |
| request_timeout=args.request_timeout, |
| random_seed=args.random_seed, |
| group_by_document=args.group_by_document, |
| file_ext_mapping=args.file_ext_mapping |
| ) |
| unstructured_inference.infer(args.data_path) |
|
|