|
| 1 | +import os |
| 2 | +import json |
| 3 | +import logging |
| 4 | +from datetime import datetime |
| 5 | +import unstructured_client |
| 6 | +from unstructured_client.models import shared, operations |
| 7 | + |
| 8 | +# Set up verbose logging |
| 9 | +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| 10 | +logger = logging.getLogger("unstructured-client") |
| 11 | +logger.setLevel(logging.INFO) |
| 12 | + |
| 13 | +def run_partition_with_hook(pdf_path: str): |
| 14 | + api_url = os.getenv("URL", None) |
| 15 | + api_key = os.getenv("KEY", None) |
| 16 | + |
| 17 | + client = unstructured_client.UnstructuredClient( |
| 18 | + server_url=api_url, |
| 19 | + api_key_auth=api_key, |
| 20 | + ) |
| 21 | + |
| 22 | + with open(pdf_path, "rb") as f: |
| 23 | + files = shared.Files( |
| 24 | + content=f.read(), |
| 25 | + file_name=pdf_path, |
| 26 | + ) |
| 27 | + |
| 28 | + partition_parameters = shared.PartitionParameters( |
| 29 | + files=files, |
| 30 | + strategy="hi_res", |
| 31 | + # This is the crucial parameter that activates the hook's logic |
| 32 | + split_pdf_page=True, |
| 33 | + ) |
| 34 | + |
| 35 | + request = operations.PartitionRequest( |
| 36 | + partition_parameters=partition_parameters |
| 37 | + ) |
| 38 | + |
| 39 | + resp = client.general.partition(request=request) |
| 40 | + |
| 41 | + print("\n--- Partitioning Response ---") |
| 42 | + if resp.elements: |
| 43 | + print(f"Successfully partitioned document into {len(resp.elements)} elements.") |
| 44 | + |
| 45 | + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| 46 | + filename = f"response_{timestamp}.json" |
| 47 | + elements_data = [element for element in resp.elements] |
| 48 | + |
| 49 | + with open(filename, 'w') as f: |
| 50 | + json.dump(elements_data, f, indent=2) |
| 51 | + print(f"✅ Saved to: {filename}") |
| 52 | + |
| 53 | + else: |
| 54 | + print("Partitioning call completed, but no elements were returned.") |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + test_filename = "input.pdf" |
| 58 | + |
| 59 | + if os.path.exists(test_filename): |
| 60 | + # Run the test |
| 61 | + run_partition_with_hook(test_filename) |
| 62 | + else: |
| 63 | + print(f"Error: The file '{test_filename}' was not found.") |
0 commit comments