Skip to content

Commit

Permalink
HumeStreamClient improvements (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
gregorybchris authored Apr 13, 2023
1 parent 6d2373b commit 83d3ed1
Show file tree
Hide file tree
Showing 56 changed files with 887 additions and 791 deletions.
1 change: 1 addition & 0 deletions docs/config/burst-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
::: hume.models.config.burst_config.BurstConfig
1 change: 1 addition & 0 deletions docs/config/face-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
::: hume.models.config.face_config.FaceConfig
1 change: 1 addition & 0 deletions docs/config/facemesh-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
::: hume.models.config.facemesh_config.FacemeshConfig
1 change: 1 addition & 0 deletions docs/config/language-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
::: hume.models.config.language_config.LanguageConfig
1 change: 1 addition & 0 deletions docs/config/ner-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
::: hume.models.config.ner_config.NerConfig
1 change: 1 addition & 0 deletions docs/config/prosody-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
::: hume.models.config.prosody_config.ProsodyConfig
17 changes: 9 additions & 8 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ Python versions 3.8 and 3.9 are supported
Basic installation:

```bash
$ pip install hume
pip install hume
```

Websocket and streaming features can be enabled with:

```bash
$ pip install hume[stream]
pip install hume[stream]
```

## Basic Usage
Expand All @@ -26,10 +26,12 @@ $ pip install hume[stream]
```python
from hume import HumeBatchClient
from hume.models.config import FaceConfig

client = HumeBatchClient("<your-api-key>")
urls = ["https://tinyurl.com/hume-img"]
job = client.submit_face(urls)
config = FaceConfig(identify_faces=True)
job = client.submit_job(urls, [config])

print(job)
print("Running...")
Expand Down Expand Up @@ -60,14 +62,13 @@ print(job)
```python
import asyncio

from hume import HumeStreamClient, StreamSocket
from hume.config import FaceConfig
from hume import HumeStreamClient
from hume.models.config import FaceConfig

async def main():
client = HumeStreamClient("<your-api-key>")
configs = [FaceConfig(identify_faces=True)]
async with client.connect(configs) as socket:
socket: StreamSocket
config = FaceConfig(identify_faces=True)
async with client.connect([config]) as socket:
result = await socket.send_file("<your-image-filepath>")
print(result)

Expand Down
10 changes: 4 additions & 6 deletions hume/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
"""Module init."""
import importlib.metadata
from importlib.metadata import version

from hume._batch import BatchJob, BatchJobResult, BatchJobStatus, HumeBatchClient
from hume._stream import HumeStreamClient, StreamSocket
from hume._common.hume_client_error import HumeClientError
from hume._common.model_type import ModelType
from hume.error.hume_client_exception import HumeClientException

__version__ = importlib.metadata.version("hume")
__version__ = version("hume")

__all__ = [
"__version__",
"BatchJob",
"BatchJobResult",
"BatchJobStatus",
"HumeBatchClient",
"HumeClientError",
"HumeClientException",
"HumeStreamClient",
"ModelType",
"StreamSocket",
]
5 changes: 1 addition & 4 deletions hume/_batch/batch_job.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Batch job."""
import logging
from typing import TYPE_CHECKING

from hume._batch.batch_job_result import BatchJobResult
Expand All @@ -9,8 +8,6 @@
if TYPE_CHECKING:
from hume._batch.hume_batch_client import HumeBatchClient

logger = logging.getLogger(__name__)


class BatchJob:
"""Batch job."""
Expand Down Expand Up @@ -51,7 +48,7 @@ def await_complete(self, timeout: int = 300) -> BatchJobResult:
Args:
timeout (int): Maximum time in seconds to await. If the timeout is reached
before the job reaches a terminal state the job will continue to be processed,
but a `HumeClientError` will be raised to the caller of `await_complete`.
but a `HumeClientException` will be raised to the caller of `await_complete`.
Raises:
ValueError: If the timeout is not valid.
Expand Down
24 changes: 12 additions & 12 deletions hume/_batch/batch_job_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
from urllib.request import urlretrieve

from hume._batch.batch_job_status import BatchJobStatus
from hume._common.model_type import ModelType
from hume._common.config.job_config_base import JobConfigBase
from hume._common.config.config_utils import config_from_model_type
from hume._common.hume_client_error import HumeClientError
from hume._common.config_utils import config_from_model_type
from hume.error.hume_client_exception import HumeClientException
from hume.models import ModelType
from hume.models.config.model_config_base import ModelConfigBase


class BatchJobResult:
Expand All @@ -18,7 +18,7 @@ class BatchJobResult:
def __init__(
self,
*,
configs: Dict[ModelType, JobConfigBase],
configs: Dict[ModelType, ModelConfigBase],
urls: List[str],
status: BatchJobStatus,
predictions_url: Optional[str] = None,
Expand All @@ -31,7 +31,7 @@ def __init__(
"""Construct a BatchJobResult.
Args:
configs (Dict[ModelType, JobConfigBase]): Configurations for the `BatchJob`.
configs (Dict[ModelType, ModelConfigBase]): Configurations for the `BatchJob`.
urls (List[str]): URLs processed in the `BatchJob`.
status (BatchJobStatus): Status of `BatchJob`.
predictions_url (Optional[str]): URL to predictions file.
Expand All @@ -58,7 +58,7 @@ def download_predictions(self, filepath: Optional[Union[str, Path]] = None) -> N
filepath (Optional[Union[str, Path]]): Filepath where predictions will be downloaded.
"""
if self.predictions_url is None:
raise HumeClientError("Could not download job predictions. No predictions found on job result.")
raise HumeClientException("Could not download job predictions. No predictions found on job result.")
urlretrieve(self.predictions_url, filepath)

def download_artifacts(self, filepath: Optional[Union[str, Path]] = None) -> None:
Expand All @@ -68,7 +68,7 @@ def download_artifacts(self, filepath: Optional[Union[str, Path]] = None) -> Non
filepath (Optional[Union[str, Path]]): Filepath where artifacts zip archive will be downloaded.
"""
if self.artifacts_url is None:
raise HumeClientError("Could not download job artifacts. No artifacts found on job result.")
raise HumeClientException("Could not download job artifacts. No artifacts found on job result.")
urlretrieve(self.artifacts_url, filepath)

def download_errors(self, filepath: Optional[Union[str, Path]] = None) -> None:
Expand All @@ -78,7 +78,7 @@ def download_errors(self, filepath: Optional[Union[str, Path]] = None) -> None:
filepath (Optional[Union[str, Path]]): Filepath where errors will be downloaded.
"""
if self.errors_url is None:
raise HumeClientError("Could not download job errors. No errors found on job result.")
raise HumeClientException("Could not download job errors. No errors found on job result.")
urlretrieve(self.errors_url, filepath)

def get_error_message(self) -> Optional[str]:
Expand Down Expand Up @@ -137,7 +137,7 @@ def from_response(cls, response: Any) -> "BatchJobResult":
configs = {}
for model_name, config_dict in request["models"].items():
model_type = ModelType.from_str(model_name)
config = config_from_model_type(model_type).deserialize(config_dict)
config = config_from_model_type(model_type).from_dict(config_dict)
configs[model_type] = config

kwargs = {}
Expand Down Expand Up @@ -167,7 +167,7 @@ def from_response(cls, response: Any) -> "BatchJobResult":
# pylint: disable=broad-except
except Exception as exc:
message = cls._get_invalid_response_message(response)
raise HumeClientError(message) from exc
raise HumeClientException(message) from exc

@classmethod
def _get_invalid_response_message(cls, response: Any) -> str:
Expand All @@ -178,6 +178,6 @@ def _get_invalid_response_message(cls, response: Any) -> str:
if "fault" in response and "faultstring" in response["fault"]:
fault_string = response["fault"]["faultstring"]
if fault_string == "Invalid ApiKey":
message = "Client initialized with invalid API key"
message = "HumeBatchClient initialized with invalid API key."

return message
Loading

0 comments on commit 83d3ed1

Please sign in to comment.