11from time import sleep
22
3+ import httpx
4+
35from mindee .client_mixin import ClientMixin
46from mindee .error .mindee_error import MindeeClientError , MindeeError
57from mindee .error .mindee_http_error import handle_error
@@ -59,14 +61,21 @@ class Client(ClientMixin):
5961 """
6062
6163 api_key : str
64+ """API key for all endpoints."""
65+ http_client : httpx .Client | None
66+ """HTTP client for making requests."""
6267
63- def __init__ (self , api_key : str = "" ) -> None :
68+ def __init__ (
69+ self , api_key : str = "" , http_client : httpx .Client | None = None
70+ ) -> None :
6471 """
6572 Mindee API Client.
6673
6774 :param api_key: Your API key for all endpoints
75+ :param http_client: HTTP client for making requests.
6876 """
6977 self .api_key = api_key
78+ self .http_client = http_client
7079
7180 def parse (
7281 self ,
@@ -522,7 +531,8 @@ def _send_to_workflow(
522531 raise MindeeClientError ("No input document provided" )
523532
524533 workflow_endpoint = WorkflowEndpoint (
525- WorkflowSettings (api_key = self .api_key , workflow_id = workflow_id )
534+ WorkflowSettings (api_key = self .api_key , workflow_id = workflow_id ),
535+ self .http_client ,
526536 )
527537
528538 response = workflow_endpoint .workflow_execution_post (input_source , options )
@@ -555,8 +565,12 @@ def _build_endpoint(
555565 version = version ,
556566 )
557567 if account_name and len (account_name ) > 0 and account_name != "mindee" :
558- return CustomEndpoint (endpoint_name , account_name , version , api_settings )
559- return Endpoint (endpoint_name , account_name , version , api_settings )
568+ return CustomEndpoint (
569+ endpoint_name , account_name , version , api_settings , self .http_client
570+ )
571+ return Endpoint (
572+ endpoint_name , account_name , version , api_settings , self .http_client
573+ )
560574
561575 def create_endpoint (
562576 self ,
@@ -583,3 +597,20 @@ def create_endpoint(
583597 )
584598 version = "1"
585599 return self ._build_endpoint (endpoint_name , account_name , version )
600+
601+ def close (self ):
602+ """Close the HTTP client."""
603+ if self .http_client and not self .http_client .is_closed :
604+ self .http_client .close ()
605+
606+ def __enter__ (self ):
607+ return self
608+
609+ def __exit__ (self , exc_type , exc_val , exc_tb ):
610+ self .close ()
611+
612+ def __del__ (self ):
613+ """Ensure the HTTP client is closed when the object is garbage collected."""
614+ if self .http_client and self .http_client and not self .http_client .is_closed :
615+ logger .info ("Force-closing unclosed Mindee Client (V1) %s." , str (self ))
616+ self .close ()
0 commit comments