LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
fix/test-azure-gcs-wf-etl (#678)
Kirtiman Mishra1dc021b6b610
diff --git a/backend/backend/exceptions.py b/backend/backend/exceptions.pyindex 01c59ad70..2e9986750 100644--- a/backend/backend/exceptions.py+++ b/backend/backend/exceptions.py@@ -39,3 +39,15 @@ def custom_exception_handler(exc, context) -> Response: # type: ignoreresponse.data["status_code"] = response.status_codereturn response+++class UnstractFSException(UnstractBaseException):+ """Handles all error from fs connector class and propagates the error+ message to UI.++ Args:+ UnstractBaseException: Inherits class UnstractBaseException+ """++ default_detail = "Error testing connection. "+ status_code = 500diff --git a/backend/workflow_manager/endpoint/destination.py b/backend/workflow_manager/endpoint/destination.pyindex dad50241a..5d8685bdd 100644--- a/backend/workflow_manager/endpoint/destination.py+++ b/backend/workflow_manager/endpoint/destination.py@@ -36,6 +36,9 @@ from workflow_manager.workflow.file_history_helper import FileHistoryHelperfrom workflow_manager.workflow.models.file_history import FileHistoryfrom workflow_manager.workflow.models.workflow import Workflow+from backend.exceptions import UnstractFSException+from unstract.connectors.exceptions import AzureHttpError+logger = logging.getLogger(__name__)@@ -218,31 +221,35 @@ class DestinationConnector(BaseConnector):destination_volume_path = os.path.join(self.execution_dir, ToolExecKey.OUTPUT_DIR)- destination_fs.create_dir_if_not_exists(input_dir=output_directory)- destination_fsspec = destination_fs.get_fsspec_fs()-- # Traverse local directory and create the same structure in the- # output_directory- for root, dirs, files in os.walk(destination_volume_path):- for dir_name in dirs:- destination_fsspec.mkdir(- os.path.join(++ try:+ destination_fs.create_dir_if_not_exists(input_dir=output_directory)+ destination_fsspec = destination_fs.get_fsspec_fs()++ # Traverse local directory and create the same structure in the+ # output_directory+ for root, dirs, files in os.walk(destination_volume_path):+ for dir_name in dirs:+ destination_fsspec.mkdir(+ os.path.join(+ output_directory,+ os.path.relpath(root, destination_volume_path),+ dir_name,+ )+ )++ for file_name in files:+ source_path = os.path.join(root, file_name)+ destination_path = os.path.join(output_directory,os.path.relpath(root, destination_volume_path),- dir_name,+ file_name,)- )-- for file_name in files:- source_path = os.path.join(root, file_name)- destination_path = os.path.join(- output_directory,- os.path.relpath(root, destination_volume_path),- file_name,- )- normalized_path = os.path.normpath(destination_path)- with open(source_path, "rb") as source_file:- destination_fsspec.write_bytes(normalized_path, source_file.read())+ destination_fs.upload_file_to_storage(+ source_path=source_path, destination_path=destination_path+ )+ except AzureHttpError as e:+ raise UnstractFSException(core_err=e) from edef insert_into_db(self, input_file_path: str) -> None:"""Insert data into the database."""diff --git a/backend/workflow_manager/workflow/workflow_helper.py b/backend/workflow_manager/workflow/workflow_helper.pyindex fbc4a560a..e9a420c5c 100644--- a/backend/workflow_manager/workflow/workflow_helper.py+++ b/backend/workflow_manager/workflow/workflow_helper.py@@ -157,6 +157,7 @@ class WorkflowHelper:except Exception as e:failed_files += 1error_message = f"Error processing file '{file_path}'. {e}"+ logger.error(error_message, stack_info=True, exc_info=True)execution_service.publish_log(message=error_message, level=LogLevel.ERROR)diff --git a/unstract/connectors/src/unstract/connectors/exceptions.py b/unstract/connectors/src/unstract/connectors/exceptions.pyindex bbb4d6128..f06e073a7 100644--- a/unstract/connectors/src/unstract/connectors/exceptions.py+++ b/unstract/connectors/src/unstract/connectors/exceptions.py@@ -31,3 +31,11 @@ class ConnectorError(ConnectorBaseException):def __str__(self) -> str:return f"{self.message}"+++class AzureHttpError(ConnectorError):+ """Handles invalid directory error from azure.++ Args:+ ConnectorError (Class): Inherits class ConnectorError+ """diff --git a/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.py b/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.pyindex c9a6311e3..caa5ca179 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.py@@ -2,15 +2,20 @@ import loggingimport osfrom typing import Any+import azure.core.exceptions as AzureExceptionfrom adlfs import AzureBlobFileSystem-from unstract.connectors.exceptions import ConnectorError+from unstract.connectors.exceptions import AzureHttpError, ConnectorErrorfrom unstract.connectors.filesystems.unstract_file_system import UnstractFileSystem+logging.getLogger("azurefs").setLevel(logging.ERROR)logger = logging.getLogger(__name__)class AzureCloudStorageFS(UnstractFileSystem):+ class AzureFsError:+ INVALID_PATH = "The specifed resource name contains invalid characters."+def __init__(self, settings: dict[str, Any]):super().__init__("AzureCloudStorageFS")account_name = settings.get("account_name", "")@@ -72,3 +77,38 @@ class AzureCloudStorageFS(UnstractFileSystem):f"Error from Azure Cloud Storage while testing connection: {str(e)}") from ereturn True++ def upload_file_to_storage(self, source_path: str, destination_path: str) -> None:+ """Method to upload filepath from tool to destination connector+ directory.++ Args:+ source_path (str): source file path from tool+ destination_path (str): destination azure directory file path++ Raises:+ AzureHttpError: returns error for invalid directory+ """+ normalized_path = os.path.normpath(destination_path)+ fs = self.get_fsspec_fs()+ try:+ with open(source_path, "rb") as source_file:+ fs.write_bytes(normalized_path, source_file.read())+ except AzureException.HttpResponseError as e:+ self.raise_http_exception(e=e, path=normalized_path)++ def raise_http_exception(+ self, e: AzureException.HttpResponseError, path: str+ ) -> AzureHttpError:+ user_message = f"Error from Azure Cloud Storage connector. {e.reason} "+ if hasattr(e, "reason"):+ error_reason = e.reason+ if error_reason == self.AzureFsError.INVALID_PATH:+ user_message = (+ f"Error from Azure Cloud Storage connector. "+ f"Invalid resource name for path '{path}'. {e.reason}"+ )+ raise AzureHttpError(+ user_message,+ treat_as_user_message=True,+ ) from ediff --git a/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.py b/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.pyindex 34057315a..73f8a38b4 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.py@@ -1,4 +1,5 @@import logging+import osfrom abc import ABC, abstractmethodfrom typing import Any@@ -77,8 +78,25 @@ class UnstractFileSystem(UnstractConnector, ABC):return f"{input_dir.strip('/')}/"def create_dir_if_not_exists(self, input_dir: str) -> None:- """Override to create dir of a connector if not exists."""+ """Method to create dir of a connector if not exists.++ Args:+ input_dir (str): input directory of source connector+ """fs_fsspec = self.get_fsspec_fs()is_dir = fs_fsspec.isdir(input_dir)if not is_dir:fs_fsspec.mkdir(input_dir)++ def upload_file_to_storage(self, source_path: str, destination_path: str) -> None:+ """Method to upload filepath from tool to destination connector+ directory.++ Args:+ source_path (str): _description_+ destination_path (str): _description_+ """+ normalized_path = os.path.normpath(destination_path)+ fs = self.get_fsspec_fs()+ with open(source_path, "rb") as source_file:+ fs.write_bytes(normalized_path, source_file.read())