Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-1856 [GATED-FEAT] - Ruff linting issues in SDK v1 (#1560)

Praveen Kumar52362f1730fb
diff --git a/unstract/sdk1/pyproject.toml b/unstract/sdk1/pyproject.toml
index 515f26804..59e007de8 100644
--- a/unstract/sdk1/pyproject.toml
+++ b/unstract/sdk1/pyproject.toml
@@ -120,6 +120,8 @@ select = [
]
fixable = ["ALL"]
ignore = [
+ "ANN101", # Missing type annotation for self
+ "ANN102", # Missing type annotation for cls
"D100", # Missing docstring in public module
"D101", # Missing docstring in public class
"D102", # Missing docstring in public method
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/adapterkit.py b/unstract/sdk1/src/unstract/sdk1/adapters/adapterkit.py
index e672ef68c..55227e662 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/adapterkit.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/adapterkit.py
@@ -63,7 +63,7 @@ class Adapterkit:
def get_adapters_list(self) -> list[dict[str, "Any"]]:
adapters = []
- for adapter_id, adapter_registry_metadata in self._adapters.items():
+ for _adapter_id, adapter_registry_metadata in self._adapters.items():
m: Adapter = adapter_registry_metadata[Common.METADATA][Common.ADAPTER]
_id = m.get_id()
name = m.get_name()
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/base1.py b/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
index 4b24de1e6..edc435698 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
@@ -50,10 +50,10 @@ def register_adapters(adapters: dict[str, dict[str, "Any"]], adapter_type: str)
# IMPORTANT!
#
# We are introspecting adapter classes to retrieve id and metadata.
- # However their `repr`` is DIFFERENT from their `type`, because
- # `pydantic` is involved.
- # e.g. repr: <class 'unstract.sdk1.adapters.llm1.base.OpenAILLMAdapter'>
- # type: <class 'pydantic._internal._model_construction.ModelMetaclass'> # noqa: E501
+ # However their repr is DIFFERENT from their type, because
+ # pydantic is involved.
+ # e.g. repr - class unstract.sdk1.adapters.llm1.base.OpenAILLMAdapter
+ # type - class pydantic._internal._model_construction.ModelMetaclass
#
# This leads to following matrix for various introspection methods:
#
@@ -164,7 +164,7 @@ class BaseEmbeddingParameters(BaseModel):
class OpenAILLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/openai/"""
+ """See https://docs.litellm.ai/docs/providers/openai/."""
api_key: str
api_base: str
@@ -227,7 +227,7 @@ class OpenAILLMParameters(BaseChatCompletionParameters):
class AzureOpenAILLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/azure/#completion---using-azure_ad_token-api_base-api_version"""
+ """See https://docs.litellm.ai/docs/providers/azure/#completion---using-azure_ad_token-api_base-api_version."""
api_base: str
api_version: str | None = None
@@ -299,7 +299,7 @@ class AzureOpenAILLMParameters(BaseChatCompletionParameters):
class VertexAILLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/vertex"""
+ """See https://docs.litellm.ai/docs/providers/vertex."""
vertex_credentials: str
vertex_project: str
@@ -383,7 +383,7 @@ class VertexAILLMParameters(BaseChatCompletionParameters):
class AWSBedrockLLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/bedrock"""
+ """See https://docs.litellm.ai/docs/providers/bedrock."""
aws_access_key_id: str | None
aws_secret_access_key: str | None
@@ -457,7 +457,7 @@ class AWSBedrockLLMParameters(BaseChatCompletionParameters):
class AnthropicLLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/anthropic"""
+ """See https://docs.litellm.ai/docs/providers/anthropic."""
api_key: str
@@ -521,7 +521,7 @@ class AnthropicLLMParameters(BaseChatCompletionParameters):
class AnyscaleLLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/anyscale"""
+ """See https://docs.litellm.ai/docs/providers/anyscale."""
api_key: str
@@ -542,7 +542,7 @@ class AnyscaleLLMParameters(BaseChatCompletionParameters):
class MistralLLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/mistral"""
+ """See https://docs.litellm.ai/docs/providers/mistral."""
api_key: str
@@ -563,7 +563,7 @@ class MistralLLMParameters(BaseChatCompletionParameters):
class OllamaLLMParameters(BaseChatCompletionParameters):
- """See https://docs.litellm.ai/docs/providers/ollama"""
+ """See https://docs.litellm.ai/docs/providers/ollama."""
api_base: str
@@ -588,7 +588,7 @@ class OllamaLLMParameters(BaseChatCompletionParameters):
class OpenAIEmbeddingParameters(BaseEmbeddingParameters):
- """See https://docs.litellm.ai/docs/providers/openai"""
+ """See https://docs.litellm.ai/docs/providers/openai."""
api_key: str
api_base: str | None = None
@@ -609,7 +609,7 @@ class OpenAIEmbeddingParameters(BaseEmbeddingParameters):
class AzureOpenAIEmbeddingParameters(BaseEmbeddingParameters):
- """See https://docs.litellm.ai/docs/providers/azure"""
+ """See https://docs.litellm.ai/docs/providers/azure."""
api_key: str
api_base: str
@@ -649,7 +649,7 @@ class AzureOpenAIEmbeddingParameters(BaseEmbeddingParameters):
class VertexAIEmbeddingParameters(BaseEmbeddingParameters):
- """See https://docs.litellm.ai/docs/providers/vertex"""
+ """See https://docs.litellm.ai/docs/providers/vertex."""
vertex_credentials: str
vertex_project: str
@@ -681,7 +681,7 @@ class VertexAIEmbeddingParameters(BaseEmbeddingParameters):
class AWSBedrockEmbeddingParameters(BaseEmbeddingParameters):
- """See https://docs.litellm.ai/docs/providers/bedrock"""
+ """See https://docs.litellm.ai/docs/providers/bedrock."""
aws_access_key_id: str | None
aws_secret_access_key: str | None
@@ -706,7 +706,7 @@ class AWSBedrockEmbeddingParameters(BaseEmbeddingParameters):
class OllamaEmbeddingParameters(BaseEmbeddingParameters):
- """See https://docs.litellm.ai/docs/providers/ollama"""
+ """See https://docs.litellm.ai/docs/providers/ollama."""
api_base: str
embed_batch_size: int | None = 10
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/ocr/google_document_ai/src/google_document_ai.py b/unstract/sdk1/src/unstract/sdk1/adapters/ocr/google_document_ai/src/google_document_ai.py
index ef467ad7d..a36d3ae35 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/ocr/google_document_ai/src/google_document_ai.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/ocr/google_document_ai/src/google_document_ai.py
@@ -145,7 +145,7 @@ class GoogleDocumentAI(OCRAdapter):
except Exception as e:
logger.error(f"Error while processing document {e}")
if not isinstance(e, AdapterError):
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
else:
raise e
@@ -162,6 +162,6 @@ class GoogleDocumentAI(OCRAdapter):
except Exception as e:
logger.error(f"Error occured while testing adapter {e}")
if not isinstance(e, AdapterError):
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
else:
raise e
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/ocr/register.py b/unstract/sdk1/src/unstract/sdk1/adapters/ocr/register.py
index 7fbc8e53a..fde5558c1 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/ocr/register.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/ocr/register.py
@@ -1,12 +1,16 @@
+from __future__ import annotations
+
import logging
import os
from importlib import import_module
-from typing import Any
+from typing import TYPE_CHECKING, Any
from unstract.sdk1.adapters.constants import Common
-from unstract.sdk1.adapters.ocr.ocr_adapter import OCRAdapter
from unstract.sdk1.adapters.registry import AdapterRegistry
+if TYPE_CHECKING:
+ from unstract.sdk1.adapters.ocr.ocr_adapter import OCRAdapter
+
logger = logging.getLogger(__name__)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/utils.py b/unstract/sdk1/src/unstract/sdk1/adapters/utils.py
index 0ecf9464c..edaeb6d78 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/utils.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/utils.py
@@ -1,10 +1,15 @@
+from __future__ import annotations
+
import logging
+from typing import TYPE_CHECKING
-from requests import Response
-from requests.exceptions import RequestException
from unstract.sdk1.adapters.constants import Common
from unstract.sdk1.constants import MimeType
+if TYPE_CHECKING:
+ from requests import Response
+ from requests.exceptions import RequestException
+
logger = logging.getLogger(__name__)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/helper.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/helper.py
index e855d812d..ed2b4921e 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/helper.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/helper.py
@@ -55,38 +55,40 @@ class VectorDBHelper:
except Exception as e:
logger.error(f"Error occured while testing adapter {e}")
- raise VectorDBError(message=str(e), actual_err=e)
+ raise VectorDBError(message=str(e), actual_err=e) from e
@staticmethod
def get_collection_name(
collection_name_prefix: str,
embedding_dimension: int,
) -> str:
- """Notes:
+ """Get collection name for vector database storage.
+
This function constructs the collection / table name to store the
documents in the vector db.
If user supplies this field in the config metadata then system
would pick that and append it as prefix to embedding type.
If this does not come as user setting, then system looks for it
- in the get_vector_db() argument and append it to embedding type
+ in the get_vector_db() argument and append it to embedding type.
If it is not there in both places then system appends
"unstract_vector_db" as prefix to embedding type.
If embedding type is not passed in get_vector_db() as arg,
- then system ignores appending that
+ then system ignores appending that.
+
Args:
collection_name_prefix (str): the prefix to be added. If this is
not passed in, then the default DEFAULT_VECTOR_DB_NAME
- will be picked up for prefixing
+ will be picked up for prefixing.
embedding_dimension (str): this will be suffixed.
If this value is not passed in,
- then only collection_name_prefix will be returned
- Eg. collection_name_prefix -> mock_org
- embedding_dimension -> 1536
- return value -> mock_org_unstract_1536
+ then only collection_name_prefix will be returned.
+ Eg. collection_name_prefix -> mock_org.
+ embedding_dimension -> 1536.
+ return value -> mock_org_unstract_1536.
- collection_name_prefix -> No value
- embedding_type -> No value
- return value -> unstract_vector_db
+ collection_name_prefix -> No value.
+ embedding_type -> No value.
+ return value -> unstract_vector_db.
"""
vector_db_collection_name: str = VectorDbConstants.DEFAULT_VECTOR_DB_NAME
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/milvus/src/milvus.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/milvus/src/milvus.py
index 53d74541a..b2a7fa2d7 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/milvus/src/milvus.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/milvus/src/milvus.py
@@ -1,14 +1,18 @@
+from __future__ import annotations
+
import os
-from typing import Any
+from typing import TYPE_CHECKING
-from llama_index.core.vector_stores.types import VectorStore
from llama_index.vector_stores.milvus import MilvusVectorStore
-from pymilvus import MilvusClient
from unstract.sdk1.adapters.exceptions import AdapterError
from unstract.sdk1.adapters.vectordb.constants import VectorDbConstants
from unstract.sdk1.adapters.vectordb.helper import VectorDBHelper
from unstract.sdk1.adapters.vectordb.vectordb_adapter import VectorDBAdapter
+if TYPE_CHECKING:
+ from llama_index.core.vector_stores.types import VectorStore
+ from pymilvus import MilvusClient
+
class Constants:
URI = "uri"
@@ -17,7 +21,7 @@ class Constants:
class Milvus(VectorDBAdapter):
- def __init__(self, settings: dict[str, Any]) -> None:
+ def __init__(self, settings: dict[str, object]) -> None:
"""Initialize Milvus adapter.
Args:
@@ -70,7 +74,7 @@ class Milvus(VectorDBAdapter):
self._client = vector_db.client
return vector_db
except Exception as e:
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
def test_connection(self) -> bool:
vector_db = self.get_vector_db_instance()
@@ -80,6 +84,6 @@ class Milvus(VectorDBAdapter):
self._client.drop_collection(self._collection_name)
return test_result
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
if self._client:
self._client.close()
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_custom_vectordb.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_custom_vectordb.py
index 6c1b9f4d8..3944710fb 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_custom_vectordb.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_custom_vectordb.py
@@ -1,5 +1,4 @@
import time
-from typing import Any
from llama_index.core.schema import TextNode
from llama_index.core.vector_stores.types import VectorStore, VectorStoreQueryResult
@@ -20,7 +19,7 @@ class NoOpCustomVectorDB(VectorStore):
self.wait_time = wait_time
self.dim = dim
- def query(self, query, **kwargs: Any) -> VectorStoreQueryResult:
+ def query(self, query: object, **kwargs: object) -> VectorStoreQueryResult:
"""Query vector store."""
node1 = TextNode(text="This is a dummy document.", id_="1")
similarity_scores = [0.9]
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_vectordb.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_vectordb.py
index f5e1c05e1..0f396a79e 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_vectordb.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/no_op/src/no_op_vectordb.py
@@ -1,6 +1,5 @@
import os
import time
-from typing import Any
from llama_index.core.schema import BaseNode
from llama_index.core.vector_stores.types import VectorStore
@@ -14,7 +13,7 @@ from unstract.sdk1.adapters.vectordb.vectordb_adapter import VectorDBAdapter
class NoOpVectorDB(VectorDBAdapter):
- def __init__(self, settings: dict[str, Any]) -> None:
+ def __init__(self, settings: dict[str, object]) -> None:
"""Initialize NoOpVectorDB adapter.
Args:
@@ -62,16 +61,16 @@ class NoOpVectorDB(VectorDBAdapter):
self._client = vector_db.client
return vector_db
except Exception as e:
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
def test_connection(self) -> bool:
time.sleep(self._config.get("wait_time"))
return True
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
pass
- def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
+ def delete(self, ref_doc_id: str, **delete_kwargs: object) -> None:
pass
def add(self, ref_doc_id: str, nodes: list[BaseNode]) -> list[str]:
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/pinecone/src/pinecone.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/pinecone/src/pinecone.py
index 03900b790..17fe6dcbc 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/pinecone/src/pinecone.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/pinecone/src/pinecone.py
@@ -1,6 +1,5 @@
import logging
import os
-from typing import Any
from llama_index.core.schema import BaseNode
from llama_index.core.vector_stores.types import BasePydanticVectorStore
@@ -31,7 +30,13 @@ class Constants:
class Pinecone(VectorDBAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, object]) -> None:
+ """Initialize the Pinecone vector database adapter.
+
+ Args:
+ settings: Configuration dictionary containing Pinecone connection parameters
+ including API key, environment, and other settings.
+ """
self._config = settings
self._client: LLamaIndexPinecone | None = None
self._collection_name: str = VectorDbConstants.DEFAULT_VECTOR_DB_NAME
@@ -106,7 +111,7 @@ class Pinecone(VectorDBAdapter):
)
return self.vector_db
except Exception as e:
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
def test_connection(self) -> bool:
vector_db = self.get_vector_db_instance()
@@ -116,11 +121,11 @@ class Pinecone(VectorDBAdapter):
self._client.delete_index(self._collection_name)
return test_result
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
# Close connection is not defined for this client
pass
- def delete(self, ref_doc_id: str, **delete_kwargs: dict[Any, Any]) -> None:
+ def delete(self, ref_doc_id: str, **delete_kwargs: dict[object, object]) -> None:
specification = self._config.get(Constants.SPECIFICATION)
if specification == Constants.SPEC_SERVERLESS:
# To delete all records representing chunks of a single document,
@@ -133,7 +138,7 @@ class Pinecone(VectorDBAdapter):
logger.info(ids)
index.delete(ids=ids)
except Exception as e:
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
elif specification == Constants.SPEC_POD:
if self.vector_db.environment == "gcp-starter": # type: ignore
raise AdapterError(
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/postgres/src/postgres.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/postgres/src/postgres.py
index 39dc402f1..bfe28823c 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/postgres/src/postgres.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/postgres/src/postgres.py
@@ -1,16 +1,20 @@
+from __future__ import annotations
+
import os
-from typing import Any
+from typing import TYPE_CHECKING
from urllib.parse import quote_plus
import psycopg2
-from llama_index.core.vector_stores.types import BasePydanticVectorStore
from llama_index.vector_stores.postgres import PGVectorStore
-from psycopg2._psycopg import connection
from unstract.sdk1.adapters.exceptions import AdapterError
from unstract.sdk1.adapters.vectordb.constants import VectorDbConstants
from unstract.sdk1.adapters.vectordb.helper import VectorDBHelper
from unstract.sdk1.adapters.vectordb.vectordb_adapter import VectorDBAdapter
+if TYPE_CHECKING:
+ from llama_index.core.vector_stores.types import BasePydanticVectorStore
+ from psycopg2._psycopg import connection
+
class Constants:
DATABASE = "database"
@@ -23,7 +27,13 @@ class Constants:
class Postgres(VectorDBAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, object]) -> None:
+ """Initialize the Postgres vector database adapter.
+
+ Args:
+ settings: Configuration dictionary containing PostgreSQL connection parameters
+ including host, port, database, user, password, and other settings.
+ """
self._config = settings
self._client: connection | None = None
self._collection_name: str = VectorDbConstants.DEFAULT_VECTOR_DB_NAME
@@ -92,7 +102,7 @@ class Postgres(VectorDBAdapter):
return vector_db
except Exception as e:
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
def test_connection(self) -> bool:
vector_db = self.get_vector_db_instance()
@@ -108,6 +118,6 @@ class Postgres(VectorDBAdapter):
return test_result
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
if self._client:
self._client.close()
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/qdrant/src/qdrant.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/qdrant/src/qdrant.py
index bc20ba755..afd9be0c3 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/qdrant/src/qdrant.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/qdrant/src/qdrant.py
@@ -1,6 +1,5 @@
import logging
import os
-from typing import Any
from llama_index.core.vector_stores.types import BasePydanticVectorStore
from llama_index.vector_stores.qdrant import QdrantVectorStore
@@ -20,7 +19,13 @@ class Constants:
class Qdrant(VectorDBAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, object]) -> None:
+ """Initialize the Qdrant vector database adapter.
+
+ Args:
+ settings: Configuration dictionary containing Qdrant connection parameters
+ including URL, API key, and other settings.
+ """
self._config = settings
self._client: QdrantClient | None = None
self._collection_name: str = VectorDbConstants.DEFAULT_VECTOR_DB_NAME
@@ -83,7 +88,7 @@ class Qdrant(VectorDBAdapter):
except Exception as e:
raise self.parse_vector_db_err(e) from e
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
if self._client:
self._client.close(**kwargs)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/register.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/register.py
index 42e433772..1c551dafe 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/register.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/register.py
@@ -1,11 +1,15 @@
+from __future__ import annotations
+
import logging
import os
from importlib import import_module
-from typing import Any
+from typing import TYPE_CHECKING, Any
from unstract.sdk1.adapters.constants import Common
from unstract.sdk1.adapters.registry import AdapterRegistry
-from unstract.sdk1.adapters.vectordb.vectordb_adapter import VectorDBAdapter
+
+if TYPE_CHECKING:
+ from unstract.sdk1.adapters.vectordb.vectordb_adapter import VectorDBAdapter
logger = logging.getLogger(__name__)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/supabase/src/supabase.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/supabase/src/supabase.py
index 5db81cee3..6508eaad9 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/supabase/src/supabase.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/supabase/src/supabase.py
@@ -1,14 +1,18 @@
+from __future__ import annotations
+
import os
-from typing import Any
+from typing import TYPE_CHECKING
from urllib.parse import quote_plus
-from llama_index.core.vector_stores.types import VectorStore
from llama_index.vector_stores.supabase import SupabaseVectorStore
from unstract.sdk1.adapters.exceptions import AdapterError
from unstract.sdk1.adapters.vectordb.constants import VectorDbConstants
from unstract.sdk1.adapters.vectordb.helper import VectorDBHelper
from unstract.sdk1.adapters.vectordb.vectordb_adapter import VectorDBAdapter
-from vecs import Client
+
+if TYPE_CHECKING:
+ from llama_index.core.vector_stores.types import VectorStore
+ from vecs import Client
class Constants:
@@ -21,7 +25,13 @@ class Constants:
class Supabase(VectorDBAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, object]) -> None:
+ """Initialize the Supabase vector database adapter.
+
+ Args:
+ settings: Configuration dictionary containing Supabase connection parameters
+ including host, port, database, user, password, and other settings.
+ """
self._config = settings
self._client: Client | None = None
self._collection_name: str = VectorDbConstants.DEFAULT_VECTOR_DB_NAME
@@ -81,7 +91,7 @@ class Supabase(VectorDBAdapter):
self._client = vector_db.client
return vector_db
except Exception as e:
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
def test_connection(self) -> bool:
vector_db = self.get_vector_db_instance()
@@ -91,6 +101,6 @@ class Supabase(VectorDBAdapter):
self._client.delete_collection(self._collection_name)
return test_result
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
if self._client:
self._client.close()
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/vectordb_adapter.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/vectordb_adapter.py
index b32e7c9b9..786ab1145 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/vectordb_adapter.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/vectordb_adapter.py
@@ -14,7 +14,14 @@ class VectorDBAdapter(Adapter, ABC):
self,
name: str,
vector_db_instance: VectorStore | BasePydanticVectorStore,
- ):
+ ) -> None:
+ """Initialize the VectorDBAdapter base class.
+
+ Args:
+ name: Name identifier for the vector database adapter
+ vector_db_instance: The vector database instance (VectorStore or
+ BasePydanticVectorStore)
+ """
super().__init__(name)
self.name = name
self._vector_db_instance: VectorStore | BasePydanticVectorStore = (
@@ -58,8 +65,7 @@ class VectorDBAdapter(Adapter, ABC):
def get_vector_db_instance(
self, vector_db_config: dict[str, Any]
) -> BasePydanticVectorStore | VectorStore:
- """Instantiate the llama index VectorStore / BasePydanticVectorStore
- class.
+ """Instantiate the llama index VectorStore / BasePydanticVectorStore class.
Returns:
BasePydanticVectorStore / VectorStore:
@@ -68,7 +74,7 @@ class VectorDBAdapter(Adapter, ABC):
"""
return SimpleVectorStore()
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
"""Closes the client connection.
Returns:
@@ -78,7 +84,7 @@ class VectorDBAdapter(Adapter, ABC):
# library methods invoked
pass
- def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
+ def delete(self, ref_doc_id: str, **delete_kwargs: object) -> None:
"""Delete the specified docs.
Returns:
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/weaviate/src/weaviate.py b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/weaviate/src/weaviate.py
index 117362e8d..457f80a07 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/weaviate/src/weaviate.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/vectordb/weaviate/src/weaviate.py
@@ -1,6 +1,5 @@
import logging
import os
-from typing import Any
import weaviate
from llama_index.core.vector_stores.types import BasePydanticVectorStore
@@ -21,7 +20,13 @@ class Constants:
class Weaviate(VectorDBAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, object]) -> None:
+ """Initialize the Weaviate vector database adapter.
+
+ Args:
+ settings: Configuration dictionary containing Weaviate connection parameters
+ including URL, API key, and other settings.
+ """
self._config = settings
self._client: weaviate.Client | None = None
self._collection_name: str = VectorDbConstants.DEFAULT_VECTOR_DB_NAME
@@ -85,7 +90,7 @@ class Weaviate(VectorDBAdapter):
)
return vector_db
except Exception as e:
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
def test_connection(self) -> bool:
vector_db = self.get_vector_db_instance()
@@ -95,6 +100,6 @@ class Weaviate(VectorDBAdapter):
self._client.collections.delete(self._collection_name)
return test_result
- def close(self, **kwargs: Any) -> None:
+ def close(self, **kwargs: object) -> None:
if self._client:
self._client.close(**kwargs)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/helper.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/helper.py
index 076aa8f21..0f4f2f196 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/helper.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/helper.py
@@ -20,7 +20,7 @@ class X2TextHelper:
def parse_response(
response: Response,
out_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> tuple[str, bool]:
"""Parses the response from a request.
@@ -35,6 +35,8 @@ class X2TextHelper:
Returns:
tuple[str, bool]: Response's content and status of parsing
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
if not response.ok and not response.content:
return "", False
if isinstance(response.content, bytes):
@@ -64,8 +66,10 @@ class UnstructuredHelper:
unstructured_adapter_config: dict[str, Any],
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> str:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
try:
response: Response
local_storage = FileStorage(FileStorageProvider.LOCAL)
@@ -91,7 +95,7 @@ class UnstructuredHelper:
msg += f"and writing {output_file_path}"
msg += f": {str(e)}"
logger.error(msg)
- raise AdapterError(str(e))
+ raise AdapterError(str(e)) from e
@staticmethod
def make_request(
@@ -132,16 +136,16 @@ class UnstructuredHelper:
logger.error(f"Adapter error: {e}")
raise AdapterError(
"Unable to connect to unstructured-io's service, please check the URL"
- )
+ ) from e
except Timeout as e:
msg = "Request to unstructured-io's service has timed out"
logger.error(f"{msg}: {e}")
- raise AdapterError(msg)
+ raise AdapterError(msg) from e
except HTTPError as e:
logger.error(f"Adapter error: {e}")
default_err = "Error while calling the unstructured-io service"
msg = AdapterUtils.get_msg_from_request_exc(
err=e, message_key="detail", default_err=default_err
)
- raise AdapterError("unstructured-io: " + msg)
+ raise AdapterError("unstructured-io: " + msg) from e
return response
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llama_parse/src/llama_parse.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llama_parse/src/llama_parse.py
index 8a64a7dca..5f148c2ff 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llama_parse/src/llama_parse.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llama_parse/src/llama_parse.py
@@ -15,7 +15,13 @@ logger = logging.getLogger(__name__)
class LlamaParseAdapter(X2TextAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, Any]) -> None:
+ """Initialize the LlamaParse text extraction adapter.
+
+ Args:
+ settings: Configuration dictionary containing LlamaParse API settings
+ including API key, base URL, and other parameters.
+ """
super().__init__("LlamaParse")
self.config = settings
@@ -40,8 +46,10 @@ class LlamaParseAdapter(X2TextAdapter):
def _call_parser(
self,
input_file_path: str,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> str:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
parser = LlamaParse(
api_key=self.config.get(LlamaParseConfig.API_KEY),
base_url=self.config.get(LlamaParseConfig.BASE_URL),
@@ -71,7 +79,7 @@ class LlamaParseAdapter(X2TextAdapter):
)
except OSError as os_err:
logger.error("Exception raised while handling input file.")
- raise AdapterError(str(os_err))
+ raise AdapterError(str(os_err)) from os_err
file_bytes = fs.read(path=input_file_path, mode="rb")
documents = parser.load_data(
@@ -82,12 +90,12 @@ class LlamaParseAdapter(X2TextAdapter):
logger.error(f"Invalid Base URL given. : {connec_err}")
raise AdapterError(
"Unable to connect to llama-parse`s service, please check the Base URL"
- )
+ ) from connec_err
except Exception as exe:
logger.error(
"Seems like an invalid API Key or possible internal errors: {exe}"
)
- raise AdapterError(str(exe))
+ raise AdapterError(str(exe)) from exe
response_text = documents[0].text
return response_text # type:ignore
@@ -96,9 +104,11 @@ class LlamaParseAdapter(X2TextAdapter):
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[Any, Any],
) -> TextExtractionResult:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
response_text = self._call_parser(input_file_path=input_file_path, fs=fs)
if output_file_path:
fs.write(
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer/src/llm_whisperer.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer/src/llm_whisperer.py
index 3134e8b9f..71a8fb9f2 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer/src/llm_whisperer.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer/src/llm_whisperer.py
@@ -33,7 +33,13 @@ logger = logging.getLogger(__name__)
class LLMWhisperer(X2TextAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, Any]) -> None:
+ """Initialize the LLMWhisperer text extraction adapter.
+
+ Args:
+ settings: Configuration dictionary containing LLMWhisperer API settings
+ including API key, base URL, and other parameters.
+ """
super().__init__("LLMWhisperer")
self.config = settings
@@ -70,9 +76,9 @@ class LLMWhisperer(X2TextAdapter):
self,
request_method: HTTPMethod,
request_endpoint: str,
- headers: dict[str, Any] | None = None,
- params: dict[str, Any] | None = None,
- data: Any | None = None,
+ headers: dict[str, object] | None = None,
+ params: dict[str, object] | None = None,
+ data: object | None = None,
) -> Response:
"""Makes a request to LLMWhisperer service.
@@ -115,18 +121,18 @@ class LLMWhisperer(X2TextAdapter):
logger.error(f"Adapter error: {e}")
raise ExtractorError(
"Unable to connect to LLMWhisperer service, please check the URL"
- )
+ ) from e
except Timeout as e:
msg = "Request to LLMWhisperer has timed out"
logger.error(f"{msg}: {e}")
- raise ExtractorError(msg)
+ raise ExtractorError(msg) from e
except HTTPError as e:
logger.error(f"Adapter error: {e}")
default_err = "Error while calling the LLMWhisperer service"
msg = AdapterUtils.get_msg_from_request_exc(
err=e, message_key="message", default_err=default_err
)
- raise ExtractorError(msg)
+ raise ExtractorError(msg) from e
return response
def _get_whisper_params(self, enable_highlight: bool = False) -> dict[str, Any]:
@@ -224,16 +230,16 @@ class LLMWhisperer(X2TextAdapter):
Returns:
WhisperStatus: Status of the extraction
"""
- POLL_INTERVAL = WhispererDefaults.POLL_INTERVAL
- MAX_POLLS = WhispererDefaults.MAX_POLLS
+ poll_interval = WhispererDefaults.POLL_INTERVAL
+ max_polls = WhispererDefaults.MAX_POLLS
request_count = 0
# Check status in fixed intervals upto max poll count.
while True:
request_count += 1
logger.info(
- f"Checking status with interval: {POLL_INTERVAL}s"
- f", request count: {request_count} [max: {MAX_POLLS}]"
+ f"Checking status with interval: {poll_interval}s"
+ f", request count: {request_count} [max: {max_polls}]"
)
status_response = self._make_request(
request_method=HTTPMethod.GET,
@@ -254,11 +260,11 @@ class LLMWhisperer(X2TextAdapter):
)
# Exit with error if max poll count is reached
- if request_count >= MAX_POLLS:
+ if request_count >= max_polls:
raise ExtractorError(
f"Unable to extract text after attempting {request_count} times"
)
- time.sleep(POLL_INTERVAL)
+ time.sleep(poll_interval)
return status
@@ -303,9 +309,11 @@ class LLMWhisperer(X2TextAdapter):
def _send_whisper_request(
self,
input_file_path: str,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
enable_highlight: bool = False,
) -> requests.Response:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
headers = self._get_request_headers()
headers["Content-Type"] = "application/octet-stream"
params = self._get_whisper_params(enable_highlight)
@@ -321,15 +329,17 @@ class LLMWhisperer(X2TextAdapter):
)
except OSError as e:
logger.error(f"OS error while reading {input_file_path}: {e}")
- raise ExtractorError(str(e))
+ raise ExtractorError(str(e)) from e
return response
def _extract_text_from_response(
self,
output_file_path: str | None,
response: requests.Response,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> str:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
output_json = {}
if response.status_code == 200:
output_json = response.json()
@@ -348,10 +358,12 @@ class LLMWhisperer(X2TextAdapter):
self,
output_json: dict,
output_file_path: Path,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> None:
- """Writes the extracted text and metadata to the specified output file
- and metadata file.
+ """Write extracted text and metadata to output files.
+
+ Writes the extracted text and metadata to the specified output file and
+ metadata file.
Args:
output_json (dict): The dictionary containing the extracted data,
@@ -362,6 +374,8 @@ class LLMWhisperer(X2TextAdapter):
Raises:
ExtractorError: If there is an error while writing the output file.
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
try:
text_output = output_json.get("text", "")
logger.info(f"Writing output to {output_file_path}")
@@ -397,13 +411,13 @@ class LLMWhisperer(X2TextAdapter):
except Exception as e:
logger.error(f"Error while writing {output_file_path}: {e}")
- raise ExtractorError(str(e))
+ raise ExtractorError(str(e)) from e
def process(
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[Any, Any],
) -> TextExtractionResult:
"""Used to extract text from documents.
@@ -417,6 +431,8 @@ class LLMWhisperer(X2TextAdapter):
Returns:
str: Extracted text
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
response: requests.Response = self._send_whisper_request(
input_file_path,
fs,
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/dto.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/dto.py
index 11bc036ff..2bf5665e3 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/dto.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/dto.py
@@ -6,7 +6,8 @@ class WhispererRequestParams:
"""DTO for LLM Whisperer API request parameters.
Args:
- tag (Optional[Union[str, List[str]]]): Tag value. Can be initialized with List[str] or str.
+ tag (Optional[Union[str, List[str]]]): Tag value. Can be initialized with
+ List[str] or str.
Will be converted to str or None after initialization.
enable_highlight (bool): Whether to enable highlighting. Defaults to False.
"""
@@ -16,6 +17,7 @@ class WhispererRequestParams:
enable_highlight: bool = False
def __post_init__(self) -> None:
+ """Post-initialization processing for LLMWhisperer V2 request data."""
# TODO: Allow list of tags once it's supported in LLMW v2
if isinstance(self.tag, list):
self.tag = self.tag[0] if self.tag else None
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.py
index 5e96c19bc..2977d5052 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.py
@@ -240,8 +240,10 @@ class LLMWhispererHelper:
input_file_path: str,
config: dict[str, Any],
extra_params: WhispererRequestParams,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> requests.Response:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
params = LLMWhispererHelper.get_whisperer_params(
config=config, extra_params=extra_params
)
@@ -302,8 +304,10 @@ class LLMWhispererHelper:
def extract_text_from_response(
output_file_path: str | None,
response: dict[str, Any],
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> str:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
if not response:
raise ExtractorError("Couldn't extract text from file", status_code=500)
output_json = {}
@@ -320,7 +324,7 @@ class LLMWhispererHelper:
def write_output_to_file(
output_json: dict,
output_file_path: Path,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> None:
"""Write LLMW outputs to file.
@@ -337,6 +341,8 @@ class LLMWhispererHelper:
Raises:
ExtractorError: If there is an error while writing the output file.
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
try:
text_output = output_json.get("result_text", "")
logger.info(f"Writing output to {output_file_path}")
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/llm_whisperer_v2.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/llm_whisperer_v2.py
index 221938349..9325320d4 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/llm_whisperer_v2.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/llm_whisperer_v2.py
@@ -1,8 +1,9 @@
+from __future__ import annotations
+
import logging
import os
-from typing import Any
+from typing import TYPE_CHECKING, Any
-import requests
from unstract.sdk1.adapters.x2text.constants import X2TextConstants
from unstract.sdk1.adapters.x2text.dto import (
TextExtractionMetadata,
@@ -18,11 +19,20 @@ from unstract.sdk1.adapters.x2text.llm_whisperer_v2.src.helper import LLMWhisper
from unstract.sdk1.adapters.x2text.x2text_adapter import X2TextAdapter
from unstract.sdk1.file_storage import FileStorage, FileStorageProvider
+if TYPE_CHECKING:
+ import requests
+
logger = logging.getLogger(__name__)
class LLMWhispererV2(X2TextAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, Any]) -> None:
+ """Initialize the LLMWhispererV2 text extraction adapter.
+
+ Args:
+ settings: Configuration dictionary containing LLMWhispererV2 API settings
+ including API key, base URL, and other parameters.
+ """
super().__init__("LLMWhispererV2")
self.config = settings
@@ -55,7 +65,7 @@ class LLMWhispererV2(X2TextAdapter):
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[Any, Any],
) -> TextExtractionResult:
"""Used to extract text from documents.
@@ -69,6 +79,8 @@ class LLMWhispererV2(X2TextAdapter):
Returns:
str: Extracted text
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
enable_highlight = kwargs.get(X2TextConstants.ENABLE_HIGHLIGHT, False)
extra_params = WhispererRequestParams(
tag=kwargs.get(X2TextConstants.TAGS),
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/no_op/src/no_op_x2text.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/no_op/src/no_op_x2text.py
index b8907c052..7e7caf4b6 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/no_op/src/no_op_x2text.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/no_op/src/no_op_x2text.py
@@ -11,7 +11,13 @@ logger = logging.getLogger(__name__)
class NoOpX2Text(X2TextAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, Any]) -> None:
+ """Initialize the NoOpX2Text adapter for testing purposes.
+
+ Args:
+ settings: Configuration dictionary containing adapter settings
+ including wait_time and other test parameters.
+ """
super().__init__("NoOpX2Text")
self.config = settings
@@ -37,9 +43,11 @@ class NoOpX2Text(X2TextAdapter):
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[Any, Any],
) -> TextExtractionResult:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
extracted_text: str = (
"This is a No Op x2text adapter response."
" This is a sample response and intended for testing \f"
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/register.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/register.py
index 27987b86c..48d6a606a 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/register.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/register.py
@@ -1,11 +1,15 @@
+from __future__ import annotations
+
import logging
import os
from importlib import import_module
-from typing import Any
+from typing import TYPE_CHECKING, Any
from unstract.sdk1.adapters.constants import Common
from unstract.sdk1.adapters.registry import AdapterRegistry
-from unstract.sdk1.adapters.x2text.x2text_adapter import X2TextAdapter
+
+if TYPE_CHECKING:
+ from unstract.sdk1.adapters.x2text.x2text_adapter import X2TextAdapter
logger = logging.getLogger(__name__)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_community/src/unstructured_community.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_community/src/unstructured_community.py
index 411732643..6d7eaee35 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_community/src/unstructured_community.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_community/src/unstructured_community.py
@@ -11,7 +11,13 @@ logger = logging.getLogger(__name__)
class UnstructuredCommunity(X2TextAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, Any]) -> None:
+ """Initialize the UnstructuredCommunity text extraction adapter.
+
+ Args:
+ settings: Configuration dictionary containing Unstructured.io Community
+ API settings and other parameters.
+ """
super().__init__("UnstructuredIOCommunity")
self.config = settings
@@ -37,9 +43,11 @@ class UnstructuredCommunity(X2TextAdapter):
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[Any, Any],
) -> TextExtractionResult:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
extracted_text: str = UnstructuredHelper.process_document(
self.config, input_file_path, output_file_path, fs
)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_enterprise/src/unstructured_enterprise.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_enterprise/src/unstructured_enterprise.py
index 0f5ffd8d6..71879a975 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_enterprise/src/unstructured_enterprise.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/unstructured_enterprise/src/unstructured_enterprise.py
@@ -11,7 +11,13 @@ logger = logging.getLogger(__name__)
class UnstructuredEnterprise(X2TextAdapter):
- def __init__(self, settings: dict[str, Any]):
+ def __init__(self, settings: dict[str, Any]) -> None:
+ """Initialize the UnstructuredEnterprise text extraction adapter.
+
+ Args:
+ settings: Configuration dictionary containing Unstructured.io Enterprise
+ API settings and other parameters.
+ """
super().__init__("UnstructuredIOEnterprise")
self.config = settings
@@ -37,9 +43,11 @@ class UnstructuredEnterprise(X2TextAdapter):
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[str, Any],
) -> TextExtractionResult:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
extracted_text: str = UnstructuredHelper.process_document(
self.config, input_file_path, output_file_path, fs
)
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/x2text_adapter.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/x2text_adapter.py
index 56111479f..f2febc246 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/x2text_adapter.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/x2text_adapter.py
@@ -8,7 +8,12 @@ from unstract.sdk1.file_storage import FileStorage, FileStorageProvider
class X2TextAdapter(Adapter, ABC):
- def __init__(self, name: str):
+ def __init__(self, name: str) -> None:
+ """Initialize the X2TextAdapter base class.
+
+ Args:
+ name: Name identifier for the text extraction adapter.
+ """
super().__init__(name)
self.name = name
@@ -39,9 +44,11 @@ class X2TextAdapter(Adapter, ABC):
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[Any, Any],
) -> TextExtractionResult:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
return TextExtractionResult(
extracted_text="extracted text", extraction_metadata=None
)
diff --git a/unstract/sdk1/src/unstract/sdk1/audit.py b/unstract/sdk1/src/unstract/sdk1/audit.py
index 64eb79caf..0396ab33a 100644
--- a/unstract/sdk1/src/unstract/sdk1/audit.py
+++ b/unstract/sdk1/src/unstract/sdk1/audit.py
@@ -9,8 +9,7 @@ from unstract.sdk1.utils.common import TokenCounterCompat
class Audit(StreamMixin):
- """The 'Audit' class is responsible for pushing usage data to the platform
- service.
+ """The 'Audit' class is responsible for pushing usage data to the platform service.
Methods:
- push_usage_data: Pushes the usage data to the platform service.
@@ -20,6 +19,11 @@ class Audit(StreamMixin):
"""
def __init__(self, log_level: LogLevel = LogLevel.INFO) -> None:
+ """Initialize the Audit class for tracking usage data.
+
+ Args:
+ log_level: Logging level for output control
+ """
super().__init__(log_level)
def push_usage_data(
@@ -28,7 +32,7 @@ class Audit(StreamMixin):
token_counter: TokenCountingHandler | TokenCounterCompat = None,
model_name: str = "",
event_type: CBEventType = None,
- kwargs: dict[Any, Any] = {},
+ kwargs: dict[Any, Any] = None,
) -> None:
"""Pushes the usage data to the platform service.
@@ -56,6 +60,8 @@ class Audit(StreamMixin):
requests.RequestException: If there is an error while pushing the
usage details.
"""
+ if kwargs is None:
+ kwargs = {}
platform_host = self.get_env_or_die(ToolEnv.PLATFORM_HOST)
platform_port = self.get_env_or_die(ToolEnv.PLATFORM_PORT)
@@ -125,8 +131,10 @@ class Audit(StreamMixin):
page_count: int,
file_size: int,
file_type: str,
- kwargs: dict[Any, Any] = {},
+ kwargs: dict[Any, Any] = None,
) -> None:
+ if kwargs is None:
+ kwargs = {}
platform_host = self.get_env_or_die(ToolEnv.PLATFORM_HOST)
platform_port = self.get_env_or_die(ToolEnv.PLATFORM_PORT)
run_id = kwargs.get("run_id", "")
diff --git a/unstract/sdk1/src/unstract/sdk1/cache.py b/unstract/sdk1/src/unstract/sdk1/cache.py
index 50fe6186b..9a8565920 100644
--- a/unstract/sdk1/src/unstract/sdk1/cache.py
+++ b/unstract/sdk1/src/unstract/sdk1/cache.py
@@ -1,5 +1,3 @@
-from typing import Any
-
import requests
from unstract.sdk1.constants import LogLevel
from unstract.sdk1.platform import PlatformHelper
@@ -14,7 +12,9 @@ class ToolCache(PlatformHelper):
"""
def __init__(self, tool: BaseTool, platform_host: str, platform_port: int) -> None:
- """Args:
+ """Initialize the Cache for tool-specific caching operations.
+
+ Args:
tool (AbstractTool): Instance of AbstractTool
platform_host (str): The host of the platform.
platform_port (int): The port of the platform.
@@ -53,7 +53,7 @@ class ToolCache(PlatformHelper):
)
return False
- def get(self, key: str) -> Any | None:
+ def get(self, key: str) -> object | None:
"""Gets the value for a key in the cache.
Args:
diff --git a/unstract/sdk1/src/unstract/sdk1/constants.py b/unstract/sdk1/src/unstract/sdk1/constants.py
index ad865840f..65119d8ba 100644
--- a/unstract/sdk1/src/unstract/sdk1/constants.py
+++ b/unstract/sdk1/src/unstract/sdk1/constants.py
@@ -22,9 +22,6 @@ class AdapterTypes(Enum):
X2TEXT = "X2TEXT"
-from enum import Enum
-
-
class ToolEnv:
"""Environment variables used by tools.
diff --git a/unstract/sdk1/src/unstract/sdk1/embedding.py b/unstract/sdk1/src/unstract/sdk1/embedding.py
index b6fb1c121..2e861b002 100644
--- a/unstract/sdk1/src/unstract/sdk1/embedding.py
+++ b/unstract/sdk1/src/unstract/sdk1/embedding.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import os
-from typing import Any
+from typing import TYPE_CHECKING
import litellm
from llama_index.core.embeddings import BaseEmbedding
@@ -11,12 +11,15 @@ from unstract.sdk1.adapters.embedding1 import adapters
from unstract.sdk1.constants import ToolEnv
from unstract.sdk1.exceptions import SdkError
from unstract.sdk1.platform import PlatformHelper
-from unstract.sdk1.tool.base import BaseTool
from unstract.sdk1.utils.callback_manager import CallbackManager
+if TYPE_CHECKING:
+ from unstract.sdk1.tool.base import BaseTool
+
class Embedding:
"""Unified embedding interface powered by LiteLLM.
+
Internally invokes Unstract embedding adapters.
Accepts either of the following pairs for init:
@@ -29,11 +32,24 @@ class Embedding:
def __init__(
self,
adapter_id: str = "",
- adapter_metadata: dict[str, Any] = {},
+ adapter_metadata: dict[str, object] = None,
adapter_instance_id: str = "",
- tool: BaseTool = None,
- kwargs: dict[str, Any] = {},
+ tool: BaseTool | None = None,
+ kwargs: dict[str, object] = None,
) -> None:
+ """Initialize the Embedding interface.
+
+ Args:
+ adapter_id: Adapter identifier for embedding model
+ adapter_metadata: Configuration metadata for the adapter
+ adapter_instance_id: Instance identifier for the adapter
+ tool: BaseTool instance for tool-specific operations
+ kwargs: Additional keyword arguments for configuration
+ """
+ if adapter_metadata is None:
+ adapter_metadata = {}
+ if kwargs is None:
+ kwargs = {}
try:
embedding_config = None
@@ -63,16 +79,16 @@ class Embedding:
# Retrieve the adapter class.
self.adapter = adapters[self._adapter_id][Common.MODULE]
- except KeyError:
+ except KeyError as e:
raise SdkError(
"Embedding adapter not supported: " + adapter_id or adapter_instance_id
- )
+ ) from e
try:
- self.platform_kwargs: dict[str, Any] = kwargs
- self.kwargs: dict[str, Any] = self.adapter.validate(self._adapter_metadata)
+ self.platform_kwargs: dict[str, object] = kwargs
+ self.kwargs: dict[str, object] = self.adapter.validate(self._adapter_metadata)
except ValidationError as e:
- raise SdkError("Invalid embedding adapter metadata: " + str(e))
+ raise SdkError("Invalid embedding adapter metadata: " + str(e)) from e
self._length = len(self.get_embedding(self._TEST_SNIPPET))
@@ -128,11 +144,20 @@ class EmbeddingCompat(BaseEmbedding):
def __init__(
self,
adapter_id: str = "",
- adapter_metadata: dict[str, Any] = None,
+ adapter_metadata: dict[str, object] = None,
adapter_instance_id: str = "",
- tool: BaseTool = None,
- kwargs: dict[str, Any] = None,
- ):
+ tool: BaseTool | None = None,
+ kwargs: dict[str, object] = None,
+ ) -> None:
+ """Initialize the EmbeddingCompat wrapper for compatibility.
+
+ Args:
+ adapter_id: Adapter identifier for embedding model
+ adapter_metadata: Configuration metadata for the adapter
+ adapter_instance_id: Instance identifier for the adapter
+ tool: BaseTool instance for tool-specific operations
+ kwargs: Additional keyword arguments for configuration
+ """
adapter_metadata = adapter_metadata or {}
kwargs = kwargs or {}
super().__init__(**kwargs)
diff --git a/unstract/sdk1/src/unstract/sdk1/exceptions.py b/unstract/sdk1/src/unstract/sdk1/exceptions.py
index 194aeced9..de67a45b5 100644
--- a/unstract/sdk1/src/unstract/sdk1/exceptions.py
+++ b/unstract/sdk1/src/unstract/sdk1/exceptions.py
@@ -8,7 +8,14 @@ class SdkError(Exception):
message: str = DEFAULT_MESSAGE,
status_code: int | None = None,
actual_err: Exception | None = None,
- ):
+ ) -> None:
+ """Initialize the SdkError exception.
+
+ Args:
+ message: Error message description
+ status_code: HTTP status code associated with the error
+ actual_err: The original exception that caused this error
+ """
super().__init__(message)
# Make it user friendly wherever possible
self.message = message
@@ -22,14 +29,21 @@ class SdkError(Exception):
if hasattr(actual_err, "status_code"): # Most providers
self.status_code = actual_err.status_code
elif hasattr(actual_err, "http_status"): # Few providers like Mistral
- self.status_code = resolve_err_status_code(actual_err.status)
+ self.status_code = actual_err.http_status
def __str__(self) -> str:
+ """Return string representation of the SdkError."""
return self.message
class IndexingError(SdkError):
- def __init__(self, message: str = "", **kwargs):
+ def __init__(self, message: str = "", **kwargs: object) -> None:
+ """Initialize the IndexingError exception.
+
+ Args:
+ message: Error message description
+ **kwargs: Additional keyword arguments passed to parent SdkError
+ """
if "404" in message:
message = "Index not found. Please check vector DB settings."
super().__init__(message, **kwargs)
diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/env_helper.py b/unstract/sdk1/src/unstract/sdk1/file_storage/env_helper.py
index cf347f656..22b521094 100644
--- a/unstract/sdk1/src/unstract/sdk1/file_storage/env_helper.py
+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/env_helper.py
@@ -19,9 +19,9 @@ class EnvHelper:
@staticmethod
def get_storage(storage_type: StorageType, env_name: str) -> FileStorage:
- """Helper function for clients to pick up remote storage configuration
- from env, initialise the file storage for the same and return the
- instance.
+ """Helper function for clients to pick up remote storage configuration from env.
+
+ Initialise the file storage for the same and return the instance.
Args:
storage_type: Permanent / Temporary file storage
diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/helper.py b/unstract/sdk1/src/unstract/sdk1/file_storage/helper.py
index 4be3c58c2..17e614b00 100644
--- a/unstract/sdk1/src/unstract/sdk1/file_storage/helper.py
+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/helper.py
@@ -67,9 +67,10 @@ class FileStorageHelper:
raise FileStorageError(str(e)) from e
-def skip_local_cache(func):
- """Helper function/decorator for handling FileNotFound exception and making
- sure that the error is not because of stale cache.
+def skip_local_cache(func: object) -> object:
+ """Helper function/decorator for handling FileNotFound exception.
+
+ Making sure that the error is not because of stale cache.
Args:
func: The original function that is called in the context
@@ -78,7 +79,7 @@ def skip_local_cache(func):
NA
"""
- def wrapper(*args, **kwargs):
+ def wrapper(*args: object, **kwargs: object) -> object:
try:
return func(*args, **kwargs)
except FileNotFoundError:
@@ -89,9 +90,10 @@ def skip_local_cache(func):
return wrapper
-def _handle_file_not_found(func, *args, **kwargs):
- """Helper function for handling FileNotFound exception and making sure that
- the error is not because of stale cache.
+def _handle_file_not_found(func: object, *args: object, **kwargs: object) -> object:
+ """Helper function for handling FileNotFound exception.
+
+ Making sure that the error is not because of stale cache.
Args:
func: The original function that is called in the context
diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/impl.py b/unstract/sdk1/src/unstract/sdk1/file_storage/impl.py
index 8e249530e..9666c8652 100644
--- a/unstract/sdk1/src/unstract/sdk1/file_storage/impl.py
+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/impl.py
@@ -2,7 +2,6 @@ import json
import logging
from datetime import datetime
from hashlib import sha256
-from typing import Any
import filetype
import fsspec
@@ -23,7 +22,15 @@ class FileStorage(FileStorageInterface):
fs: fsspec # fsspec file system handle
provider: FileStorageProvider
- def __init__(self, provider: FileStorageProvider, **storage_config: dict[str, Any]):
+ def __init__(
+ self, provider: FileStorageProvider, **storage_config: dict[str, object]
+ ) -> None:
+ """Initialize the FileStorage implementation.
+
+ Args:
+ provider: File storage provider type (e.g., LOCAL, S3, etc.)
+ **storage_config: Additional configuration parameters for the storage provider
+ """
self.fs = FileStorageHelper.file_storage_init(provider, **storage_config)
self.provider = provider
@@ -89,8 +96,10 @@ class FileStorage(FileStorageInterface):
location: int = 0,
position: FileSeekPosition = FileSeekPosition.START,
) -> int:
- """Place the file pointer to the mentioned location in the file
- relative to the position.
+ """Place file pointer at the specified location relative to position.
+
+ Place the file pointer to the mentioned location in the file relative to the
+ position.
Args:
path (str): path of the file
@@ -105,7 +114,7 @@ class FileStorage(FileStorageInterface):
with self.fs.open(path=path, mode="rb") as file_handle:
return file_handle.seek(location, position)
- def mkdir(self, path: str, create_parents: bool = True):
+ def mkdir(self, path: str, create_parents: bool = True) -> None:
"""Create a directory.
Args:
@@ -148,7 +157,7 @@ class FileStorage(FileStorageInterface):
return self.fs.ls(path)
@skip_local_cache
- def rm(self, path: str, recursive: bool = True):
+ def rm(self, path: str, recursive: bool = True) -> None:
"""Removes a file or directory mentioned in path.
Args:
@@ -168,7 +177,7 @@ class FileStorage(FileStorageInterface):
dest: str,
recursive: bool = False,
overwrite: bool = True,
- ):
+ ) -> None:
"""Copies files from source(lpath) path to the destination(rpath) path.
Args:
@@ -229,8 +238,9 @@ class FileStorage(FileStorageInterface):
path: str,
read_length: int = FileOperationParams.READ_ENTIRE_LENGTH,
) -> str:
- """Gets the file MIME type for an input file. Uses libmagic to perform
- the same.
+ """Gets the file MIME type for an input file.
+
+ Uses libmagic to perform the same.
Args:
path (str): Path of the input file
@@ -245,10 +255,11 @@ class FileStorage(FileStorageInterface):
return mime_type
@skip_local_cache
- def download(self, from_path: str, to_path: str):
- """Downloads the file mentioned in from_path to to_path on the local
- system. The instance calling the method needs to be the FileStorage
- initialised with the remote file system.
+ def download(self, from_path: str, to_path: str) -> None:
+ """Downloads the file mentioned in from_path to to_path on the local system.
+
+ The instance calling the method needs to be the FileStorage initialised with
+ the remote file system.
Args:
from_path (str): Path of the file to be downloaded (remote)
@@ -261,11 +272,12 @@ class FileStorage(FileStorageInterface):
self.fs.get(rpath=from_path, lpath=to_path)
@skip_local_cache
- def upload(self, from_path: str, to_path: str):
- """Uploads the file mentioned in from_path (local system) to to_path
- (remote system). The instance calling the method needs to be the
- FileStorage initialised with the remote file system where the file
- needs to be uploaded.
+ def upload(self, from_path: str, to_path: str) -> None:
+ """Upload file from local system to remote system.
+
+ Uploads the file mentioned in from_path (local system) to to_path (remote
+ system). The instance calling the method needs to be the FileStorage
+ initialised with the remote file system where the file needs to be uploaded.
Args:
from_path (str): Path of the file to be uploaded (local)
@@ -277,8 +289,10 @@ class FileStorage(FileStorageInterface):
self.fs.put(from_path, to_path)
def glob(self, path: str) -> list[str]:
- """Lists files under path matching the pattern sepcified as part of
- path in the argument.
+ """List files matching pattern in path.
+
+ Lists files under path matching the pattern sepcified as part of path in the
+ argument.
Args:
path (str): path to the directory where files matching the
@@ -316,9 +330,9 @@ class FileStorage(FileStorageInterface):
def json_dump(
self,
path: str,
- data: dict[str, Any],
- **kwargs: dict[Any, Any], # type: ignore
- ):
+ data: dict[str, object],
+ **kwargs: dict[object, object], # type: ignore
+ ) -> None:
"""Dumps data into the given file specified by path.
Args:
@@ -335,9 +349,9 @@ class FileStorage(FileStorageInterface):
def yaml_dump(
self,
path: str,
- data: dict[str, Any],
- **kwargs: dict[Any, Any], # type: ignore
- ):
+ data: dict[str, object],
+ **kwargs: dict[object, object], # type: ignore
+ ) -> None:
"""Dumps data into the given file specified by path.
Args:
@@ -352,16 +366,16 @@ class FileStorage(FileStorageInterface):
raise FileOperationError(str(e)) from e
@skip_local_cache
- def json_load(self, path: str) -> dict[Any, Any]:
+ def json_load(self, path: str) -> dict[object, object]:
with self.fs.open(path=path) as json_file:
- data: dict[str, Any] = json.load(json_file)
+ data: dict[str, object] = json.load(json_file)
return data
@skip_local_cache
def yaml_load(
self,
path: str,
- ) -> dict[Any, Any]:
+ ) -> dict[object, object]:
"""Loads data from a file as yaml.
Args:
@@ -371,7 +385,7 @@ class FileStorage(FileStorageInterface):
dict[Any, Any]: Data loaded as yaml
"""
with self.fs.open(path=path) as f:
- data: dict[str, Any] = yaml.safe_load(f)
+ data: dict[str, object] = yaml.safe_load(f)
return data
def guess_extension(self, path: str) -> str:
@@ -394,7 +408,9 @@ class FileStorage(FileStorageInterface):
file_extension = file_type.EXTENSION
return file_extension
- def walk(self, path: str, max_depth=None, topdown=True):
+ def walk(
+ self, path: str, max_depth: int | None = None, topdown: bool = True
+ ) -> object:
"""Walks the dir in the path and returns the list of files/dirs.
Args:
diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/interface.py b/unstract/sdk1/src/unstract/sdk1/file_storage/interface.py
index 00f6e0c32..d053f149f 100644
--- a/unstract/sdk1/src/unstract/sdk1/file_storage/interface.py
+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/interface.py
@@ -39,7 +39,7 @@ class FileStorageInterface(ABC):
pass
@abstractmethod
- def mkdir(self, path: str, create_parents: bool):
+ def mkdir(self, path: str, create_parents: bool) -> None:
pass
@abstractmethod
@@ -51,7 +51,7 @@ class FileStorageInterface(ABC):
pass
@abstractmethod
- def rm(self, path: str, recursive: bool = True):
+ def rm(self, path: str, recursive: bool = True) -> None:
pass
@abstractmethod
@@ -61,7 +61,7 @@ class FileStorageInterface(ABC):
rpath: str,
recursive: bool = False,
overwrite: bool = True,
- ):
+ ) -> None:
pass
@abstractmethod
@@ -81,7 +81,7 @@ class FileStorageInterface(ABC):
pass
@abstractmethod
- def download(self, from_path: str, to_path: str):
+ def download(self, from_path: str, to_path: str) -> None:
pass
@abstractmethod
@@ -98,7 +98,7 @@ class FileStorageInterface(ABC):
path: str,
data: dict[str, Any],
**kwargs: dict[Any, Any],
- ):
+ ) -> None:
pass
@abstractmethod
@@ -107,7 +107,7 @@ class FileStorageInterface(ABC):
path: str,
data: dict[str, Any],
**kwargs: dict[Any, Any],
- ):
+ ) -> None:
pass
@abstractmethod
@@ -126,5 +126,5 @@ class FileStorageInterface(ABC):
pass
@abstractmethod
- def walk(self, path: str):
+ def walk(self, path: str) -> object:
pass
diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/permanent.py b/unstract/sdk1/src/unstract/sdk1/file_storage/permanent.py
index 9d12c4bca..a21fe5431 100644
--- a/unstract/sdk1/src/unstract/sdk1/file_storage/permanent.py
+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/permanent.py
@@ -24,7 +24,14 @@ class PermanentFileStorage(FileStorage):
self,
provider: FileStorageProvider,
**storage_config: dict[str, Any],
- ):
+ ) -> None:
+ """Initialize the PermanentFileStorage with validation.
+
+ Args:
+ provider: File storage provider type that must be supported for permanent
+ storage
+ **storage_config: Additional configuration parameters for the storage provider
+ """
if provider.value not in self.SUPPORTED_FILE_STORAGE_TYPES:
raise FileStorageError(
f"File storage provider `{provider.value}` is not "
@@ -42,8 +49,9 @@ class PermanentFileStorage(FileStorage):
else:
raise NotImplementedError(f"Provider {provider.value} is not implemented")
- def _copy_on_read(self, path: str, legacy_storage_path: str):
+ def _copy_on_read(self, path: str, legacy_storage_path: str) -> None:
"""Copies the file to the remote storage lazily if not present already.
+
Checks if the file is present in the Local File system. If yes, copies
the file to the mentioned path using the remote file system. This is a
silent copy done on need basis.
@@ -109,8 +117,9 @@ class PermanentFileStorage(FileStorage):
read_length: int = FileOperationParams.READ_ENTIRE_LENGTH,
legacy_storage_path: str | None = None,
) -> str:
- """Gets the file MIME type for an input file. Uses libmagic to perform
- the same.
+ """Gets the file MIME type for an input file.
+
+ Uses libmagic to perform the same.
Args:
path (str): Path of the input file
diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/shared_temporary.py b/unstract/sdk1/src/unstract/sdk1/file_storage/shared_temporary.py
index ad1630d27..0cd7fb265 100644
--- a/unstract/sdk1/src/unstract/sdk1/file_storage/shared_temporary.py
+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/shared_temporary.py
@@ -14,7 +14,14 @@ class SharedTemporaryFileStorage(FileStorage):
self,
provider: FileStorageProvider,
**storage_config: dict[str, Any],
- ):
+ ) -> None:
+ """Initialize the SharedTemporaryFileStorage with validation.
+
+ Args:
+ provider: File storage provider type that must be supported for shared
+ temporary storage
+ **storage_config: Additional configuration parameters for the storage provider
+ """
if provider.value not in self.SUPPORTED_FILE_STORAGE_TYPES:
raise FileStorageError(
f"File storage provider is not supported in Shared Temporary mode. "
diff --git a/unstract/sdk1/src/unstract/sdk1/index.py b/unstract/sdk1/src/unstract/sdk1/index.py
index 2bd9f07e8..ed4867963 100644
--- a/unstract/sdk1/src/unstract/sdk1/index.py
+++ b/unstract/sdk1/src/unstract/sdk1/index.py
@@ -1,7 +1,8 @@
+from __future__ import annotations
+
import json
import logging
-from collections.abc import Callable
-from typing import Any
+from typing import TYPE_CHECKING, Any
from llama_index.core import Document
from llama_index.core.node_parser import SentenceSplitter
@@ -17,19 +18,22 @@ from unstract.sdk1.adapters.vectordb.no_op.src.no_op_custom_vectordb import (
NoOpCustomVectorDB,
)
from unstract.sdk1.adapters.x2text.constants import X2TextConstants
-from unstract.sdk1.adapters.x2text.dto import TextExtractionResult
from unstract.sdk1.adapters.x2text.llm_whisperer_v2.src import LLMWhispererV2
from unstract.sdk1.constants import LogLevel
from unstract.sdk1.embedding import EmbeddingCompat
from unstract.sdk1.exceptions import IndexingError, SdkError, VectorDBError, X2TextError
from unstract.sdk1.file_storage import FileStorage, FileStorageProvider
from unstract.sdk1.platform import PlatformHelper
-from unstract.sdk1.tool.base import BaseTool
from unstract.sdk1.utils.common import capture_metrics, log_elapsed
from unstract.sdk1.utils.tool import ToolUtils
from unstract.sdk1.vector_db import VectorDB
from unstract.sdk1.x2txt import X2Text
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from unstract.sdk1.tool.base import BaseTool
+
logger = logging.getLogger(__name__)
@@ -43,7 +47,14 @@ class Index:
tool: BaseTool,
run_id: str | None = None,
capture_metrics: bool = False,
- ):
+ ) -> None:
+ """Initialize the Index for document indexing and querying operations.
+
+ Args:
+ tool: BaseTool instance for accessing tool-specific operations
+ run_id: Optional run identifier for tracking operations
+ capture_metrics: Whether to capture performance metrics during operations
+ """
# TODO: Inherit from StreamMixin and avoid using BaseTool
self.tool = tool
self._run_id = run_id
@@ -56,8 +67,10 @@ class Index:
embedding_instance_id: str,
vector_db_instance_id: str,
doc_id: str,
- usage_kwargs: dict[Any, Any] = {},
- ):
+ usage_kwargs: dict[object, object] = None,
+ ) -> object:
+ if usage_kwargs is None:
+ usage_kwargs = {}
embedding = EmbeddingCompat(
tool=self.tool,
adapter_instance_id=embedding_instance_id,
@@ -95,7 +108,7 @@ class Index:
)
raise VectorDBError(
f"Failed to construct query for {vector_db}: {e}", actual_err=e
- )
+ ) from e
try:
n: VectorStoreQueryResult = vector_db.query(query=q)
if len(n.nodes) > 0:
@@ -113,7 +126,7 @@ class Index:
)
raise VectorDBError(
f"Failed to execute query on {vector_db}: {e}", actual_err=e
- )
+ ) from e
finally:
vector_db.close()
@@ -124,9 +137,9 @@ class Index:
file_path: str,
output_file_path: str | None = None,
enable_highlight: bool = False,
- usage_kwargs: dict[Any, Any] = {},
+ usage_kwargs: dict[Any, Any] = None,
process_text: Callable[[str], str] | None = None,
- fs: FileStorage = FileStorage(FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
tags: list[str] | None = None,
) -> str:
"""Extracts text from a document.
@@ -152,6 +165,10 @@ class Index:
Raises:
IndexingError: Errors during text extraction
"""
+ if usage_kwargs is None:
+ usage_kwargs = {}
+ if fs is None:
+ fs = FileStorage(FileStorageProvider.LOCAL)
self.tool.stream_log("Extracting text from input file")
extracted_text = ""
x2text = X2Text(
@@ -161,7 +178,7 @@ class Index:
)
try:
if enable_highlight and isinstance(x2text.x2text_instance, LLMWhispererV2):
- process_response: TextExtractionResult = x2text.process(
+ process_response = x2text.process(
input_file_path=file_path,
output_file_path=output_file_path,
enable_highlight=enable_highlight,
@@ -173,7 +190,7 @@ class Index:
if hasattr(self.tool, "update_exec_metadata"):
self.tool.update_exec_metadata(metadata)
else:
- process_response: TextExtractionResult = x2text.process(
+ process_response = x2text.process(
input_file_path=file_path,
output_file_path=output_file_path,
tags=tags,
@@ -216,9 +233,9 @@ class Index:
file_hash: str | None = None,
output_file_path: str | None = None,
enable_highlight: bool = False,
- usage_kwargs: dict[Any, Any] = {},
+ usage_kwargs: dict[Any, Any] = None,
process_text: Callable[[str], str] | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
tags: list[str] | None = None,
) -> str:
"""Indexes an individual file using the passed arguments.
@@ -246,6 +263,10 @@ class Index:
Returns:
str: A unique ID for the file and indexing arguments combination
"""
+ if usage_kwargs is None:
+ usage_kwargs = {}
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
doc_id = self.generate_index_key(
vector_db=vector_db_instance_id,
embedding=embedding_instance_id,
@@ -363,7 +384,7 @@ class Index:
text_to_idx: str,
doc_id: str,
doc_id_found: bool,
- ):
+ ) -> None:
self.tool.stream_log("Indexing file...")
full_text = [
{
@@ -445,7 +466,7 @@ class Index:
chunk_overlap: str,
file_path: str | None = None,
file_hash: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> str:
"""Generates a unique ID useful for identifying files during indexing.
@@ -464,6 +485,8 @@ class Index:
Returns:
str: Key representing unique ID for a file
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
if not file_path and not file_hash:
raise ValueError("One of `file_path` or `file_hash` need to be provided")
@@ -488,8 +511,8 @@ class Index:
hashed_index_key = ToolUtils.hash_str(json.dumps(index_key, sort_keys=True))
return hashed_index_key
- def get_metrics(self):
+ def get_metrics(self) -> dict[str, Any]:
return self._metrics
- def clear_metrics(self):
+ def clear_metrics(self) -> None:
self._metrics = {}
diff --git a/unstract/sdk1/src/unstract/sdk1/llm.py b/unstract/sdk1/src/unstract/sdk1/llm.py
index a0301c656..2d64ad338 100644
--- a/unstract/sdk1/src/unstract/sdk1/llm.py
+++ b/unstract/sdk1/src/unstract/sdk1/llm.py
@@ -1,8 +1,8 @@
import logging
import os
import re
-from collections.abc import Callable, Generator
-from typing import Any, cast
+from collections.abc import Callable, Generator, Mapping
+from typing import cast
import litellm
@@ -29,6 +29,7 @@ logger = logging.getLogger(__name__)
class LLM:
"""Unified LLM interface powered by LiteLLM.
+
Internally invokes Unstract LLM adapters.
Accepts either of the following pairs for init:
@@ -41,17 +42,35 @@ class LLM:
JSON_REGEX = re.compile(r"\[(?:.|\n)*\]|\{(?:.|\n)*\}")
JSON_CONTENT_MARKER = os.environ.get("JSON_SELECTION_MARKER", "§§§")
- def __init__(
+ def __init__( # noqa: C901
self,
adapter_id: str = "",
- adapter_metadata: dict[str, Any] = {},
+ adapter_metadata: dict[str, object] | None = None,
adapter_instance_id: str = "",
- tool: BaseTool = None,
- usage_kwargs: dict[str, Any] = {},
+ tool: BaseTool | None = None,
+ usage_kwargs: dict[str, object] | None = None,
system_prompt: str = "",
- kwargs: dict[str, Any] = {},
+ kwargs: dict[str, object] | None = None,
capture_metrics: bool = False,
) -> None:
+ """Initialize the LLM interface.
+
+ Args:
+ adapter_id: Adapter identifier for LLM model
+ adapter_metadata: Configuration metadata for the adapter
+ adapter_instance_id: Instance identifier for the adapter
+ tool: BaseTool instance for tool-specific operations
+ usage_kwargs: Usage tracking parameters
+ system_prompt: System prompt for the LLM
+ kwargs: Additional keyword arguments for configuration
+ capture_metrics: Whether to capture performance metrics
+ """
+ if adapter_metadata is None:
+ adapter_metadata = {}
+ if usage_kwargs is None:
+ usage_kwargs = {}
+ if kwargs is None:
+ kwargs = {}
self._usage_kwargs = usage_kwargs
self._capture_metrics = capture_metrics
try:
@@ -80,10 +99,10 @@ class LLM:
# Retrieve the adapter class.
self.adapter = adapters[self._adapter_id][Common.MODULE]
- except KeyError:
+ except KeyError as e:
raise SdkError(
- "LLM adapter not supported: " + adapter_id or adapter_instance_id
- )
+ f"LLM adapter not supported: {adapter_id or adapter_instance_id}"
+ ) from e
try:
self.platform_kwargs = {**kwargs, **usage_kwargs}
@@ -94,12 +113,14 @@ class LLM:
self.kwargs = self.adapter.validate(self._adapter_metadata)
# REF: https://docs.litellm.ai/docs/completion/input#translated-openai-params
- # supported = get_supported_openai_params(model=self.kwargs["model"], custom_llm_provider=self.provider)
+ # supported = get_supported_openai_params(model=self.kwargs["model"],
+ # custom_llm_provider=self.provider)
# for s in supported:
# if s not in self.kwargs:
- # logger.warning("Missing supported parameter for '%s': %s", self.adapter.get_provider(), s)
+ # logger.warning("Missing supported parameter for '%s': %s",
+ # self.adapter.get_provider(), s)
except ValidationError as e:
- raise SdkError("Invalid LLM adapter metadata: " + str(e))
+ raise SdkError("Invalid LLM adapter metadata: " + str(e)) from e
self._system_prompt = system_prompt or self.SYSTEM_PROMPT
@@ -113,7 +134,7 @@ class LLM:
# Metrics capture.
self._run_id = self.platform_kwargs.get("run_id")
self._capture_metrics = self.platform_kwargs.get("capture_metrics")
- self._metrics: dict[str, Any] = {}
+ self._metrics: dict[str, object] = {}
def test_connection(self) -> bool:
"""Test connection to the LLM provider."""
@@ -137,9 +158,11 @@ class LLM:
raise e
@capture_metrics
- def complete(self, prompt: str, **kwargs: dict[str, Any]) -> dict[str, Any]:
- """Return a standard chat completion dict and optionally captures metrics
- if run ID is provided.
+ def complete(self, prompt: str, **kwargs: object) -> dict[str, object]:
+ """Return a standard chat completion dict with optional metrics capture.
+
+ Return a standard chat completion dict and optionally captures metrics if run
+ ID is provided.
Args:
prompt (str) The input text prompt for generating the completion.
@@ -164,7 +187,7 @@ class LLM:
# if hasattr(self, "thinking_dict") and self.thinking_dict is not None:
# completion_kwargs["temperature"] = 1
- response: dict[str, Any] = litellm.completion(
+ response: dict[str, object] = litellm.completion(
messages=messages,
**completion_kwargs,
)
@@ -179,9 +202,9 @@ class LLM:
# The typecasting was required to stop the type checker from complaining.
# Improvements in readability are definitely welcome.
extract_json: bool = cast("bool", kwargs.get("extract_json", False))
- post_process_fn: Callable[[LLMResponseCompat, bool], dict[str, Any]] | None = (
+ post_process_fn: Callable[[LLMResponseCompat, bool], dict[str, object]] | None = (
cast(
- "Callable[[LLMResponseCompat, bool], dict[str, Any]] | None",
+ "Callable[[LLMResponseCompat, bool], dict[str, object]] | None",
kwargs.get("process_text", None),
)
)
@@ -196,8 +219,8 @@ class LLM:
def stream_complete(
self,
prompt: str,
- callback_manager: Any | None = None,
- **kwargs: Any,
+ callback_manager: object | None = None,
+ **kwargs: object,
) -> Generator[str, None, None]:
"""Yield chunks of text as they arrive from the provider."""
messages = [
@@ -230,7 +253,7 @@ class LLM:
yield text
- async def acomplete(self, prompt: str, **kwargs: Any) -> dict[str, Any]:
+ async def acomplete(self, prompt: str, **kwargs: object) -> dict[str, object]:
"""Asynchronous chat completion (wrapper around ``litellm.acompletion``)."""
messages = [
{"role": "system", "content": self._system_prompt},
@@ -257,7 +280,7 @@ class LLM:
@classmethod
def get_context_window_size(
- cls, adapter_id: str, adapter_metadata: dict[str, Any]
+ cls, adapter_id: str, adapter_metadata: dict[str, object]
) -> int:
"""Returns the context window size of the LLM."""
try:
@@ -294,20 +317,25 @@ class LLM:
"""
return self.kwargs["model"]
- def get_metrics(self):
+ def get_metrics(self) -> dict[str, object]:
return self._metrics
- def get_usage_reason(self):
+ def get_usage_reason(self) -> object:
return self.platform_kwargs.get("llm_usage_reason")
def _record_usage(
- self, model: str, messages: list[dict[str, str]], usage: Any, llm_api: str
- ):
+ self,
+ model: str,
+ messages: list[dict[str, str]],
+ usage: Mapping[str, int] | None,
+ llm_api: str,
+ ) -> None:
prompt_tokens = token_counter(model=model, messages=messages)
+ usage_data: Mapping[str, int] = usage or {}
all_tokens = TokenCounterCompat(
- prompt_tokens=usage.get("prompt_tokens", 0),
- completion_tokens=usage.get("completion_tokens", 0),
- total_tokens=usage.get("total_tokens", 0),
+ prompt_tokens=usage_data.get("prompt_tokens", 0),
+ completion_tokens=usage_data.get("completion_tokens", 0),
+ total_tokens=usage_data.get("total_tokens", 0),
)
logger.info(f"[sdk1][LLM][{model}][{llm_api}] Prompt Tokens: {prompt_tokens}")
@@ -325,9 +353,9 @@ class LLM:
self,
response_text: str,
extract_json: bool,
- post_process_fn: Callable[[LLMResponseCompat, bool], dict[str, Any]] | None,
- ) -> tuple[str, dict[str, Any]]:
- post_processed_output: dict[str, Any] = {}
+ post_process_fn: Callable[[LLMResponseCompat, bool], dict[str, object]] | None,
+ ) -> tuple[str, dict[str, object]]:
+ post_processed_output: dict[str, object] = {}
if extract_json:
start = response_text.find(LLM.JSON_CONTENT_MARKER)
diff --git a/unstract/sdk1/src/unstract/sdk1/platform.py b/unstract/sdk1/src/unstract/sdk1/platform.py
index 58ee3f563..d51f87bb3 100644
--- a/unstract/sdk1/src/unstract/sdk1/platform.py
+++ b/unstract/sdk1/src/unstract/sdk1/platform.py
@@ -3,7 +3,7 @@ import logging
from typing import Any
import requests
-from requests import ConnectionError, RequestException, Response
+from requests import RequestException, Response
from requests.exceptions import ConnectionError, HTTPError
from unstract.sdk1.constants import (
AdapterKeys,
@@ -96,9 +96,9 @@ class PlatformHelper:
tool: BaseTool,
adapter_instance_id: str,
) -> dict[str, Any]:
- """Get Adapter
- 1. Get the adapter config from platform service
- using the adapter_instance_id
+ """Get adapter configuration from platform service.
+
+ 1. Get the adapter config from platform service using the adapter_instance_id.
Args:
adapter_instance_id (str): Adapter instance ID
@@ -130,10 +130,10 @@ class PlatformHelper:
f"'{adapter_type}', provider: '{provider}', name: '{adapter_name}'",
level=LogLevel.DEBUG,
)
- except ConnectionError:
+ except ConnectionError as e:
raise SdkError(
"Unable to connect to platform service, please contact the admin."
- )
+ ) from e
except HTTPError as e:
default_err = (
"Error while calling the platform service, please contact the admin."
@@ -141,7 +141,7 @@ class PlatformHelper:
msg = Utils.get_msg_from_request_exc(
err=e, message_key="error", default_err=default_err
)
- raise SdkError(f"Error retrieving adapter. {msg}")
+ raise SdkError(f"Error retrieving adapter. {msg}") from e
return adapter_data
@classmethod
diff --git a/unstract/sdk1/src/unstract/sdk1/tool/base.py b/unstract/sdk1/src/unstract/sdk1/tool/base.py
index 2e07f954f..90b115b2a 100644
--- a/unstract/sdk1/src/unstract/sdk1/tool/base.py
+++ b/unstract/sdk1/src/unstract/sdk1/tool/base.py
@@ -137,8 +137,7 @@ class BaseTool(ABC, StreamMixin):
return str(file_path)
def get_source_file(self) -> str:
- """Gets the absolute path to the workflow execution's input file
- (SOURCE).
+ """Gets the absolute path to the workflow execution's input file (SOURCE).
Returns:
str: Absolute path to the source file
@@ -146,8 +145,10 @@ class BaseTool(ABC, StreamMixin):
return self._get_file_from_data_dir(ToolExecKey.SOURCE, raise_err=True)
def get_input_file(self) -> str:
- """Gets the absolute path to the input file that's meant for the tool
- being run (INFILE).
+ """Get absolute path to the input file for the tool (INFILE).
+
+ Gets the absolute path to the input file that's meant for the tool being run
+ (INFILE).
Returns:
str: Absolute path to the input file
@@ -155,9 +156,11 @@ class BaseTool(ABC, StreamMixin):
return self._get_file_from_data_dir(ToolExecKey.INFILE, raise_err=True)
def get_output_dir(self) -> str:
- """Get the absolute path to the output folder where the tool needs to
- place its output file. This is where the tool writes its output files
- that need to be copied into the destination (COPY_TO_FOLDER path).
+ """Get absolute path to the output folder for tool output files.
+
+ Get the absolute path to the output folder where the tool needs to place its
+ output file. This is where the tool writes its output files that need to be
+ copied into the destination (COPY_TO_FOLDER path).
Returns:
str: Absolute path to the output directory.
@@ -175,8 +178,9 @@ class BaseTool(ABC, StreamMixin):
return self._exec_metadata
def _get_exec_metadata(self) -> dict[str, Any]:
- """Retrieve the contents from METADATA.json present in the data
- directory. This file contains metadata for the tool execution.
+ """Retrieve the contents from METADATA.json present in the data directory.
+
+ This file contains metadata for the tool execution.
Returns:
dict[str, Any]: Contents of METADATA.json
@@ -234,8 +238,7 @@ class BaseTool(ABC, StreamMixin):
self._write_exec_metadata(metadata=self._exec_metadata)
def update_exec_metadata(self, metadata: dict[str, Any]) -> None:
- """Helps update the execution metadata with the provided metadata
- dictionary.
+ """Helps update the execution metadata with the provided metadata dictionary.
This method iterates over the key-value pairs in the input metadata dictionary
and updates the internal `_exec_metadata` dictionary of the tool instance
diff --git a/unstract/sdk1/src/unstract/sdk1/tool/cache.py b/unstract/sdk1/src/unstract/sdk1/tool/cache.py
index 50fe6186b..159f905c5 100644
--- a/unstract/sdk1/src/unstract/sdk1/tool/cache.py
+++ b/unstract/sdk1/src/unstract/sdk1/tool/cache.py
@@ -1,5 +1,3 @@
-from typing import Any
-
import requests
from unstract.sdk1.constants import LogLevel
from unstract.sdk1.platform import PlatformHelper
@@ -14,7 +12,9 @@ class ToolCache(PlatformHelper):
"""
def __init__(self, tool: BaseTool, platform_host: str, platform_port: int) -> None:
- """Args:
+ """Initialize the ToolCache for tool-specific caching operations.
+
+ Args:
tool (AbstractTool): Instance of AbstractTool
platform_host (str): The host of the platform.
platform_port (int): The port of the platform.
@@ -53,7 +53,7 @@ class ToolCache(PlatformHelper):
)
return False
- def get(self, key: str) -> Any | None:
+ def get(self, key: str) -> str | None:
"""Gets the value for a key in the cache.
Args:
diff --git a/unstract/sdk1/src/unstract/sdk1/tool/mixin.py b/unstract/sdk1/src/unstract/sdk1/tool/mixin.py
index f42b25838..1ad8fd4f9 100644
--- a/unstract/sdk1/src/unstract/sdk1/tool/mixin.py
+++ b/unstract/sdk1/src/unstract/sdk1/tool/mixin.py
@@ -13,7 +13,7 @@ class ToolConfigHelper:
@staticmethod
def spec(
spec_file: str = "config/spec.json",
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> dict[str, Any]:
"""Returns the JSON schema for the tool settings.
@@ -24,12 +24,14 @@ class ToolConfigHelper:
Returns:
str: The JSON schema of the tool.
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
return ToolUtils.load_json(spec_file, fs=fs)
@staticmethod
def properties(
properties_file: str = "config/properties.json",
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> dict[str, Any]:
"""Returns the properties of the tool.
@@ -40,12 +42,14 @@ class ToolConfigHelper:
Returns:
str: The properties of the tool.
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
return ToolUtils.load_json(properties_file, fs)
@staticmethod
def variables(
variables_file: str = "config/runtime_variables.json",
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> dict[str, Any]:
"""Returns the JSON schema of the runtime variables.
@@ -56,6 +60,8 @@ class ToolConfigHelper:
Returns:
str: The JSON schema for the runtime variables.
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
try:
return ToolUtils.load_json(variables_file, fs)
# Allow runtime variables definition to be optional
@@ -66,7 +72,7 @@ class ToolConfigHelper:
@staticmethod
def icon(
icon_file: str = "config/icon.svg",
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> str:
"""Returns the icon of the tool.
@@ -77,5 +83,7 @@ class ToolConfigHelper:
Returns:
str: The icon of the tool.
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
icon = fs.read(path=icon_file, mode="rb", encoding="utf-8")
return icon
diff --git a/unstract/sdk1/src/unstract/sdk1/tool/validator.py b/unstract/sdk1/src/unstract/sdk1/tool/validator.py
index 43d225e07..30d6ae475 100644
--- a/unstract/sdk1/src/unstract/sdk1/tool/validator.py
+++ b/unstract/sdk1/src/unstract/sdk1/tool/validator.py
@@ -1,7 +1,6 @@
import re
from json import JSONDecodeError
from pathlib import Path
-from typing import Any
from jsonschema import Draft202012Validator, ValidationError, validators
from unstract.sdk1.constants import MetadataKey, PropKey
@@ -10,7 +9,7 @@ from unstract.sdk1.tool.mime_types import EXT_MIME_MAP
from unstract.sdk1.utils.common import Utils
-def extend_with_default(validator_class: Any) -> Any:
+def extend_with_default(validator_class: object) -> object:
"""Extend a JSON schema validator class with a default value functionality.
Parameters:
@@ -24,7 +23,9 @@ def extend_with_default(validator_class: Any) -> Any:
"""
validate_properties = validator_class.VALIDATORS["properties"]
- def set_defaults(validator: Any, properties: Any, instance: Any, schema: Any) -> Any:
+ def set_defaults(
+ validator: object, properties: object, instance: object, schema: object
+ ) -> object:
for property_, subschema in properties.items():
if "default" in subschema:
instance.setdefault(property_, subschema["default"])
@@ -47,16 +48,19 @@ DefaultsGeneratingValidator = extend_with_default(Draft202012Validator)
class ToolValidator:
- """Class to validate a tool and its configuration before its executed with
- an input.
- """
+ """Class to validate a tool and its configuration before its executed."""
def __init__(self, tool: BaseTool) -> None:
+ """Initialize the ToolValidator for validating tool configuration and execution.
+
+ Args:
+ tool: BaseTool instance to validate
+ """
self.tool = tool
props = self.tool.properties
self.restrictions = props.get(PropKey.RESTRICTIONS)
- def validate_pre_execution(self, settings: dict[str, Any]) -> dict[str, Any]:
+ def validate_pre_execution(self, settings: dict[str, object]) -> dict[str, object]:
"""Performs validation before the tool executes on the input file.
Args:
@@ -85,7 +89,9 @@ class ToolValidator:
self._validate_file_size(input_file)
self._validate_file_type(input_file)
- def _validate_settings_and_fill_defaults(self, tool_settings: dict[str, Any]) -> None:
+ def _validate_settings_and_fill_defaults(
+ self, tool_settings: dict[str, object]
+ ) -> None:
"""Validates and obtains settings for a tool.
Validation is done against the tool's settings based
@@ -103,8 +109,7 @@ class ToolValidator:
self.tool.stream_error_and_exit(f"Invalid settings: {str(e)}")
def _validate_file_size(self, input_file: Path) -> None:
- """Validates the input file size against the max allowed size set in
- the tool's PROPERTIES.
+ """Validates input file size against the max allowed size in tool's PROPERTIES.
Raises:
RuntimeError: File size exceeds max allowed size
@@ -154,8 +159,7 @@ class ToolValidator:
return size_in_bytes
def _validate_file_type(self, input_file: Path) -> None:
- """Validate the input file type against the allowed types mentioned in
- tool's PROPERTIES.
+ """Validate input file type against allowed types in tool's PROPERTIES.
Args:
input_file (Path): Path obj of input file to validate
diff --git a/unstract/sdk1/src/unstract/sdk1/usage_handler.py b/unstract/sdk1/src/unstract/sdk1/usage_handler.py
index dbbea842b..0ffa7c43e 100644
--- a/unstract/sdk1/src/unstract/sdk1/usage_handler.py
+++ b/unstract/sdk1/src/unstract/sdk1/usage_handler.py
@@ -9,10 +9,11 @@ from unstract.sdk1.tool.stream import StreamMixin
class UsageHandler(StreamMixin, BaseCallbackHandler):
- """UsageHandler class is a subclass of BaseCallbackHandler and is
- responsible for handling usage events in the LLM or Embedding models. It
- provides methods for starting and ending traces, as well as handling event
- starts and ends.
+ """Handler for usage events in LLM or Embedding models.
+
+ UsageHandler class is a subclass of BaseCallbackHandler and is responsible for
+ handling usage events in the LLM or Embedding models. It provides methods for
+ starting and ending traces, as well as handling event starts and ends.
Attributes:
- token_counter (TokenCountingHandler): The token counter object used
@@ -36,8 +37,22 @@ class UsageHandler(StreamMixin, BaseCallbackHandler):
event_ends_to_ignore: list[CBEventType] | None = None,
verbose: bool = False,
log_level: LogLevel = LogLevel.INFO,
- kwargs: dict[Any, Any] = {},
+ kwargs: dict[Any, Any] = None,
) -> None:
+ """Initialize the UsageHandler for tracking usage events in LLM/Embedding models.
+
+ Args:
+ platform_api_key: API key for platform service communication
+ token_counter: Token counting handler for tracking token usage
+ embed_model: Embedding model instance for embedding operations
+ event_starts_to_ignore: List of event types to ignore at start
+ event_ends_to_ignore: List of event types to ignore at end
+ verbose: Whether to enable verbose output
+ log_level: Logging level for output
+ kwargs: Additional keyword arguments for usage tracking
+ """
+ if kwargs is None:
+ kwargs = {}
self.kwargs = kwargs.copy()
self._verbose = verbose
self.token_counter = token_counter
@@ -65,8 +80,10 @@ class UsageHandler(StreamMixin, BaseCallbackHandler):
payload: dict[str, Any] | None = None,
event_id: str = "",
parent_id: str = "",
- kwargs: dict[Any, Any] = {},
+ kwargs: dict[Any, Any] = None,
) -> str:
+ if kwargs is None:
+ kwargs = {}
return event_id
def on_event_end(
@@ -74,9 +91,11 @@ class UsageHandler(StreamMixin, BaseCallbackHandler):
event_type: CBEventType,
payload: dict[str, Any] | None = None,
event_id: str = "",
- kwargs: dict[Any, Any] = {},
+ kwargs: dict[Any, Any] = None,
) -> None:
"""Push the usage of Embedding to platform service."""
+ if kwargs is None:
+ kwargs = {}
if (
event_type == CBEventType.EMBEDDING
and event_type not in self.event_ends_to_ignore
diff --git a/unstract/sdk1/src/unstract/sdk1/utils/callback_manager.py b/unstract/sdk1/src/unstract/sdk1/utils/callback_manager.py
index 5508b8ea4..b5a1c5578 100644
--- a/unstract/sdk1/src/unstract/sdk1/utils/callback_manager.py
+++ b/unstract/sdk1/src/unstract/sdk1/utils/callback_manager.py
@@ -1,5 +1,6 @@
import logging
from collections.abc import Callable
+from typing import Any
import tiktoken
from llama_index.core.callbacks import CallbackManager as LlamaIndexCallbackManager
@@ -24,10 +25,11 @@ class CallbackManager:
def set_callback(
platform_api_key: str,
model: LLM | BaseEmbedding,
- kwargs,
+ kwargs: dict[str, Any],
) -> None:
- """Sets the standard callback manager for LlamaIndex embedding. This is
- to be called explicitly to set the handlers which are invoked in the
+ """Sets the standard callback manager for LlamaIndex embedding.
+
+ This is to be called explicitly to set the handlers which are invoked in the
callback handling.
Parameters:
@@ -56,7 +58,7 @@ class CallbackManager:
def get_callback_manager(
model: LLM | BaseEmbedding,
platform_api_key: str,
- kwargs,
+ kwargs: dict[str, Any],
) -> LlamaIndexCallbackManager:
embedding = None
handler_list = []
@@ -82,9 +84,7 @@ class CallbackManager:
@staticmethod
def get_tokenizer(
model: BaseEmbedding | None,
- fallback_tokenizer: Callable[[str], list] = tiktoken.encoding_for_model(
- "gpt-3.5-turbo"
- ).encode,
+ fallback_tokenizer: Callable[[str], list] | None = None,
) -> Callable[[str], list]:
"""Returns a tokenizer function based on the provided model.
@@ -98,6 +98,8 @@ class CallbackManager:
Raises:
OSError: If an error occurs while loading the tokenizer.
"""
+ if fallback_tokenizer is None:
+ fallback_tokenizer = tiktoken.encoding_for_model("gpt-3.5-turbo").encode
try:
if isinstance(model, BaseEmbedding):
model_name = model.model_name
diff --git a/unstract/sdk1/src/unstract/sdk1/utils/common.py b/unstract/sdk1/src/unstract/sdk1/utils/common.py
index 07a1c57f1..ec3fa37f5 100644
--- a/unstract/sdk1/src/unstract/sdk1/utils/common.py
+++ b/unstract/sdk1/src/unstract/sdk1/utils/common.py
@@ -1,13 +1,18 @@
+from __future__ import annotations
+
import functools
import logging
import time
import uuid
+from typing import TYPE_CHECKING
-from requests import Response
-from requests.exceptions import RequestException
from unstract.sdk1.constants import Common, LogLevel, MimeType
from unstract.sdk1.utils.metrics_mixin import MetricsMixin
+if TYPE_CHECKING:
+ from requests import Response
+ from requests.exceptions import RequestException
+
logger = logging.getLogger(__name__)
@@ -33,7 +38,7 @@ class Utils:
@staticmethod
def pretty_file_size(num: float, suffix: str = "B") -> str:
- """Gets the human readable size for a file,
+ """Gets the human readable size for a file.
Args:
num (int): Size in bytes to parse
@@ -96,7 +101,16 @@ class Utils:
class TokenCounterCompat:
- def __init__(self, prompt_tokens: int, completion_tokens: int, total_tokens: int):
+ def __init__(
+ self, prompt_tokens: int, completion_tokens: int, total_tokens: int
+ ) -> None:
+ """Initialize the TokenCounterCompat for compatibility with token counting.
+
+ Args:
+ prompt_tokens: Number of tokens in the prompt
+ completion_tokens: Number of tokens in the completion
+ total_tokens: Total number of tokens used
+ """
self.prompt_llm_token_count = prompt_tokens
self.completion_llm_token_count = completion_tokens
self.total_llm_token_count = total_tokens
@@ -106,7 +120,12 @@ class TokenCounterCompat:
class LLMResponseCompat:
"""Compatibility class to mimic llama-index CompletionResponse interface."""
- def __init__(self, text):
+ def __init__(self, text: str) -> None:
+ """Initialize the LLMResponseCompat for compatibility with LLM responses.
+
+ Args:
+ text: The response text from the LLM
+ """
self.text = text
# Add other CompletionResponse attributes for compatibility
self.additional_kwargs = {}
@@ -124,16 +143,16 @@ PY_TO_UNSTRACT_LOG_LEVEL = {
}
-def log_elapsed(operation):
+def log_elapsed(operation: str) -> object:
"""Adds an elapsed time log.
Args:
operation (str): Operation being measured
"""
- def decorator(func):
+ def decorator(func: object) -> object:
@functools.wraps(func)
- def wrapper(*args, **kwargs):
+ def wrapper(*args: object, **kwargs: object) -> object:
start_time = time.time()
try:
result = func(*args, **kwargs)
@@ -148,11 +167,11 @@ def log_elapsed(operation):
return decorator
-def capture_metrics(func):
+def capture_metrics(func: object) -> object:
"""Decorator to capture metrics at the start and end of a function."""
@functools.wraps(func)
- def wrapper(self, *args, **kwargs):
+ def wrapper(self: object, *args: object, **kwargs: object) -> object:
# Ensure the required attributes exist; if not,
# execute the function and return its result
if not all(
diff --git a/unstract/sdk1/src/unstract/sdk1/utils/file_storage.py b/unstract/sdk1/src/unstract/sdk1/utils/file_storage.py
index eaa8cb950..845fce2c5 100644
--- a/unstract/sdk1/src/unstract/sdk1/utils/file_storage.py
+++ b/unstract/sdk1/src/unstract/sdk1/utils/file_storage.py
@@ -14,10 +14,10 @@ class FileStorageUtils:
destination_paths: list[str],
chunk_size: int = 4096,
) -> None:
- """Copy a file from a source storage to one or more paths in a
- destination storage.
+ """Copy file from source storage to destination storage paths.
- This function reads the source file in chunks and writes each chunk to
+ Copy a file from a source storage to one or more paths in a destination
+ storage. This function reads the source file in chunks and writes each chunk to
the specified destination paths. The function will continue until the
entire source file is copied.
diff --git a/unstract/sdk1/src/unstract/sdk1/utils/indexing.py b/unstract/sdk1/src/unstract/sdk1/utils/indexing.py
index 8d5a6d613..0e9bbef92 100644
--- a/unstract/sdk1/src/unstract/sdk1/utils/indexing.py
+++ b/unstract/sdk1/src/unstract/sdk1/utils/indexing.py
@@ -17,10 +17,12 @@ class IndexingUtils:
tool: BaseTool,
file_path: str | None = None,
file_hash: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> str:
- """Generates a unique index key based on the provided configuration,
- file information, instance identifiers, and processing options.
+ """Generate unique index key for document indexing.
+
+ Generates a unique index key based on the provided configuration, file
+ information, instance identifiers, and processing options.
Args:
fs (FileStorage, optional): File storage for remote storage.
@@ -28,6 +30,8 @@ class IndexingUtils:
Returns:
str: A unique index key used for indexing the document.
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
if not file_path and not file_hash:
raise ValueError("One of `file_path` or `file_hash` need to be provided")
diff --git a/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py b/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py
index 8f9bb3fde..9ffaf916e 100644
--- a/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py
+++ b/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py
@@ -12,7 +12,7 @@ logger = logging.getLogger(__name__)
class MetricsMixin:
TIME_TAKEN_KEY = "time_taken(s)"
- def __init__(self, run_id):
+ def __init__(self, run_id: str) -> None:
"""Initialize the MetricsMixin class.
Args:
@@ -39,18 +39,15 @@ class MetricsMixin:
# Set the start time immediately upon initialization
self.set_start_time()
- def set_start_time(self, ttl=86400):
- """Store the current timestamp in Redis when the instance is
- created.
- """
+ def set_start_time(self, ttl: int = 86400) -> None:
+ """Store the current timestamp in Redis when the instance is created."""
if self.redis_client is None:
logger.error("Redis client is not initialized. Cannot set start time.")
return
self.redis_client.set(self.redis_key, time.time(), ex=ttl)
def collect_metrics(self) -> dict[str, Any]:
- """Calculate the time taken since the timestamp was set and delete the
- Redis key.
+ """Calculate the time taken since the timestamp was set and delete the Redis key.
Returns:
dict: The calculated time taken and the associated run_id and op_id.
diff --git a/unstract/sdk1/src/unstract/sdk1/utils/tool.py b/unstract/sdk1/src/unstract/sdk1/utils/tool.py
index 8c72bdd60..2c5293101 100644
--- a/unstract/sdk1/src/unstract/sdk1/utils/tool.py
+++ b/unstract/sdk1/src/unstract/sdk1/utils/tool.py
@@ -3,7 +3,6 @@ import logging
import os
from hashlib import md5, sha256
from pathlib import Path
-from typing import Any
from unstract.sdk1.exceptions import FileStorageError
from unstract.sdk1.file_storage import (
@@ -19,7 +18,7 @@ class ToolUtils:
"""Class containing utility methods."""
@staticmethod
- def hash_str(string_to_hash: Any, hash_method: str = "sha256") -> str:
+ def hash_str(string_to_hash: object, hash_method: str = "sha256") -> str:
"""Computes the hash for a given input string.
Useful to hash strings needed for caching and other purposes.
@@ -38,7 +37,7 @@ class ToolUtils:
return str(md5(string_to_hash).hexdigest())
return str(md5(string_to_hash.encode()).hexdigest())
elif hash_method == "sha256":
- if isinstance(string_to_hash, (bytes, bytearray)):
+ if isinstance(string_to_hash, (bytes, bytearray)): # noqa: UP038
return str(sha256(string_to_hash).hexdigest())
return str(sha256(string_to_hash.encode()).hexdigest())
else:
@@ -47,8 +46,8 @@ class ToolUtils:
@staticmethod
def load_json(
file_to_load: str,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
- ) -> dict[str, Any]:
+ fs: FileStorage | None = None,
+ ) -> dict[str, object]:
"""Loads and returns a JSON from a file.
Args:
@@ -57,15 +56,17 @@ class ToolUtils:
Returns:
dict[str, Any]: The JSON loaded from file
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
file_contents: str = fs.read(path=file_to_load, mode="r", encoding="utf-8")
- loaded_json: dict[str, Any] = json.loads(file_contents)
+ loaded_json: dict[str, object] = json.loads(file_contents)
return loaded_json
@staticmethod
def dump_json(
- json_to_dump: dict[str, Any],
+ json_to_dump: dict[str, object],
file_to_dump: str,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> None:
"""Helps dump the JSON to a file.
@@ -73,13 +74,14 @@ class ToolUtils:
json_to_dump (dict[str, Any]): Input JSON to dump
file_to_dump (str): Path to the file to dump the JSON to
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
compact_json = json.dumps(json_to_dump, separators=(", ", ":"))
fs.write(path=file_to_dump, mode="w", data=compact_json)
@staticmethod
- def json_to_str(json_to_dump: dict[str, Any]) -> str:
- """Helps convert the JSON to a string. Useful for dumping the JSON to a
- file.
+ def json_to_str(json_to_dump: dict[str, object]) -> str:
+ """Helps convert the JSON to a string. Useful for dumping the JSON to a file.
Args:
json_to_dump (dict[str, Any]): Input JSON to dump
@@ -93,7 +95,7 @@ class ToolUtils:
@staticmethod
def get_file_size(
input_file: Path,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> int:
"""Gets the file size in bytes for an input file.
@@ -103,6 +105,8 @@ class ToolUtils:
Returns:
str: MIME type of the file
"""
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
file_length = fs.size(path=input_file)
return file_length
@@ -111,11 +115,11 @@ class ToolUtils:
def calculate_page_count(
pages_string: str, max_page: int = 0, min_page: int = 1
) -> int:
- """Calculates the total number of pages based on the input string of
- page numbers or ranges.
+ """Calculate total page count from string of page numbers or ranges.
- Parses the input 'pages_string' to extract individual page numbers or
- ranges separated by commas.
+ Calculates the total number of pages based on the input string of page
+ numbers or ranges. Parses the input 'pages_string' to extract individual
+ page numbers or ranges separated by commas.
Supports ranges like '1-5' or open-ended ranges like '4-'.
The 'max_page' parameter defines the upper limit for page numbers.
The 'min_page' parameter defines the lower limit for page numbers.
@@ -164,9 +168,7 @@ class ToolUtils:
def get_filestorage_provider(
var_name: str, default: str = "minio"
) -> FileStorageProvider:
- """Retrieve the file storage provider based on an environment
- variable.
- """
+ """Retrieve the file storage provider based on an environment variable."""
provider_name = os.environ.get(var_name, default).upper()
try:
# Attempt to map the provider name to an enum value, case-insensitively
@@ -179,26 +181,26 @@ class ToolUtils:
f"Invalid provider '{provider_name}'. Allowed providers: "
f"{allowed_providers}"
)
- raise FileStorageError(f"Invalid provider '{provider_name}'")
+ raise FileStorageError(f"Invalid provider '{provider_name}'") from None
@staticmethod
- def get_filestorage_credentials(var_name: str) -> dict[str, Any]:
- """Retrieve the file storage credentials based on an environment
- variable.
- """
+ def get_filestorage_credentials(var_name: str) -> dict[str, object]:
+ """Retrieve the file storage credentials based on an environment variable."""
credentials = os.environ.get(var_name, "{}")
try:
return json.loads(credentials)
- except json.JSONDecodeError:
+ except json.JSONDecodeError as e:
raise ValueError(
"File storage credentials are not set properly. "
"Please check your settings."
- )
+ ) from e
@staticmethod
def get_workflow_filestorage(
provider: FileStorageProvider,
- credentials: dict[str, Any] = {},
+ credentials: dict[str, object] | None = None,
) -> SharedTemporaryFileStorage:
"""Get the file storage for the workflow."""
+ if credentials is None:
+ credentials = {}
return SharedTemporaryFileStorage(provider=provider, **credentials)
diff --git a/unstract/sdk1/src/unstract/sdk1/vector_db.py b/unstract/sdk1/src/unstract/sdk1/vector_db.py
index 3aacf642b..4b2e20a6c 100644
--- a/unstract/sdk1/src/unstract/sdk1/vector_db.py
+++ b/unstract/sdk1/src/unstract/sdk1/vector_db.py
@@ -1,6 +1,5 @@
import logging
from collections.abc import Sequence
-from typing import Any
from llama_index.core import StorageContext, VectorStoreIndex
from llama_index.core.indices.base import IndexType
@@ -35,7 +34,14 @@ class VectorDB:
tool: BaseTool,
adapter_instance_id: str | None = None,
embedding: EmbeddingCompat | None = None,
- ):
+ ) -> None:
+ """Initialize the VectorDB for handling vector database operations.
+
+ Args:
+ tool: BaseTool instance for accessing tool-specific operations
+ adapter_instance_id: Optional adapter instance identifier for vector database
+ embedding: Optional embedding instance for vectorization operations
+ """
self._tool = tool
self._adapter_instance_id = adapter_instance_id
self._vector_db_instance = None
@@ -43,7 +49,7 @@ class VectorDB:
self._embedding_dimension = VectorDB.DEFAULT_EMBEDDING_DIMENSION
self._initialise(embedding)
- def _initialise(self, embedding: EmbeddingCompat | None = None):
+ def _initialise(self, embedding: EmbeddingCompat | None = None) -> None:
if embedding:
self._embedding_instance = embedding._embedding_instance
self._embedding_dimension = embedding._length
@@ -114,7 +120,7 @@ class VectorDB:
chunk_size: int = 1024,
chunk_overlap: int = 128,
show_progress: bool = False,
- **index_kwargs,
+ **index_kwargs: object,
) -> IndexType:
if not self._embedding_instance:
raise VectorDBError(self.EMBEDDING_INSTANCE_ERROR)
@@ -134,7 +140,7 @@ class VectorDB:
**index_kwargs,
)
- def get_vector_store_index(self, **kwargs: Any) -> VectorStoreIndex:
+ def get_vector_store_index(self, **kwargs: object) -> VectorStoreIndex:
if not self._embedding_instance:
raise VectorDBError(self.EMBEDDING_INSTANCE_ERROR)
return VectorStoreIndex.from_vector_store(
@@ -146,13 +152,13 @@ class VectorDB:
def get_storage_context(self) -> StorageContext:
return StorageContext.from_defaults(vector_store=self._vector_db_instance)
- def query(self, query) -> VectorStoreQueryResult:
+ def query(self, query: object) -> VectorStoreQueryResult:
try:
return self._vector_db_instance.query(query=query)
except Exception as e:
raise parse_vector_db_err(e, self.vector_db_adapter_class) from e
- def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
+ def delete(self, ref_doc_id: str, **delete_kwargs: object) -> None:
if not self.vector_db_adapter_class:
raise VectorDBError("Vector DB is not initialised properly")
self.vector_db_adapter_class.delete(
@@ -161,7 +167,7 @@ class VectorDB:
def add(
self,
- ref_doc_id,
+ ref_doc_id: str,
nodes: list[BaseNode],
) -> list[str]:
if not self.vector_db_adapter_class:
@@ -171,7 +177,7 @@ class VectorDB:
nodes=nodes,
)
- def close(self, **kwargs):
+ def close(self, **kwargs: object) -> None:
if not self.vector_db_adapter_class:
raise VectorDBError("Vector DB is not initialised properly")
self.vector_db_adapter_class.close()
diff --git a/unstract/sdk1/src/unstract/sdk1/x2txt.py b/unstract/sdk1/src/unstract/sdk1/x2txt.py
index 33a39da10..c45bb0a15 100644
--- a/unstract/sdk1/src/unstract/sdk1/x2txt.py
+++ b/unstract/sdk1/src/unstract/sdk1/x2txt.py
@@ -1,5 +1,4 @@
import io
-from abc import ABCMeta
from typing import Any
import pdfplumber
@@ -17,13 +16,22 @@ from unstract.sdk1.tool.base import BaseTool
from unstract.sdk1.utils.tool import ToolUtils
-class X2Text(metaclass=ABCMeta):
+class X2Text:
def __init__(
self,
tool: BaseTool,
adapter_instance_id: str | None = None,
- usage_kwargs: dict[Any, Any] = {},
- ):
+ usage_kwargs: dict[Any, Any] = None,
+ ) -> None:
+ """Initialize the X2Text for text extraction operations.
+
+ Args:
+ tool: BaseTool instance for accessing tool-specific operations
+ adapter_instance_id: Optional adapter instance identifier for text extraction
+ usage_kwargs: Usage tracking parameters for monitoring operations
+ """
+ if usage_kwargs is None:
+ usage_kwargs = {}
self._tool = tool
self._x2text_adapters = adapters
self._adapter_instance_id = adapter_instance_id
@@ -32,10 +40,10 @@ class X2Text(metaclass=ABCMeta):
self._initialise()
@property
- def x2text_instance(self):
+ def x2text_instance(self) -> X2TextAdapter:
return self._x2text_instance
- def _initialise(self):
+ def _initialise(self) -> None:
if self._adapter_instance_id:
self._x2text_instance = self._get_x2text()
@@ -86,9 +94,11 @@ class X2Text(metaclass=ABCMeta):
self,
input_file_path: str,
output_file_path: str | None = None,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
**kwargs: dict[Any, Any],
) -> TextExtractionResult:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
mime_type = fs.mime_type(input_file_path)
text_extraction_result: TextExtractionResult = None
if mime_type == MimeType.TEXT:
@@ -107,8 +117,10 @@ class X2Text(metaclass=ABCMeta):
self,
input_file_path: str,
mime_type: str,
- fs: FileStorage = FileStorage(provider=FileStorageProvider.LOCAL),
+ fs: FileStorage | None = None,
) -> None:
+ if fs is None:
+ fs = FileStorage(provider=FileStorageProvider.LOCAL)
file_size = ToolUtils.get_file_size(input_file_path, fs)
if mime_type == MimeType.PDF: