diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 07e9f0a..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,5 +0,0 @@ -include README.md -include LICENSE -include docs/*.md -include test/data/*.wav -include test/data/*.mp3 diff --git a/README.md b/README.md deleted file mode 100644 index f04fe88..0000000 --- a/README.md +++ /dev/null @@ -1,135 +0,0 @@ -# deepaffects-python - -[![Build Status](https://travis-ci.org/SEERNET/deepaffects-python.svg?branch=master)](https://travis-ci.org/SEERNET/deepaffects-python) -[![PyPI version](https://badge.fury.io/py/deepaffects.svg)](https://badge.fury.io/py/deepaffects) - -Python client library for DeepAffects APIs - -## Requirements. - -Python 2.7 and 3.3+ - -pymediainfo >= 2.1.9, this is a wrapper library around [mediainfo](https://mediaarea.net/en/MediaInfo), which we use to -extract the sampling rate and codec information from audio files. - -## Installation - -### pip install - -The python package can be installed directly from pip using: - -```bash -pip install deepaffects - -``` -### pip install from github - -The python package is hosted on Github, you can install directly from Github - -```sh -pip install git+https://github.com/SEERNET/deepaffects-python.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/SEERNET/deepaffects-python.git`) - -Then import the package: -```python -import deepaffects -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import deepaffects -``` - -## Documentation for Authorization - -DeepAffects API authenticates all the api requests via API Key. - -For API key registration and setup, checkout our [quickstart guide](https://developers.deepaffects.com/docs/#quickstart-guide) - -### UserSecurity - -- **Type**: API key -- **API key parameter name**: apikey -- **Location**: URL query string - - -## Getting Started - -Please follow the [installation](#installation) instruction and execute the following python code: - - -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' -# create an instance of the API class -api_instance = deepaffects.DenoiseApi() -body = deepaffects.Audio.from_file('/path/to/file') # Audio | Audio object that needs to be denoised. -webhook = 'webhook_example' # str | The webhook url where result from async resource is posted -request_id = 'request_id_example' # str | Unique identifier for the request (optional) - -try: - # Denoise an audio file - api_response = api_instance.async_denoise_audio(body, webhook, request_id=request_id) - pprint(api_response) -except ApiException as e: - print("Exception when calling DenoiseApi->async_denoise_audio: %s\n" % e) - -``` - -## Documentation for API Endpoints - -All URIs are relative to *https://localhost* - -Class | Method | HTTP request | Description ------------------ | --------------------------------------- | ------------- | ------------- -*DenoiseApi* | [async_denoise_audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/DenoiseApi.md#async_denoise_audio) | **POST** /api/v1/async/denoise | Denoise an audio file -*DenoiseApi* | [sync_denoise_audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/DenoiseApi.md#sync_denoise_audio) | **POST** /api/v1/sync/denoise | Denoise an audio file -*DiarizeApiV2* | [async_diarize_audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/DiarizeApiV2.md#async_diarize_audio) | **POST** /api/v2/async/diarize | Diarize an audio file -*DiarizeApi* | [async_diarize_audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/DiarizeApi.md#async_diarize_audio) | **POST** /api/v1/async/diarize | Diarize an audio file (Legacy) -*DiarizeApi* | [sync_diarize_audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/DiarizeApi.md#sync_diarize_audio) | **POST** /api/v1/sync/diarize | Diarize an audio file (Legacy) -*EmotionApi* | [async_recognise_emotion](https://github.com/SEERNET/deepaffects-python/blob/master/docs/EmotionApi.md#async_recognise_emotion) | **POST** /api/v1/async/recognise_emotion | Find emotion in an audio file -*EmotionApi* | [sync_recognise_emotion](https://github.com/SEERNET/deepaffects-python/blob/master/docs/EmotionApi.md#sync_recognise_emotion) | **POST** /api/v1/sync/recognise_emotion | Find emotion in an audio file -*FeaturizeApi* | [async_featurize_audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/FeaturizeApi.md#async_featurize_audio) | **POST** /api/v1/async/featurize | featurize an audio file -*FeaturizeApi* | [sync_featurize_audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/FeaturizeApi.md#sync_featurize_audio) | **POST** /api/v1/sync/featurize | featurize an audio file - - -## Documentation For Models - - - [AsyncResponse](https://github.com/SEERNET/deepaffects-python/blob/master/docs/AsyncResponse.md) - - [Audio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/Audio.md) - - [DiarizeAudio](https://github.com/SEERNET/deepaffects-python/blob/master/docs/DiarizeAudio.md) - - [EmotionScore](https://github.com/SEERNET/deepaffects-python/blob/master/docs/EmotionScore.md) - - - - -## UserSecurity - -- **Type**: API key -- **API key parameter name**: apikey -- **Location**: URL query string - - -## About -[DeepAffects](https://www.deepaffects.com/dashboard) is an emotional intelligence analysis engine that measures the effect emotional intelligence -has on team dynamics, and provides emotional analytics that serve as the basis of insights to improve -project management, performance and satisfaction across organizations, projects, and teams. To watch DeepAffects in action: check out DeepAffects [Atlassian JIRA addon](https://marketplace.atlassian.com/plugins/com.deepaffects.teams.jira/cloud/overview) and our [Github addon](https://teams.deepaffects.com/). - - - diff --git a/deepaffects/__init__.py b/deepaffects/__init__.py index 87e529b..a5e29a9 100644 --- a/deepaffects/__init__.py +++ b/deepaffects/__init__.py @@ -1,36 +1,2 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: 0.1.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import models into sdk package -from .models.async_response import AsyncResponse -from .models.audio import Audio -from .models.diarize_audio import DiarizeAudio -from .models.emotion_score import EmotionScore -from .models.diarize_segment import DiarizeSegment - -# import apis into sdk package -from .apis.denoise_api import DenoiseApi -from .apis.diarize_api import DiarizeApi -from .apis.emotion_api import EmotionApi -from .apis.featurize_api import FeaturizeApi -from .apis.ellipsis_api import EllipsisAPI -from .apis.diarize_api_v2 import DiarizeApiV2 - -# import ApiClient -from .api_client import ApiClient - -from .configuration import Configuration - -configuration = Configuration() +from .text_emotion_recognition import EmotionApi +from .smart_punctuation import PunctApi \ No newline at end of file diff --git a/deepaffects/api_client.py b/deepaffects/api_client.py deleted file mode 100644 index 479c7f4..0000000 --- a/deepaffects/api_client.py +++ /dev/null @@ -1,621 +0,0 @@ -# coding: utf-8 -""" - DeepAffects - - OpenAPI spec version: v1 -""" - -from __future__ import absolute_import - -import os -import re -import json -import mimetypes -import tempfile -import threading - -from datetime import date, datetime - -# python 2 and python 3 compatibility library -from six import PY3, integer_types, iteritems, text_type -from six.moves.urllib.parse import quote - -from . import models -from .configuration import Configuration -from .rest import ApiException, RESTClientObject - - -class ApiClient(object): - """ - Generic API client for Swagger client library builds. - - Swagger generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the Swagger - templates. - - :param host: The base path for the server to call. - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to the API. - """ - - PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int if PY3 else long, - 'float': float, - 'str': str, - 'bool': bool, - 'date': date, - 'datetime': datetime, - 'object': object, - } - - def __init__(self, host=None, header_name=None, header_value=None, cookie=None): - """ - Constructor of the class. - """ - self.rest_client = RESTClientObject() - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - if host is None: - self.host = Configuration().host - else: - self.host = host - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'Swagger-Codegen/1.0.0/python' - - @property - def user_agent(self): - """ - Gets user agent. - """ - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - """ - Sets user agent. - """ - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - resource_path = resource_path.replace( - '{%s}' % k, quote(str(v), safe='')) # no safe chars, encode everything - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, - collection_formats) - - # post parameters - if post_params or files: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.host + resource_path - - # perform request and return response - response_data = self.request(method, url, - query_params=query_params, - headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - - self.last_response = response_data - - return_data = response_data - if _preload_content: - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if callback: - if _return_http_data_only: - callback(return_data) - else: - callback((return_data, response_data.status, response_data.getheaders())) - elif _return_http_data_only: - return (return_data) - else: - return (return_data, response_data.status, response_data.getheaders()) - - def sanitize_for_serialization(self, obj): - """ - Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) - elif isinstance(obj, (datetime, date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} - - def deserialize(self, response, response_type): - """ - Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """ - Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith('list['): - sub_kls = re.match('list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] - - if klass.startswith('dict('): - sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in iteritems(data)} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == date: - return self.__deserialize_date(data) - elif klass == datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True, - _request_timeout=None): - """ - Makes the HTTP request (synchronous) and return the deserialized data. - To make an async request, define a function for callback. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param callback function: Callback function for asynchronous request. - If provide this parameter, - the request will be called asynchronously. - :param _return_http_data_only: response data without head status code and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. - :return: - If provide parameter callback, - the request will be called asynchronously. - The method will return the request thread. - If parameter callback is None, - then the method will return the response directly. - """ - if callback is None: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback, - _return_http_data_only, collection_formats, _preload_content, _request_timeout) - else: - thread = threading.Thread(target=self.__call_api, - args=(resource_path, method, - path_params, query_params, - header_params, body, - post_params, files, - response_type, auth_settings, - callback, _return_http_data_only, - collection_formats, _preload_content, _request_timeout)) - thread.start() - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, _request_timeout=None): - """ - Makes the HTTP request using RESTClient. - """ - if method == "GET": - return self.rest_client.GET(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.HEAD(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.OPTIONS(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "POST": - return self.rest_client.POST(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.PUT(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.PATCH(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.DELETE(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """ - Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in iteritems(params) if isinstance(params, dict) else params: - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def prepare_post_parameters(self, post_params=None, files=None): - """ - Builds form parameters. - - :param post_params: Normal form parameters. - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if post_params: - params = post_params - - if files: - for k, v in iteritems(files): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.\ - guess_type(filename)[0] or 'application/octet-stream' - params.append(tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """ - Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """ - Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return 'application/json' - - content_types = [x.lower() for x in content_types] - - if 'application/json' in content_types or '*/*' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """ - Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - """ - config = Configuration() - - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = config.auth_settings().get(auth) - if auth_setting: - if not auth_setting['value']: - continue - elif auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys.append((auth_setting['key'], auth_setting['value'])) - else: - raise ValueError( - 'Authentication token must be in `query` or `header`' - ) - - def __deserialize_file(self, response): - """ - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - config = Configuration() - - fd, path = tempfile.mkstemp(dir=config.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.\ - search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ - group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "w") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """ - Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return unicode(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """ - Return a original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """ - Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - except ValueError: - raise ApiException( - status=0, - reason="Failed to parse `{0}` into a date object".format(string) - ) - - def __deserialize_datatime(self, string): - """ - Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - except ValueError: - raise ApiException( - status=0, - reason=( - "Failed to parse `{0}` into a datetime object" - .format(string) - ) - ) - - def __deserialize_model(self, data, klass): - """ - Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - instance = klass() - - if not instance.swagger_types: - return data - - for attr, attr_type in iteritems(instance.swagger_types): - if data is not None \ - and instance.attribute_map[attr] in data \ - and isinstance(data, (list, dict)): - value = data[instance.attribute_map[attr]] - setattr(instance, attr, self.__deserialize(value, attr_type)) - - return instance diff --git a/deepaffects/apis/__init__.py b/deepaffects/apis/__init__.py deleted file mode 100644 index cbd0dfc..0000000 --- a/deepaffects/apis/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import absolute_import - -# import apis into api package -from .denoise_api import DenoiseApi -from .diarize_api import DiarizeApi -from .emotion_api import EmotionApi -from .featurize_api import FeaturizeApi -from .ellipsis_api import EllipsisAPI -from .diarize_api_v2 import DiarizeApiV2 diff --git a/deepaffects/apis/denoise_api.py b/deepaffects/apis/denoise_api.py deleted file mode 100644 index 6199e1e..0000000 --- a/deepaffects/apis/denoise_api.py +++ /dev/null @@ -1,248 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -# python 2 and python 3 compatibility library -from six import iteritems - -from ..api_client import ApiClient -from ..configuration import Configuration - - -class DenoiseApi(object): - def __init__(self, api_client=None): - config = Configuration() - if api_client: - self.api_client = api_client - else: - if not config.api_client: - config.api_client = ApiClient() - self.api_client = config.api_client - - def async_denoise_audio(self, body, webhook, **kwargs): - """ - Denoise an audio file asynchronously - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_denoise_audio(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be denoised. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.async_denoise_audio_with_http_info(body, webhook, **kwargs) - else: - (data) = self.async_denoise_audio_with_http_info(body, webhook, **kwargs) - return data - - def async_denoise_audio_with_http_info(self, body, webhook, **kwargs): - """ - Denoise an audio file asynchronously - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_denoise_audio_with_http_info(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be denoised. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'webhook', 'request_id'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method async_denoise_audio" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `async_denoise_audio`") - # verify the required parameter 'webhook' is set - if ('webhook' not in params) or (params['webhook'] is None): - raise ValueError("Missing the required parameter `webhook` when calling `async_denoise_audio`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/async/denoise'.replace('{format}', 'json') - path_params = {} - - query_params = {} - if 'webhook' in params: - query_params['webhook'] = params['webhook'] - if 'request_id' in params: - query_params['request_id'] = params['request_id'] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='AsyncResponse', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def sync_denoise_audio(self, body, **kwargs): - """ - Denoise an audio file synchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_denoise_audio(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be denoised. (required) - :return: Audio - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.sync_denoise_audio_with_http_info(body, **kwargs) - else: - (data) = self.sync_denoise_audio_with_http_info(body, **kwargs) - return data - - def sync_denoise_audio_with_http_info(self, body, **kwargs): - """ - Denoise an audio file synchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_denoise_audio_with_http_info(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be denoised. (required) - :return: Audio - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method sync_denoise_audio" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `sync_denoise_audio`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/sync/denoise'.replace('{format}', 'json') - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Audio', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/deepaffects/apis/diarize_api.py b/deepaffects/apis/diarize_api.py deleted file mode 100644 index 4cc5ab4..0000000 --- a/deepaffects/apis/diarize_api.py +++ /dev/null @@ -1,249 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -# python 2 and python 3 compatibility library -from six import iteritems - -from ..api_client import ApiClient -from ..configuration import Configuration - - -class DiarizeApi(object): - - def __init__(self, api_client=None): - config = Configuration() - if api_client: - self.api_client = api_client - else: - if not config.api_client: - config.api_client = ApiClient() - self.api_client = config.api_client - - def async_diarize_audio(self, body, webhook, **kwargs): - """ - Diarize an audio file asynchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_diarize_audio(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param DiarizeAudio body: Audio object that needs to be diarized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.async_diarize_audio_with_http_info(body, webhook, **kwargs) - else: - (data) = self.async_diarize_audio_with_http_info(body, webhook, **kwargs) - return data - - def async_diarize_audio_with_http_info(self, body, webhook, **kwargs): - """ - Diarize an audio file asynchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_diarize_audio_with_http_info(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param DiarizeAudio body: Audio object that needs to be diarized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'webhook', 'request_id'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method async_diarize_audio" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `async_diarize_audio`") - # verify the required parameter 'webhook' is set - if ('webhook' not in params) or (params['webhook'] is None): - raise ValueError("Missing the required parameter `webhook` when calling `async_diarize_audio`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/async/diarize'.replace('{format}', 'json') - path_params = {} - - query_params = {} - if 'webhook' in params: - query_params['webhook'] = params['webhook'] - if 'request_id' in params: - query_params['request_id'] = params['request_id'] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='AsyncResponse', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def sync_diarize_audio(self, body, **kwargs): - """ - Diarize an audio file synchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_diarize_audio(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param DiarizeAudio body: Audio object that needs to be diarized. (required) - :return: list[Audio] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.sync_diarize_audio_with_http_info(body, **kwargs) - else: - (data) = self.sync_diarize_audio_with_http_info(body, **kwargs) - return data - - def sync_diarize_audio_with_http_info(self, body, **kwargs): - """ - Diarize an audio file synchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_diarize_audio_with_http_info(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param DiarizeAudio body: Audio object that needs to be diarized. (required) - :return: list[Audio] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method sync_diarize_audio" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `sync_diarize_audio`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/sync/diarize'.replace('{format}', 'json') - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Audio]', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/deepaffects/apis/diarize_api_v2.py b/deepaffects/apis/diarize_api_v2.py deleted file mode 100644 index 45bfc31..0000000 --- a/deepaffects/apis/diarize_api_v2.py +++ /dev/null @@ -1,145 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -# python 2 and python 3 compatibility library -from six import iteritems - -from ..api_client import ApiClient -from ..configuration import Configuration - - -class DiarizeApiV2(object): - - def __init__(self, api_client=None): - config = Configuration() - if api_client: - self.api_client = api_client - else: - if not config.api_client: - config.api_client = ApiClient() - self.api_client = config.api_client - - def async_diarize_audio(self, body, webhook, **kwargs): - """ - Diarize an audio file asynchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_diarize_audio(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param DiarizeAudio body: Audio object that needs to be diarized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.async_diarize_audio_with_http_info(body, webhook, **kwargs) - else: - (data) = self.async_diarize_audio_with_http_info(body, webhook, **kwargs) - return data - - def async_diarize_audio_with_http_info(self, body, webhook, **kwargs): - """ - Diarize an audio file asynchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_diarize_audio_with_http_info(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param DiarizeAudio body: Audio object that needs to be diarized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'webhook', 'request_id'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method async_diarize_audio" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `async_diarize_audio`") - # verify the required parameter 'webhook' is set - if ('webhook' not in params) or (params['webhook'] is None): - raise ValueError("Missing the required parameter `webhook` when calling `async_diarize_audio`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v2/async/diarize'.replace('{format}', 'json') - path_params = {} - - query_params = {} - if 'webhook' in params: - query_params['webhook'] = params['webhook'] - if 'request_id' in params: - query_params['request_id'] = params['request_id'] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='AsyncResponse', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - diff --git a/deepaffects/apis/ellipsis_api.py b/deepaffects/apis/ellipsis_api.py deleted file mode 100644 index 378bcff..0000000 --- a/deepaffects/apis/ellipsis_api.py +++ /dev/null @@ -1,249 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -# python 2 and python 3 compatibility library -from six import iteritems - -from ..api_client import ApiClient -from ..configuration import Configuration - - -class EllipsisAPI(object): - - def __init__(self, api_client=None): - config = Configuration() - if api_client: - self.api_client = api_client - else: - if not config.api_client: - config.api_client = ApiClient() - self.api_client = config.api_client - - def async_is_depressed(self, body, webhook, **kwargs): - """ - Detect whether the person in audio clip is depressed - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_is_depressed(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object to predict depression. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.async_is_depressed_with_http_info(body, webhook, **kwargs) - else: - (data) = self.async_is_depressed_with_http_info(body, webhook, **kwargs) - return data - - def async_is_depressed_with_http_info(self, body, webhook, **kwargs): - """ - Detect whether the person in audio clip is depressed - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_is_depressed_with_http_info(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object to predict depression. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'webhook', 'request_id'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method async_is_depressed" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `async_is_depressed`") - # verify the required parameter 'webhook' is set - if ('webhook' not in params) or (params['webhook'] is None): - raise ValueError("Missing the required parameter `webhook` when calling `async_is_depressed`") - - - collection_formats = {} - - resource_path = '/audio/custom/ellipsis/api/v1/async/is_depressed'.replace('{format}', 'json') - path_params = {} - - query_params = {} - if 'webhook' in params: - query_params['webhook'] = params['webhook'] - if 'request_id' in params: - query_params['request_id'] = params['request_id'] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='AsyncResponse', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def sync_is_depressed(self, body, **kwargs): - """ - Detect whether the person in audio clip is depressed - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_is_depressed(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object to predict depression. (required) - :return: boolean - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.sync_is_depressed_with_http_info(body, **kwargs) - else: - (data) = self.sync_is_depressed_with_http_info(body, **kwargs) - return data - - def sync_is_depressed_with_http_info(self, body, **kwargs): - """ - Detect whether the person in audio clip is depressed - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_is_depressed_with_http_info(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object to predict depression. (required) - :return: boolean - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method sync_is_depressed" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `sync_is_depressed`") - - - collection_formats = {} - - resource_path = '/audio/custom/ellipsis/api/v1/sync/is_depressed'.replace('{format}', 'json') - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='bool', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/deepaffects/apis/emotion_api.py b/deepaffects/apis/emotion_api.py deleted file mode 100644 index e4fb875..0000000 --- a/deepaffects/apis/emotion_api.py +++ /dev/null @@ -1,253 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -# python 2 and python 3 compatibility library -from six import iteritems - -from ..api_client import ApiClient -from ..configuration import Configuration - - -class EmotionApi(object): - - def __init__(self, api_client=None): - config = Configuration() - if api_client: - self.api_client = api_client - else: - if not config.api_client: - config.api_client = ApiClient() - self.api_client = config.api_client - - def async_recognise_emotion(self, body, webhook, **kwargs): - """ - Find emotion in an audio file - Extract emotion from an audio file asynchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_recognise_emotion(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.async_recognise_emotion_with_http_info(body, webhook, **kwargs) - else: - (data) = self.async_recognise_emotion_with_http_info(body, webhook, **kwargs) - return data - - def async_recognise_emotion_with_http_info(self, body, webhook, **kwargs): - """ - Find emotion in an audio file - Extract emotion from an audio file. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_recognise_emotion_with_http_info(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'webhook', 'request_id'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method async_recognise_emotion" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `async_recognise_emotion`") - # verify the required parameter 'webhook' is set - if ('webhook' not in params) or (params['webhook'] is None): - raise ValueError("Missing the required parameter `webhook` when calling `async_recognise_emotion`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/async/recognise_emotion'.replace('{format}', 'json') - path_params = {} - - query_params = {} - if 'webhook' in params: - query_params['webhook'] = params['webhook'] - if 'request_id' in params: - query_params['request_id'] = params['request_id'] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='AsyncResponse', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def sync_recognise_emotion(self, body, **kwargs): - """ - Find emotion in an audio file - Extract emotion from an audio file. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_recognise_emotion(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :return: list[EmotionScore] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.sync_recognise_emotion_with_http_info(body, **kwargs) - else: - (data) = self.sync_recognise_emotion_with_http_info(body, **kwargs) - return data - - def sync_recognise_emotion_with_http_info(self, body, **kwargs): - """ - Find emotion in an audio file - Extract emotion from an audio file. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_recognise_emotion_with_http_info(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :return: list[EmotionScore] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method sync_recognise_emotion" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `sync_recognise_emotion`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/sync/recognise_emotion'.replace('{format}', 'json') - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[EmotionScore]', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/deepaffects/apis/featurize_api.py b/deepaffects/apis/featurize_api.py deleted file mode 100644 index 184ba02..0000000 --- a/deepaffects/apis/featurize_api.py +++ /dev/null @@ -1,250 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -# python 2 and python 3 compatibility library -from six import iteritems - -from ..api_client import ApiClient -from ..configuration import Configuration - - -class FeaturizeApi(object): - - def __init__(self, api_client=None): - config = Configuration() - if api_client: - self.api_client = api_client - else: - if not config.api_client: - config.api_client = ApiClient() - self.api_client = config.api_client - - def async_featurize_audio(self, body, webhook, **kwargs): - """ - Extract paralinguistic feature from an audio file asynchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_featurize_audio(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.async_featurize_audio_with_http_info(body, webhook, **kwargs) - else: - (data) = self.async_featurize_audio_with_http_info(body, webhook, **kwargs) - return data - - def async_featurize_audio_with_http_info(self, body, webhook, **kwargs): - """ - featurize an audio file - Extract paralinguistic feature from an audio file. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.async_featurize_audio_with_http_info(body, webhook, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :param str webhook: The webhook url where result from async resource is posted (required) - :param str request_id: Unique identifier for the request - :return: AsyncResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'webhook', 'request_id'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method async_featurize_audio" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `async_featurize_audio`") - # verify the required parameter 'webhook' is set - if ('webhook' not in params) or (params['webhook'] is None): - raise ValueError("Missing the required parameter `webhook` when calling `async_featurize_audio`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/async/featurize'.replace('{format}', 'json') - path_params = {} - - query_params = {} - if 'webhook' in params: - query_params['webhook'] = params['webhook'] - if 'request_id' in params: - query_params['request_id'] = params['request_id'] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='AsyncResponse', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def sync_featurize_audio(self, body, **kwargs): - """ - Extract paralinguistic feature from an audio file synchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_featurize_audio(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :return: AudioFeatures - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.sync_featurize_audio_with_http_info(body, **kwargs) - else: - (data) = self.sync_featurize_audio_with_http_info(body, **kwargs) - return data - - def sync_featurize_audio_with_http_info(self, body, **kwargs): - """ - Extract paralinguistic feature from an audio file synchronously. - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.sync_featurize_audio_with_http_info(body, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Audio body: Audio object that needs to be featurized. (required) - :return: AudioFeatures - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method sync_featurize_audio" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params) or (params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `sync_featurize_audio`") - - - collection_formats = {} - - resource_path = '/audio/generic/api/v1/sync/featurize'.replace('{format}', 'json') - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) - - # Authentication setting - auth_settings = ['UserSecurity'] - - return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='AudioFeatures', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/deepaffects/asr.py b/deepaffects/asr.py new file mode 100644 index 0000000..708aa29 --- /dev/null +++ b/deepaffects/asr.py @@ -0,0 +1,85 @@ +import logging +import requests +import base64 + +PYAV = False +# try: +# import av +# PYAV = True +# except Exception as ex: +# logging.warn('Install https://github.com/mikeboers/PyAV for ease of use.') + +allowed_values = { + 'audioType': {'callcenter', 'meeting', 'earningscalls', 'interview', 'media-broadcast'} +} + +class AsrApi(): + URL = 'https://proxy.api.deepaffects.com/audio/generic/api/v1/async/asr' + API_KEY = None + def __init__(self, api_key): + if not api_key: + logging.error('"' + str(api_key) + '" is an invalid API key') + + AsrApi.API_KEY = api_key + + def async_asr( + self, + audio_file_path=None, url=None, + encoding=None, sampleRate=None, + languageCode='en-US', separateSpeakerPerChannel=False, + audioType='callcenter', + enablePunctuation=True, enableSpeakerDiarization=False, source=None, + webhook=None, request_id=None + ): + if not (audio_file_path or url): + logging.error("One of audio_file_path or url must be supplied.") + + if audio_file_path and url: + logging.error("Only one of audio_file_path and url must be supplied. Both cannot be true at the same time.") + + if not webhook: + logging.warn('Consider using webhooks for async requests.') + + if audioType not in allowed_values['audioType']: + logging.warn("The supplied audioType '" + str(audioType) + "' is not valid. Defaulting to audioType=callcenter") + audioType = 'callcenter' + + params = {'apikey': AsrApi.API_KEY} + if webhook: + params['webhook'] = webhook + if request_id: + params['request_id'] = request_id + + if not PYAV: + if not encoding: + logging.error("Encoding is not valid") + if not sampleRate: + logging.error("sampleRate is not valid") + + else: + pass + + request_json = {} + if audio_file_path: + content = open(audio_file_path, 'rb').read() + content = base64.b64encode(content).decode('utf-8') + request_json['content'] = content + + elif url: + request_json['url'] = url + + request_json['encoding'] = encoding + request_json['sampleRate'] = sampleRate + request_json['languageCode'] = languageCode + request_json['separateSpeakerPerChannel'] = separateSpeakerPerChannel + request_json['speakerCount'] = speakerCount + request_json['audioType'] = audioType + request_json['enablePunctuation'] = enablePunctuation + request_json['enableSpeakerDiarization'] = enableSpeakerDiarization + + if source: + request_json['source'] = source + + output = requests.post(url=AsrApi.URL, json=request_json, params=params).json() + + return output \ No newline at end of file diff --git a/deepaffects/configuration.py b/deepaffects/configuration.py deleted file mode 100644 index 22119db..0000000 --- a/deepaffects/configuration.py +++ /dev/null @@ -1,220 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: 0.1.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import urllib3 - -import sys -import logging - -from six import iteritems -from six.moves import http_client as httplib - - -def singleton(cls, *args, **kw): - instances = {} - - def _singleton(): - if cls not in instances: - instances[cls] = cls(*args, **kw) - return instances[cls] - return _singleton - - -@singleton -class Configuration(object): - def __init__(self): - """ - Constructor - """ - # Default Base url - self.host = "https://proxy.api.deepaffects.com" - # Default api client - self.api_client = None - # Temp file folder for downloading files - self.temp_folder_path = None - - # Authentication Settings - # dict to store API key(s) - self.api_key = {} - # dict to store API prefix (e.g. Bearer) - self.api_key_prefix = {} - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - - # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("swagger_client") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - # Log stream handler - self.logger_stream_handler = None - # Log file handler - self.logger_file_handler = None - # Debug file location - self.logger_file = None - # Debug switch - self.debug = False - - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API from https server. - self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. - self.ssl_ca_cert = None - # client certificate file - self.cert_file = None - # client key file - self.key_file = None - - @property - def logger_file(self): - """ - Gets the logger_file. - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """ - Sets the logger_file. - - If the logger_file is None, then add stream handler and remove file handler. - Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): - logger.addHandler(self.logger_file_handler) - if self.logger_stream_handler: - logger.removeHandler(self.logger_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logger_stream_handler = logging.StreamHandler() - self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in iteritems(self.logger): - logger.addHandler(self.logger_stream_handler) - if self.logger_file_handler: - logger.removeHandler(self.logger_file_handler) - - @property - def debug(self): - """ - Gets the debug status. - """ - return self.__debug - - @debug.setter - def debug(self, value): - """ - Sets the debug status. - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """ - Gets the logger_format. - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """ - Sets the logger_format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier): - """ - Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :return: The token for api key authentication. - """ - if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] - elif self.api_key.get(identifier): - return self.api_key[identifier] - - def get_basic_auth_token(self): - """ - Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ - .get('authorization') - - def auth_settings(self): - """ - Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - return { - 'UserSecurity': - { - 'type': 'api_key', - 'in': 'query', - 'key': 'apikey', - 'value': self.get_api_key_with_prefix('apikey') - }, - - } - - def to_debug_report(self): - """ - Gets the essential information for debugging. - - :return: The report for debugging. - """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: 0.1.0\n"\ - "SDK Package Version: 1.0.0".\ - format(env=sys.platform, pyversion=sys.version) diff --git a/deepaffects/interaction_analytics.py b/deepaffects/interaction_analytics.py new file mode 100644 index 0000000..00fb39e --- /dev/null +++ b/deepaffects/interaction_analytics.py @@ -0,0 +1,84 @@ +import logging +import requests +import base64 + +PYAV = False +# try: +# import av +# PYAV = True +# except Exception as ex: +# logging.warn('Install https://github.com/mikeboers/PyAV for ease of use.') + +allowed_values = { + 'audioType': {'callcenter', 'meeting', 'earningscalls', 'interview', 'media-broadcast'} +} + +class AnalyticsApi(): + URL = 'https://proxy.api.deepaffects.com/audio/generic/api/v1/async/analytics/interaction' + API_KEY = None + def __init__(self, api_key): + if not api_key: + logging.error('"' + str(api_key) + '" is an invalid API key') + + AnalyticsApi.API_KEY = api_key + + def async_analytics( + self, + audio_file_path=None, url=None, + encoding=None, sampleRate=None, + languageCode='en-US', separateSpeakerPerChannel=False, + speakerCount=-1, audioType='callcenter', + metrics=['all'], source=None, + webhook=None, request_id=None + ): + if not (audio_file_path or url): + logging.error("One of audio_file_path or url must be supplied.") + + if audio_file_path and url: + logging.error("Only one of audio_file_path and url must be supplied. Both cannot be true at the same time.") + + if not webhook: + logging.warn('Consider using webhooks for async requests.') + + if audioType not in allowed_values['audioType']: + logging.warn("The supplied audioType '" + str(audioType) + "' is not valid. Defaulting to audioType=callcenter") + audioType = 'callcenter' + + params = {'apikey': AnalyticsApi.API_KEY} + if webhook: + params['webhook'] = webhook + if request_id: + params['request_id'] = request_id + + if not PYAV: + if not encoding: + logging.error("Encoding is not valid") + if not sampleRate: + logging.error("sampleRate is not valid") + + else: + pass + + request_json = {} + if audio_file_path: + content = open(audio_file_path, 'rb').read() + content = base64.b64encode(content).decode('utf-8') + request_json['content'] = content + + elif url: + request_json['url'] = url + + request_json['encoding'] = encoding + request_json['sampleRate'] = sampleRate + request_json['languageCode'] = languageCode + request_json['separateSpeakerPerChannel'] = separateSpeakerPerChannel + request_json['speakerCount'] = speakerCount + request_json['audioType'] = audioType + request_json['metrics'] = metrics + + if source: + request_json['source'] = source + + output = requests.post(url=AnalyticsApi.URL, json=request_json, params=params).json() + + return output \ No newline at end of file diff --git a/deepaffects/models/__init__.py b/deepaffects/models/__init__.py deleted file mode 100644 index 60d9780..0000000 --- a/deepaffects/models/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: 0.1.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import models into model package -from .async_response import AsyncResponse -from .audio import Audio -from .diarize_audio import DiarizeAudio -from .emotion_score import EmotionScore -from .audio_features import AudioFeatures -from .diarize_segment import DiarizeSegment diff --git a/deepaffects/models/async_response.py b/deepaffects/models/async_response.py deleted file mode 100644 index 16a1607..0000000 --- a/deepaffects/models/async_response.py +++ /dev/null @@ -1,150 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - -from pprint import pformat - -from six import iteritems -import json - - -class AsyncResponse(object): - """ - NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - def __init__(self, request_id=None, api=None): - """ - AsyncResponse - a model defined in Swagger - - :param dict swaggerTypes: The key is attribute name - and the value is attribute type. - :param dict attributeMap: The key is attribute name - and the value is json key in definition. - """ - self.swagger_types = { - 'request_id': 'str', - 'api': 'str' - } - - self.attribute_map = { - 'request_id': 'request_id', - 'api': 'api' - } - - self._request_id = request_id - self._api = api - - @property - def request_id(self): - """ - Gets the request_id of this AsyncResponse. - Unique identifier for the api call - - :return: The request_id of this AsyncResponse. - :rtype: str - """ - return self._request_id - - @request_id.setter - def request_id(self, request_id): - """ - Sets the request_id of this AsyncResponse. - Unique identifier for the api call - - :param request_id: The request_id of this AsyncResponse. - :type: str - """ - if request_id is None: - raise ValueError("Invalid value for `request_id`, must not be `None`") - - self._request_id = request_id - - @property - def api(self): - """ - Gets the api of this AsyncResponse. - API hit - - :return: The api of this AsyncResponse. - :rtype: str - """ - return self._api - - @api.setter - def api(self, api): - """ - Sets the api of this AsyncResponse. - API hit - - :param api: The api of this AsyncResponse. - :type: str - """ - if api is None: - raise ValueError("Invalid value for `api`, must not be `None`") - - self._api = api - - def to_dict(self): - """ - Returns the model properties as a dict - """ - result = {} - - for attr, _ in iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) - - def __repr__(self): - """ - For `print` and `pprint` - """ - return self.to_str() - - def __eq__(self, other): - """ - Returns true if both objects are equal - """ - if not isinstance(other, AsyncResponse): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """ - Returns true if both objects are not equal - """ - return not self == other - - @staticmethod - def from_json(content_str): - content = json.loads(content_str) - async_response = AsyncResponse(api=content["api"], request_id=content["request_id"]) - return async_response - diff --git a/deepaffects/models/audio.py b/deepaffects/models/audio.py deleted file mode 100644 index ae816f9..0000000 --- a/deepaffects/models/audio.py +++ /dev/null @@ -1,222 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" -try: - import StringIO as SIO -except ImportError: - import io as SIO -import base64 -import json -from pprint import pformat - -from pymediainfo import MediaInfo -from six import iteritems - -class Audio(object): - def __init__(self, encoding=None, sample_rate=None, language_code='en-US', content=None): - """ - Audio - a model defined in Swagger - - :param dict swaggerTypes: The key is attribute name - and the value is attribute type. - :param dict attributeMap: The key is attribute name - and the value is json key in definition. - """ - self.swagger_types = { - 'encoding': 'str', - 'sample_rate': 'str', - 'language_code': 'str', - 'content': 'str' - } - - self.attribute_map = { - 'encoding': 'encoding', - 'sample_rate': 'sampleRate', - 'language_code': 'languageCode', - 'content': 'content' - } - - self._encoding = encoding - self._sample_rate = sample_rate - self._language_code = language_code - self._content = content - - @property - def encoding(self): - """ - Gets the encoding of this Audio. - Encoding of audio file like MP3, WAV etc. - - :return: The encoding of this Audio. - :rtype: str - """ - return self._encoding - - @encoding.setter - def encoding(self, encoding): - """ - Sets the encoding of this Audio. - Encoding of audio file like MP3, WAV etc. - - :param encoding: The encoding of this Audio. - :type: str - """ - if encoding is None: - raise ValueError("Invalid value for `encoding`, must not be `None`") - - self._encoding = encoding - - @property - def sample_rate(self): - """ - Gets the sample_rate of this Audio. - Sample rate of the audio file. - - :return: The sample_rate of this Audio. - :rtype: str - """ - return self._sample_rate - - @sample_rate.setter - def sample_rate(self, sample_rate): - """ - Sets the sample_rate of this Audio. - Sample rate of the audio file. - - :param sample_rate: The sample_rate of this Audio. - :type: int - """ - if sample_rate is None: - raise ValueError("Invalid value for `sample_rate`, must not be `None`") - - self._sample_rate = sample_rate - - @property - def language_code(self): - """ - Gets the language_code of this Audio. - Language spoken in the audio file. - - :return: The language_code of this Audio. - :rtype: str - """ - return self._language_code - - @language_code.setter - def language_code(self, language_code): - """ - Sets the language_code of this Audio. - Language spoken in the audio file. - - :param language_code: The language_code of this Audio. - :type: str - """ - if language_code is None: - raise ValueError("Invalid value for `language_code`, must not be `None`") - - self._language_code = language_code - - @property - def content(self): - """ - Gets the content of this Audio. - base64 encoding of the audio file. - - :return: The content of this Audio. - :rtype: str - """ - return self._content - - @content.setter - def content(self, content): - """ - Sets the content of this Audio. - base64 encoding of the audio file. - - :param content: The content of this Audio. - :type: str - """ - if content is None: - raise ValueError("Invalid value for `content`, must not be `None`") - - self._content = content - - def to_dict(self): - """ - Returns the model properties as a dict - """ - result = {} - - for attr, _ in iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) - - def __repr__(self): - """ - For `print` and `pprint` - """ - return self.to_str() - - def __eq__(self, other): - """ - Returns true if both objects are equal - """ - if not isinstance(other, Audio): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """ - Returns true if both objects are not equal - """ - return not self == other - - @staticmethod - def from_file(file_name, language_code='en-US'): - media_info = MediaInfo.parse(file_name) - codec = media_info.tracks[0].__dict__['codec'] - sampling_rate = media_info.tracks[1].__dict__['sampling_rate'] - fout = SIO.StringIO() - with open(file_name, 'rb') as fin: - audio_content = fin.read() - audio = Audio(encoding=codec, sample_rate=sampling_rate, language_code=language_code, - content=base64.b64encode(audio_content).decode('utf-8')) - fout.close() - return audio - - @staticmethod - def from_json(content_str): - content = json.loads(content_str) - audio = Audio(encoding=content['encoding'], sample_rate=content['sample_rate'], - language_code=content['language_code'], content=content['content']) - return audio - - def to_file(self, file_name): - base64.decode(SIO.StringIO(self.content), output=open(file_name, 'wb')) \ No newline at end of file diff --git a/deepaffects/models/audio_features.py b/deepaffects/models/audio_features.py deleted file mode 100644 index 7b46c7f..0000000 --- a/deepaffects/models/audio_features.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs # noqa: E501 - - OpenAPI spec version: 0.1.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - - -class AudioFeatures(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'mfccs': 'list[list[float]]', - 'zcr': 'list[float]', - 'energy': 'list[float]' - } - - attribute_map = { - 'mfccs': 'mfccs', - 'zcr': 'zcr', - 'energy': 'energy' - } - - def __init__(self, mfccs=None, zcr=None, energy=None): # noqa: E501 - """AudioFeatures - a model defined in Swagger""" # noqa: E501 - - self._mfccs = None - self._zcr = None - self._energy = None - self.discriminator = None - - - @property - def mfccs(self): - """Gets the mfccs of this AudioFeatures. # noqa: E501 - - mel frequency cepstral coefficients # noqa: E501 - - :return: The mfccs of this AudioFeatures. # noqa: E501 - :rtype: list[list[float]] - """ - return self._mfccs - - @mfccs.setter - def mfccs(self, mfccs): - """Sets the mfccs of this AudioFeatures. - - mel frequency cepstral coefficients # noqa: E501 - - :param mfccs: The mfccs of this AudioFeatures. # noqa: E501 - :type: list[list[float]] - """ - if mfccs is None: - raise ValueError("Invalid value for `mfccs`, must not be `None`") # noqa: E501 - - self._mfccs = mfccs - - @property - def zcr(self): - """Gets the zcr of this AudioFeatures. # noqa: E501 - - zero crossing rate # noqa: E501 - - :return: The zcr of this AudioFeatures. # noqa: E501 - :rtype: list[float] - """ - return self._zcr - - @zcr.setter - def zcr(self, zcr): - """Sets the zcr of this AudioFeatures. - - zero crossing rate # noqa: E501 - - :param zcr: The zcr of this AudioFeatures. # noqa: E501 - :type: list[float] - """ - if zcr is None: - raise ValueError("Invalid value for `zcr`, must not be `None`") # noqa: E501 - - self._zcr = zcr - - @property - def energy(self): - """Gets the energy of this AudioFeatures. # noqa: E501 - - energy # noqa: E501 - - :return: The energy of this AudioFeatures. # noqa: E501 - :rtype: list[float] - """ - return self._energy - - @energy.setter - def energy(self, energy): - """Sets the energy of this AudioFeatures. - - energy # noqa: E501 - - :param energy: The energy of this AudioFeatures. # noqa: E501 - :type: list[float] - """ - if energy is None: - raise ValueError("Invalid value for `energy`, must not be `None`") # noqa: E501 - - self._energy = energy - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AudioFeatures): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/deepaffects/models/diarize_audio.py b/deepaffects/models/diarize_audio.py deleted file mode 100644 index 1cdade3..0000000 --- a/deepaffects/models/diarize_audio.py +++ /dev/null @@ -1,311 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - -""" - - -try: - import StringIO as SIO -except ImportError: - import io as SIO -import base64 -import json -from pprint import pformat - -from pymediainfo import MediaInfo -from six import iteritems - - -class DiarizeAudio(object): - - def __init__(self, encoding=None, sample_rate=None, language_code='en-US', content=None, speakers=-1, - merge_segments=True, audio_type="default"): - """ - DiarizeAudio - a model defined in Swagger - - :param dict swaggerTypes: The key is attribute name - and the value is attribute type. - :param dict attributeMap: The key is attribute name - and the value is json key in definition. - """ - self.swagger_types = { - 'encoding': 'str', - 'sample_rate': 'int', - 'language_code': 'str', - 'content': 'str', - 'speakers': 'int', - 'audio_type': 'str', - 'merge_segments': 'bool' - } - - self.attribute_map = { - 'encoding': 'encoding', - 'sample_rate': 'sampleRate', - 'language_code': 'languageCode', - 'content': 'content', - 'speakers': 'speakers', - 'audio_type': 'audioType', - 'merge_segments': 'vad' - } - - self._encoding = encoding - self._sample_rate = sample_rate - self._language_code = language_code - self._content = content - self._speakers = speakers - self._merge_segments = merge_segments - self._audio_type = audio_type - - @property - def encoding(self): - """ - Gets the encoding of this DiarizeAudio. - Encoding of audio file like MP3, WAV etc. - - :return: The encoding of this DiarizeAudio. - :rtype: str - """ - return self._encoding - - @encoding.setter - def encoding(self, encoding): - """ - Sets the encoding of this DiarizeAudio. - Encoding of audio file like MP3, WAV etc. - - :param encoding: The encoding of this DiarizeAudio. - :type: str - """ - if encoding is None: - raise ValueError("Invalid value for `encoding`, must not be `None`") - - self._encoding = encoding - - @property - def sample_rate(self): - """ - Gets the sample_rate of this DiarizeAudio. - Sample rate of the audio file. - - :return: The sample_rate of this DiarizeAudio. - :rtype: int - """ - return self._sample_rate - - @sample_rate.setter - def sample_rate(self, sample_rate): - """ - Sets the sample_rate of this DiarizeAudio. - Sample rate of the audio file. - - :param sample_rate: The sample_rate of this DiarizeAudio. - :type: int - """ - if sample_rate is None: - raise ValueError("Invalid value for `sample_rate`, must not be `None`") - - self._sample_rate = sample_rate - - @property - def language_code(self): - """ - Gets the language_code of this DiarizeAudio. - Language spoken in the audio file. - - :return: The language_code of this DiarizeAudio. - :rtype: str - """ - return self._language_code - - @language_code.setter - def language_code(self, language_code): - """ - Sets the language_code of this DiarizeAudio. - Language spoken in the audio file. - - :param language_code: The language_code of this DiarizeAudio. - :type: str - """ - if language_code is None: - raise ValueError("Invalid value for `language_code`, must not be `None`") - - self._language_code = language_code - - @property - def content(self): - """ - Gets the content of this DiarizeAudio. - base64 encoding of the audio file. - - :return: The content of this DiarizeAudio. - :rtype: str - """ - return self._content - - @content.setter - def content(self, content): - """ - Sets the content of this DiarizeAudio. - base64 encoding of the audio file. - - :param content: The content of this DiarizeAudio. - :type: str - """ - if content is None: - raise ValueError("Invalid value for `content`, must not be `None`") - - self._content = content - - @property - def speakers(self): - """ - Gets the speakers of this DiarizeAudio. - Number of speakers in the file (-1 for unknown speakers) - - :return: The speakers of this DiarizeAudio. - :rtype: int - """ - return self._speakers - - @speakers.setter - def speakers(self, speakers): - """ - Sets the speakers of this DiarizeAudio. - Number of speakers in the file (-1 for unknown speakers) - - :param speakers: The speakers of this DiarizeAudio. - :type: int - """ - if speakers is None: - raise ValueError("Invalid value for `speakers`, must not be `None`") - - self._speakers = speakers - - @property - def audio_type(self): - """ - Gets the corresponding type of audio file - example: meeting, call-center, default - - :return: The audio_type of this DiarizeAudio. - :rtype: str - """ - return self._audio_type - - @audio_type.setter - def audio_type(self, audio_type): - """ - Sets the audio_type of this DiarizeAudio. - Corresponding type of audio file like meeting, call-center, default - - :param encoding: The audio_type of this DiarizeAudio. - :type: str - """ - if audio_type is None: - raise ValueError("Invalid value for `audio_type`, must not be `None`") - - self._audio_type = audio_type - - @property - def merge_segments(self): - """ - Whether the consecutive segments of same speaker should be merged - - :return: The merge_segments of this DiarizeAudio. - :rtype: bool - """ - return self._merge_segments - - @merge_segments.setter - def merge_segments(self, merge_segments): - """ - Sets the merge_segments of this DiarizeAudio. - Whether the consecutive segments of same speaker should be merged - - :param encoding: The merge_segments of this DiarizeAudio. - :type: str - """ - if merge_segments is None: - raise ValueError("Invalid value for `merge_segments`, must not be `None`") - - self._merge_segments = merge_segments - - def to_dict(self): - """ - Returns the model properties as a dict - """ - result = {} - - for attr, _ in iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) - - def __repr__(self): - """ - For `print` and `pprint` - """ - return self.to_str() - - def __eq__(self, other): - """ - Returns true if both objects are equal - """ - if not isinstance(other, DiarizeAudio): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """ - Returns true if both objects are not equal - """ - return not self == other - - @staticmethod - def from_file(file_name, language_code='en-US', speakers=-1, merge_segments=True, audio_type='default'): - media_info = MediaInfo.parse(file_name) - codec = media_info.tracks[0].__dict__['codec'] - sampling_rate = media_info.tracks[1].__dict__['sampling_rate'] - fout = SIO.StringIO() - with open(file_name, 'rb') as fin: - audio_content = fin.read() - audio = DiarizeAudio(encoding=codec, sample_rate=sampling_rate, language_code=language_code, - content=base64.b64encode(audio_content).decode('utf-8'), speakers=speakers, - merge_segments=merge_segments, audio_type=audio_type) - fout.close() - return audio - - @staticmethod - def from_json(content_str): - content = json.loads(content_str) - audio = DiarizeAudio(encoding=content['encoding'], sample_rate=content['sample_rate'], - language_code=content['language_code'], content=content['content'], - speakers=content['speakers'], merge_segments=content['merge_segments'], - audio_type=content['audio_type']) - return audio diff --git a/deepaffects/models/diarize_segment.py b/deepaffects/models/diarize_segment.py deleted file mode 100644 index 7a6e32c..0000000 --- a/deepaffects/models/diarize_segment.py +++ /dev/null @@ -1,167 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - -""" - - -from pprint import pformat -from six import iteritems - -class DiarizeSegment(object): - - def __init__(self, start=None, end=None, speaker_id=None): - """ - DiarizeSegment - a model defined in Swagger - - :param dict swaggerTypes: The key is attribute name - and the value is attribute type. - :param dict attributeMap: The key is attribute name - and the value is json key in definition. - """ - self.swagger_types = { - 'start': 'float', - 'end': 'float', - 'speaker_id': 'int' - } - - self.attribute_map = { - 'start': 'start', - 'end': 'end', - 'speaker_id': 'speakerId' - } - - self._start = start - self._end = end - self._speaker_id = speaker_id - - @property - def start(self): - """ - Gets the start of this DiarizeSegment. - start of the corresponding diarized segment. - - :return: The encoding of this DiarizeSegment. - :rtype: float - """ - return self._start - - @start.setter - def start(self, start): - """ - Sets the start of this DiarizeSegment. - start of the corresponding diarized segment. - - :param start: The start of this DiarizeSegment. - :type: float - """ - if start is None: - raise ValueError("Invalid value for `start`, must not be `None`") - - self._start = start - - @property - def end(self): - """ - Gets the end of this DiarizeSegment. - end of the corresponding diarized segment. - - :return: The end of this DiarizeSegment. - :rtype: float - """ - return self._end - - @end.setter - def end(self, end): - """ - Sets the end of this DiarizeSegment. - end of the corresponding diarized segment. - - :param end: The end of this DiarizeSegment. - :type: float - """ - if end is None: - raise ValueError("Invalid value for `end`, must not be `None`") - - self._end = end - - @property - def speaker_id(self): - """ - Gets the speaker_id of this DiarizeSegment. - Unique identifier of the speaker speaking in the segment - - :return: The speaker_id of this DiarizeSegment. - :rtype: int - """ - return self._speaker_id - - @speaker_id.setter - def speaker_id(self, speaker_id): - """ - Sets the speaker_id of this DiarizeSegment. - Unique identifier of the speaker speaking in the segment - - :param speaker_id: The speaker_id of this DiarizeSegment. - :type: sinttr - """ - if speaker_id is None: - raise ValueError("Invalid value for `speaker_id`, must not be `None`") - - self._speaker_id = speaker_id - - def to_dict(self): - """ - Returns the model properties as a dict - """ - result = {} - - for attr, _ in iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) - - def __repr__(self): - """ - For `print` and `pprint` - """ - return self.to_str() - - def __eq__(self, other): - """ - Returns true if both objects are equal - """ - if not isinstance(other, DiarizeSegment): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """ - Returns true if both objects are not equal - """ - return not self == other diff --git a/deepaffects/models/emotion_score.py b/deepaffects/models/emotion_score.py deleted file mode 100644 index ef16594..0000000 --- a/deepaffects/models/emotion_score.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects audio APIs -""" - -from pprint import pformat -from six import iteritems -import re - - -class EmotionScore(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'emotion': 'str', - 'score': 'float' - } - - attribute_map = { - 'emotion': 'emotion', - 'score': 'score' - } - - def __init__(self, emotion=None, score=None): # noqa: E501 - """EmotionScore - a model defined in Swagger""" # noqa: E501 - - self._emotion = None - self._score = None - self.discriminator = None - - self.emotion = emotion - self.score = score - - @property - def emotion(self): - """Gets the emotion of this EmotionScore. # noqa: E501 - - Type of emotion like Happy, Sad, Surprised etc. # noqa: E501 - - :return: The emotion of this EmotionScore. # noqa: E501 - :rtype: str - """ - return self._emotion - - @emotion.setter - def emotion(self, emotion): - """Sets the emotion of this EmotionScore. - - Type of emotion like Happy, Sad, Surprised etc. # noqa: E501 - - :param emotion: The emotion of this EmotionScore. # noqa: E501 - :type: str - """ - - self._emotion = emotion - - @property - def score(self): - """Gets the score of this EmotionScore. # noqa: E501 - - Probability score or confidence of the corresponding emotion. # noqa: E501 - - :return: The score of this EmotionScore. # noqa: E501 - :rtype: float - """ - return self._score - - @score.setter - def score(self, score): - """Sets the score of this EmotionScore. - - Probability score or confidence of the corresponding emotion. # noqa: E501 - - :param score: The score of this EmotionScore. # noqa: E501 - :type: float - """ - - self._score = score - - def to_dict(self): - """ - Returns the model properties as a dict - """ - result = {} - - for attr, _ in iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) - - def __repr__(self): - """ - For `print` and `pprint` - """ - return self.to_str() - - def __eq__(self, other): - """ - Returns true if both objects are equal - """ - if not isinstance(other, EmotionScore): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """ - Returns true if both objects are not equal - """ - return not self == other diff --git a/deepaffects/realtime/__init__.py b/deepaffects/realtime/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/deepaffects/realtime/api.py b/deepaffects/realtime/api.py deleted file mode 100644 index fb99cf2..0000000 --- a/deepaffects/realtime/api.py +++ /dev/null @@ -1,58 +0,0 @@ -from __future__ import print_function - -import random -import time -import grpc -import os -import io -import sys -import pydub -import base64 -from pydub import AudioSegment - -import deepaffects.realtime.deepaffects_realtime_pb2_grpc as deepaffects_grpc -import deepaffects.realtime.deepaffects_realtime_pb2 as deepaffects_types - - -configuration = { - "TIMEOUT_SECONDS" = 2000, - "API_KEY" = "" -} - - -def get_deepaffects_client(): - channel = grpc.insecure_channel('realtime.deepaffects.com:80') - stub = deepaffects_grpc.DeepAffectsRealtimeStub(channel) - return stub - - -# def generate_chunks(): -# # split sound in 5-second slices and export -# audio_clip = AudioSegment.from_file("modi_video.mp4") -# for i, chunk in enumerate(audio_clip[::1000]): -# time.sleep(1) -# chunk_name = "chunk.wav" -# with open(chunk_name, "wb") as f: -# chunk.export(f, format="wav") -# base64_chunk = encode_to_base64(chunk_name) -# os.remove(chunk_name) -# print("Sending chunk %s" % (i)) -# yield make_input_audio_segment(i, base64_chunk) - - -# def identify_speaker(stub): -# responses = stub.GetSpeaker(generate_chunks()) -# for response in responses: -# print("Received message %s at %s" % (response.id, -# response.speaker)) - - -# def run(): -# channel = grpc.insecure_channel('localhost:50051') -# stub = audio_stream_pb2_grpc.DeepAffectsApiStub(channel) -# print("-------------- Realtime Api --------------") -# get_speaker(stub) - - -# if __name__ == '__main__': -# run() diff --git a/deepaffects/realtime/deepaffects_realtime_pb2.py b/deepaffects/realtime/deepaffects_realtime_pb2.py deleted file mode 100644 index 6cbc5c8..0000000 --- a/deepaffects/realtime/deepaffects_realtime_pb2.py +++ /dev/null @@ -1,405 +0,0 @@ -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: deepaffects-realtime.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -from google.protobuf import descriptor_pb2 -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='deepaffects-realtime.proto', - package='deepaffectsrealtime', - syntax='proto3', - serialized_pb=_b('\n\x1a\x64\x65\x65paffects-realtime.proto\x12\x13\x64\x65\x65paffectsrealtime\"\xb3\x01\n\x0cSegmentChunk\x12\n\n\x02id\x18\x01 \x01(\x05\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\t\x12\x10\n\x08\x65ncoding\x18\x03 \x01(\t\x12\x14\n\x0clanguageCode\x18\x04 \x01(\t\x12\x12\n\nsampleRate\x18\x05 \x01(\x05\x12\x12\n\nspeakerIds\x18\x06 \x03(\t\x12\x15\n\rsegmentOffset\x18\x07 \x01(\x01\x12\x10\n\x08\x64uration\x18\x08 \x01(\x01\x12\r\n\x05\x45rror\x18\t \x01(\t\"y\n\x0eSegmentSpeaker\x12\n\n\x02id\x18\x01 \x01(\x05\x12\x12\n\nspeaker_id\x18\x02 \x01(\t\x12\r\n\x05start\x18\x03 \x01(\x01\x12\x0b\n\x03\x65nd\x18\x04 \x01(\x01\x12\r\n\x05\x45rror\x18\x05 \x01(\t\x12\x1c\n\x14identification_score\x18\x06 \x01(\x02\"o\n\x0eSegmentEmotion\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05start\x18\x02 \x01(\x01\x12\x0b\n\x03\x65nd\x18\x03 \x01(\x01\x12\x0f\n\x07\x65motion\x18\x04 \x01(\t\x12\r\n\x05\x45rror\x18\x05 \x01(\t\x12\x15\n\remotion_score\x18\x06 \x01(\x01\"\xa8\x01\n\x15SegmentDiarizeEmotion\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05start\x18\x02 \x01(\x01\x12\x0b\n\x03\x65nd\x18\x03 \x01(\x01\x12\x0f\n\x07\x65motion\x18\x04 \x01(\t\x12\x12\n\nspeaker_id\x18\x05 \x01(\t\x12\r\n\x05\x45rror\x18\x06 \x01(\t\x12\x15\n\remotion_score\x18\x07 \x01(\x01\x12\x1c\n\x14identification_score\x18\x08 \x01(\x01\x32\xbe\x02\n\x13\x44\x65\x65pAffectsRealtime\x12_\n\x0fIdentifySpeaker\x12!.deepaffectsrealtime.SegmentChunk\x1a#.deepaffectsrealtime.SegmentSpeaker\"\x00(\x01\x30\x01\x12_\n\x0fIdentifyEmotion\x12!.deepaffectsrealtime.SegmentChunk\x1a#.deepaffectsrealtime.SegmentEmotion\"\x00(\x01\x30\x01\x12\x65\n\x0e\x44iarizeEmotion\x12!.deepaffectsrealtime.SegmentChunk\x1a*.deepaffectsrealtime.SegmentDiarizeEmotion\"\x00(\x01\x30\x01\x42;\n\x1cio.grpc.examples.deepaffectsB\x13\x44\x65\x65paffectsRealtimeP\x01\xa2\x02\x03\x44RIb\x06proto3') -) - - - - -_SEGMENTCHUNK = _descriptor.Descriptor( - name='SegmentChunk', - full_name='deepaffectsrealtime.SegmentChunk', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='id', full_name='deepaffectsrealtime.SegmentChunk.id', index=0, - number=1, type=5, cpp_type=1, label=1, - has_default_value=False, default_value=0, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='content', full_name='deepaffectsrealtime.SegmentChunk.content', index=1, - number=2, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='encoding', full_name='deepaffectsrealtime.SegmentChunk.encoding', index=2, - number=3, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='languageCode', full_name='deepaffectsrealtime.SegmentChunk.languageCode', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='sampleRate', full_name='deepaffectsrealtime.SegmentChunk.sampleRate', index=4, - number=5, type=5, cpp_type=1, label=1, - has_default_value=False, default_value=0, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='speakerIds', full_name='deepaffectsrealtime.SegmentChunk.speakerIds', index=5, - number=6, type=9, cpp_type=9, label=3, - has_default_value=False, default_value=[], - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='segmentOffset', full_name='deepaffectsrealtime.SegmentChunk.segmentOffset', index=6, - number=7, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='duration', full_name='deepaffectsrealtime.SegmentChunk.duration', index=7, - number=8, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='Error', full_name='deepaffectsrealtime.SegmentChunk.Error', index=8, - number=9, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=52, - serialized_end=231, -) - - -_SEGMENTSPEAKER = _descriptor.Descriptor( - name='SegmentSpeaker', - full_name='deepaffectsrealtime.SegmentSpeaker', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='id', full_name='deepaffectsrealtime.SegmentSpeaker.id', index=0, - number=1, type=5, cpp_type=1, label=1, - has_default_value=False, default_value=0, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='speaker_id', full_name='deepaffectsrealtime.SegmentSpeaker.speaker_id', index=1, - number=2, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='start', full_name='deepaffectsrealtime.SegmentSpeaker.start', index=2, - number=3, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='end', full_name='deepaffectsrealtime.SegmentSpeaker.end', index=3, - number=4, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='Error', full_name='deepaffectsrealtime.SegmentSpeaker.Error', index=4, - number=5, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='identification_score', full_name='deepaffectsrealtime.SegmentSpeaker.identification_score', index=5, - number=6, type=2, cpp_type=6, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=233, - serialized_end=354, -) - - -_SEGMENTEMOTION = _descriptor.Descriptor( - name='SegmentEmotion', - full_name='deepaffectsrealtime.SegmentEmotion', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='id', full_name='deepaffectsrealtime.SegmentEmotion.id', index=0, - number=1, type=5, cpp_type=1, label=1, - has_default_value=False, default_value=0, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='start', full_name='deepaffectsrealtime.SegmentEmotion.start', index=1, - number=2, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='end', full_name='deepaffectsrealtime.SegmentEmotion.end', index=2, - number=3, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='emotion', full_name='deepaffectsrealtime.SegmentEmotion.emotion', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='Error', full_name='deepaffectsrealtime.SegmentEmotion.Error', index=4, - number=5, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='emotion_score', full_name='deepaffectsrealtime.SegmentEmotion.emotion_score', index=5, - number=6, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=356, - serialized_end=467, -) - - -_SEGMENTDIARIZEEMOTION = _descriptor.Descriptor( - name='SegmentDiarizeEmotion', - full_name='deepaffectsrealtime.SegmentDiarizeEmotion', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='id', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.id', index=0, - number=1, type=5, cpp_type=1, label=1, - has_default_value=False, default_value=0, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='start', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.start', index=1, - number=2, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='end', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.end', index=2, - number=3, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='emotion', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.emotion', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='speaker_id', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.speaker_id', index=4, - number=5, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='Error', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.Error', index=5, - number=6, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='emotion_score', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.emotion_score', index=6, - number=7, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='identification_score', full_name='deepaffectsrealtime.SegmentDiarizeEmotion.identification_score', index=7, - number=8, type=1, cpp_type=5, label=1, - has_default_value=False, default_value=float(0), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=470, - serialized_end=638, -) - -DESCRIPTOR.message_types_by_name['SegmentChunk'] = _SEGMENTCHUNK -DESCRIPTOR.message_types_by_name['SegmentSpeaker'] = _SEGMENTSPEAKER -DESCRIPTOR.message_types_by_name['SegmentEmotion'] = _SEGMENTEMOTION -DESCRIPTOR.message_types_by_name['SegmentDiarizeEmotion'] = _SEGMENTDIARIZEEMOTION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -SegmentChunk = _reflection.GeneratedProtocolMessageType('SegmentChunk', (_message.Message,), dict( - DESCRIPTOR = _SEGMENTCHUNK, - __module__ = 'deepaffects_realtime_pb2' - # @@protoc_insertion_point(class_scope:deepaffectsrealtime.SegmentChunk) - )) -_sym_db.RegisterMessage(SegmentChunk) - -SegmentSpeaker = _reflection.GeneratedProtocolMessageType('SegmentSpeaker', (_message.Message,), dict( - DESCRIPTOR = _SEGMENTSPEAKER, - __module__ = 'deepaffects_realtime_pb2' - # @@protoc_insertion_point(class_scope:deepaffectsrealtime.SegmentSpeaker) - )) -_sym_db.RegisterMessage(SegmentSpeaker) - -SegmentEmotion = _reflection.GeneratedProtocolMessageType('SegmentEmotion', (_message.Message,), dict( - DESCRIPTOR = _SEGMENTEMOTION, - __module__ = 'deepaffects_realtime_pb2' - # @@protoc_insertion_point(class_scope:deepaffectsrealtime.SegmentEmotion) - )) -_sym_db.RegisterMessage(SegmentEmotion) - -SegmentDiarizeEmotion = _reflection.GeneratedProtocolMessageType('SegmentDiarizeEmotion', (_message.Message,), dict( - DESCRIPTOR = _SEGMENTDIARIZEEMOTION, - __module__ = 'deepaffects_realtime_pb2' - # @@protoc_insertion_point(class_scope:deepaffectsrealtime.SegmentDiarizeEmotion) - )) -_sym_db.RegisterMessage(SegmentDiarizeEmotion) - - -DESCRIPTOR.has_options = True -DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\034io.grpc.examples.deepaffectsB\023DeepaffectsRealtimeP\001\242\002\003DRI')) - -_DEEPAFFECTSREALTIME = _descriptor.ServiceDescriptor( - name='DeepAffectsRealtime', - full_name='deepaffectsrealtime.DeepAffectsRealtime', - file=DESCRIPTOR, - index=0, - options=None, - serialized_start=641, - serialized_end=959, - methods=[ - _descriptor.MethodDescriptor( - name='IdentifySpeaker', - full_name='deepaffectsrealtime.DeepAffectsRealtime.IdentifySpeaker', - index=0, - containing_service=None, - input_type=_SEGMENTCHUNK, - output_type=_SEGMENTSPEAKER, - options=None, - ), - _descriptor.MethodDescriptor( - name='IdentifyEmotion', - full_name='deepaffectsrealtime.DeepAffectsRealtime.IdentifyEmotion', - index=1, - containing_service=None, - input_type=_SEGMENTCHUNK, - output_type=_SEGMENTEMOTION, - options=None, - ), - _descriptor.MethodDescriptor( - name='DiarizeEmotion', - full_name='deepaffectsrealtime.DeepAffectsRealtime.DiarizeEmotion', - index=2, - containing_service=None, - input_type=_SEGMENTCHUNK, - output_type=_SEGMENTDIARIZEEMOTION, - options=None, - ), -]) -_sym_db.RegisterServiceDescriptor(_DEEPAFFECTSREALTIME) - -DESCRIPTOR.services_by_name['DeepAffectsRealtime'] = _DEEPAFFECTSREALTIME - -# @@protoc_insertion_point(module_scope) diff --git a/deepaffects/realtime/deepaffects_realtime_pb2_grpc.py b/deepaffects/realtime/deepaffects_realtime_pb2_grpc.py deleted file mode 100644 index 6d25999..0000000 --- a/deepaffects/realtime/deepaffects_realtime_pb2_grpc.py +++ /dev/null @@ -1,83 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - -import deepaffects.realtime.deepaffects_realtime_pb2 as deepaffects__realtime__pb2 - - -class DeepAffectsRealtimeStub(object): - """Interface exported by the server. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.IdentifySpeaker = channel.stream_stream( - '/deepaffectsrealtime.DeepAffectsRealtime/IdentifySpeaker', - request_serializer=deepaffects__realtime__pb2.SegmentChunk.SerializeToString, - response_deserializer=deepaffects__realtime__pb2.SegmentSpeaker.FromString, - ) - self.IdentifyEmotion = channel.stream_stream( - '/deepaffectsrealtime.DeepAffectsRealtime/IdentifyEmotion', - request_serializer=deepaffects__realtime__pb2.SegmentChunk.SerializeToString, - response_deserializer=deepaffects__realtime__pb2.SegmentEmotion.FromString, - ) - self.DiarizeEmotion = channel.stream_stream( - '/deepaffectsrealtime.DeepAffectsRealtime/DiarizeEmotion', - request_serializer=deepaffects__realtime__pb2.SegmentChunk.SerializeToString, - response_deserializer=deepaffects__realtime__pb2.SegmentDiarizeEmotion.FromString, - ) - - -class DeepAffectsRealtimeServicer(object): - """Interface exported by the server. - """ - - def IdentifySpeaker(self, request_iterator, context): - """A Bidirectional streaming RPC. - - Accepts a stream of SegmentChunk sent while a route is being traversed, - while receiving other SegmentSpeaker (e.g. from other users). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def IdentifyEmotion(self, request_iterator, context): - # missing associated documentation comment in .proto file - pass - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def DiarizeEmotion(self, request_iterator, context): - # missing associated documentation comment in .proto file - pass - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - -def add_DeepAffectsRealtimeServicer_to_server(servicer, server): - rpc_method_handlers = { - 'IdentifySpeaker': grpc.stream_stream_rpc_method_handler( - servicer.IdentifySpeaker, - request_deserializer=deepaffects__realtime__pb2.SegmentChunk.FromString, - response_serializer=deepaffects__realtime__pb2.SegmentSpeaker.SerializeToString, - ), - 'IdentifyEmotion': grpc.stream_stream_rpc_method_handler( - servicer.IdentifyEmotion, - request_deserializer=deepaffects__realtime__pb2.SegmentChunk.FromString, - response_serializer=deepaffects__realtime__pb2.SegmentEmotion.SerializeToString, - ), - 'DiarizeEmotion': grpc.stream_stream_rpc_method_handler( - servicer.DiarizeEmotion, - request_deserializer=deepaffects__realtime__pb2.SegmentChunk.FromString, - response_serializer=deepaffects__realtime__pb2.SegmentDiarizeEmotion.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - 'deepaffectsrealtime.DeepAffectsRealtime', rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) diff --git a/deepaffects/realtime/types.py b/deepaffects/realtime/types.py deleted file mode 100644 index de7c93e..0000000 --- a/deepaffects/realtime/types.py +++ /dev/null @@ -1,25 +0,0 @@ -from deepaffects.realtime.deepaffects_realtime_pb2 import SegmentChunk - - -def segment_chunk(content, encoding="wav", languageCode="en-US", sampleRate=8000, segmentOffset=0, duration=0): - """segment_chunk. - - Args: - encoding : Audio Encoding, - languageCode: language code , - sampleRate: sample rate of audio , - content: base64 encoded audio, - duration: in seconds, - segmentOffset: offset of the segment in complete audio stream - """ - - if duration < 3: - raise ValueError('Chunk duration should be greater than 3 sec.') - - return SegmentChunk( - content=content, - encoding=encoding, - languageCode=languageCode, - sampleRate=sampleRate, - duration=duration, - segmentOffset=segmentOffset) diff --git a/deepaffects/realtime/util.py b/deepaffects/realtime/util.py deleted file mode 100644 index ac6ddee..0000000 --- a/deepaffects/realtime/util.py +++ /dev/null @@ -1,200 +0,0 @@ -from __future__ import print_function -import random -import time -import grpc -import os -import uuid -import io -import sys -import m3u8 -import pydub -import requests -import base64 -import uuid -from pydub import AudioSegment -from pytube.request import get -from pytube.compat import urlopen -from pytube import YouTube - -import deepaffects.realtime.deepaffects_realtime_pb2_grpc as deepaffects_grpc -import deepaffects.realtime.deepaffects_realtime_pb2 as deepaffects_types -from deepaffects.realtime.types import segment_chunk - -MAX_MESSAGE_LENGTH = 1000000000 - -def encode_to_base64(file): - with open(file, "rb") as f1: - return base64.b64encode(f1.read()).decode('utf-8') - - -def get_segment_chunk_from_pydub_chunk(chunk, offset, i): - base64_chunk = pydub_segment_to_base64(chunk,i) - print("Sending chunk %s - with size :- %s sec" % (i, len(chunk) / 1000)) - audio_segments = segment_chunk( - encoding="wav", - languageCode="en-US", - sampleRate=chunk.frame_rate, - content=base64_chunk, - duration=len(chunk) / 1000, - segmentOffset=offset) - offset = (offset + len(chunk) / 1000) - return audio_segments, offset - - -def pydub_segment_to_base64(chunk,i): - chunk_file = "chunk-{}-{}.wav".format(i, str(uuid.uuid4())) - chunk.export(chunk_file, format="wav") - base64_chunk = encode_to_base64(chunk_file) - try: - os.remove(chunk_file) - except: - pass - return base64_chunk - - -def get_deepaffects_client(host_url='realtime.deepaffects.com:80'): - channel = grpc.insecure_channel(host_url, options=[('grpc.max_send_message_length', MAX_MESSAGE_LENGTH), ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH)]) - stub = deepaffects_grpc.DeepAffectsRealtimeStub(channel) - return stub - - -def chunk_generator_from_playlist(file_path=None, out_file_name=None, buffer_size=30000, download_audio=True): - chunk = None - try: - offset = 0 - last_processed = -1 - endlist = False - # for playlists with m3u8 extensions - m3u8_obj_outer = m3u8.load(file_path) - base_uri = m3u8_obj_outer.base_uri - base_audio = m3u8_obj_outer.data['playlists'][0]['uri'] - audio_stream_url = base_uri + base_audio - chunk_index = 1 - index = 0 - unsent_segment = False - while endlist is not True: - try: - m3u8_obj = m3u8.load(audio_stream_url) - if last_processed < m3u8_obj.media_sequence: - for i, segment in enumerate(m3u8_obj.data['segments']): - response = urlopen(base_uri + segment['uri']) - buff = response.read() - new_chunk = AudioSegment.from_file(io.BytesIO(buff), "aac") - - if (chunk_index == 1) and (last_processed == -1): - chunk = new_chunk - else: - chunk = chunk + new_chunk - - offset_in_milliseconds = offset * 1000 - if (len(chunk) - (offset_in_milliseconds)) > buffer_size: - segment_chunk = chunk[offset_in_milliseconds: offset_in_milliseconds + buffer_size] - audio_segment, offset = get_segment_chunk_from_pydub_chunk(segment_chunk, offset, index) - index = index + 1 - yield audio_segment - chunk_index = chunk_index + 1 - last_processed = m3u8_obj.media_sequence - - if m3u8_obj.data['is_endlist'] == True: - endlist = True - else: - time.sleep(2) - except Exception as e: - print(e) - endlist = True - - if (len(chunk) - (offset * 1000)) > 0: - segment_chunk = chunk[offset * 1000:] - audio_segment, offset = get_segment_chunk_from_pydub_chunk(segment_chunk, offset, index) - index = index + 1 - yield audio_segment - - except Exception as e: - print(e) - finally: - if download_audio and (out_file_name is not None) and (chunk is not None): - dir_path = "./output" - if not os.path.exists(dir_path): - os.makedirs(dir_path) - chunk.export(dir_path + out_file_name + "-audio-out.wav", format="wav") - - - -def chunk_generator_from_file(file_path, buffer_size=30000): - # Implement this generator function to yield Audio segments - # To generate Audio Segments use segment_chunk - # from deepaffects.realtime.types import segment_chunk - # yield segment_chunk(Args) - """segment_chunk. - - Args: - encoding : Audio Encoding, - languageCode: language code , - sampleRate: sample rate of audio , - content: base64 encoded audio, - segmentOffset: offset of the segment in complete audio stream - """ - - """ - Sample implementation which reads audio from a file and splits it into - segments more than 3 sec - AudioSegment and yields base64 encoded audio segment objects asynchronously - """ - audio_clip = AudioSegment.from_file(file_path) - offset = None - buffer_chunk = None - index = 0 - for i, chunk in enumerate(audio_clip[::buffer_size]): - if offset is None: - offset = 0 - if i == 0: - buffer_chunk = chunk - else: - buffer_chunk = buffer_chunk + chunk - offset_in_milliseconds = offset * 1000 - if ((len(buffer_chunk) - (offset_in_milliseconds)) > buffer_size): - segment_chunk = buffer_chunk[offset_in_milliseconds: offset_in_milliseconds + buffer_size] - audio_segment, offset = get_segment_chunk_from_pydub_chunk(segment_chunk, offset, index) - index = index + 1 - yield audio_segment - - if ((len(buffer_chunk) - (offset * 1000)) != 0): - segment_chunk = buffer_chunk[offset * 1000:] - audio_segment, offset = get_segment_chunk_from_pydub_chunk(segment_chunk, offset, index) - index = index + 1 - yield audio_segment - - - -def chunk_generator_from_url(file_path, is_youtube_url=False, buffer_size=30000, chunk_size=15 * 8192): - if is_youtube_url: - yt = YouTube(file_path) - stream = yt.streams.filter(only_audio=True).first() - download_url = stream.url - else: - download_url = file_path - offset = None - buffer_chunk = None - index = 0 - for i, chunk in enumerate(get(url=download_url, streaming=True, chunk_size=chunk_size)): - if offset is None: - offset = 0 - if i == 0: - buffer_chunk_raw = chunk - else: - buffer_chunk_raw = buffer_chunk_raw + chunk - - buffer_chunk = AudioSegment.from_file(io.BytesIO( - buffer_chunk_raw)) - - offset_in_milliseconds = offset * 1000 - if (len(buffer_chunk) - (offset_in_milliseconds)) > buffer_size: - segment_chunk = buffer_chunk[offset_in_milliseconds: offset_in_milliseconds + buffer_size] - audio_segment, offset = get_segment_chunk_from_pydub_chunk(segment_chunk, offset, index) - index = index + 1 - yield audio_segment - if (len(buffer_chunk) - (offset * 1000)) != 0: - segment_chunk = buffer_chunk[offset * 1000:] - audio_segment, offset = get_segment_chunk_from_pydub_chunk(segment_chunk, offset, index) - index = index + 1 - yield audio_segment diff --git a/deepaffects/rest.py b/deepaffects/rest.py deleted file mode 100644 index 9a73fbf..0000000 --- a/deepaffects/rest.py +++ /dev/null @@ -1,297 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: 0.1.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import io -import json -import ssl -import certifi -import logging -import re - -# python 2 and python 3 compatibility library -from six import PY3 -from six.moves.urllib.parse import urlencode - -from .configuration import Configuration - -try: - import urllib3 -except ImportError: - raise ImportError('Swagger python client requires urllib3.') - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """ - Returns a dictionary of the response headers. - """ - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """ - Returns a given response header. - """ - return self.urllib3_response.getheader(name, default) - - -class RESTClientObject(object): - - def __init__(self, pools_size=4, maxsize=4): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 - # maxsize is the number of requests to host that are allowed in parallel - # ca_certs vs cert_file vs key_file - # http://stackoverflow.com/a/23957365/2985775 - - # cert_reqs - if Configuration().verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if Configuration().ssl_ca_cert: - ca_certs = Configuration().ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - # cert_file - cert_file = Configuration().cert_file - - # key file - key_file = Configuration().key_file - - # https pool manager - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=cert_file, - key_file=key_file - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, _request_timeout=None): - """ - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. - :param _request_timeout: timeout setting for this request. If one number provided, it will be total request - timeout. It can also be a pair (tuple) of (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): - timeout = urllib3.Timeout(total=_request_timeout) - elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: - timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) - - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if query_params: - url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): - request_body = None - if body: - request_body = json.dumps(body) - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct Content-Type - # which generated by urllib3 will be overwritten. - del headers['Content-Type'] - r = self.pool_manager.request(method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is provided - # in serialized form - elif isinstance(body, str): - request_body = body - r = self.pool_manager.request(method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided arguments. - Please check that your arguments match declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request(method, url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if PY3: - r.data = r.data.decode('utf8') - - # log response body - logger.debug("response body: %s", r.data) - - if r.status not in range(200, 206): - raise ApiException(http_resp=r) - - return r - - def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - -class ApiException(Exception): - - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """ - Custom error messages for exception - """ - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message diff --git a/deepaffects/smart_punctuation.py b/deepaffects/smart_punctuation.py new file mode 100644 index 0000000..419fc25 --- /dev/null +++ b/deepaffects/smart_punctuation.py @@ -0,0 +1,29 @@ +import logging +import requests + +class PunctApi(): + URL = 'https://proxy.api.deepaffects.com/text/generic/api/v1/async/punctuate' + API_KEY = None + def __init__(self, api_key): + if not api_key: + logging.error('"' + str(api_key) + '" is an invalid API key') + + PunctApi.API_KEY = api_key + + def async_text_punctuate(self, texts, webhook=None, request_id=None): + if not isinstance(texts, list): + logging.warn('Batching multiple texts is much faster than running one by one.') + texts = [texts] + + if not webhook: + logging.warn('Consider using webhooks for async requests.') + + params = {'apikey': PunctApi.API_KEY} + if webhook: + params['webhook'] = webhook + if request_id: + params['request_id'] = request_id + + output = requests.post(url=PunctApi.URL, json={'texts': texts}, params=params).json() + + return output \ No newline at end of file diff --git a/deepaffects/speaker_diarization.py b/deepaffects/speaker_diarization.py new file mode 100644 index 0000000..fddd759 --- /dev/null +++ b/deepaffects/speaker_diarization.py @@ -0,0 +1,85 @@ +import logging +import requests +import base64 + +PYAV = False +# try: +# import av +# PYAV = True +# except Exception as ex: +# logging.warn('Install https://github.com/mikeboers/PyAV for ease of use.') + +allowed_values = { + 'audioType': {'callcenter', 'meeting', 'earningscalls', 'interview', 'media-broadcast'} +} + +class DiarizationApi(): + URL = 'https://proxy.api.deepaffects.com/audio/generic/api/v2/async/diarize' + API_KEY = None + def __init__(self, api_key): + if not api_key: + logging.error('"' + str(api_key) + '" is an invalid API key') + + DiarizationApi.API_KEY = api_key + + def async_audio_diarize( + self, + audio_file_path=None, url=None, + encoding=None, sampleRate=None, + languageCode='en-US', separateSpeakerPerChannel=False, + speakerCount=-1, audioType='callcenter', + speakerIds=[], doVad=False, source=None, + webhook=None, request_id=None + ): + if not (audio_file_path or url): + logging.error("One of audio_file_path or url must be supplied.") + + if audio_file_path and url: + logging.error("Only one of audio_file_path and url must be supplied. Both cannot be true at the same time.") + + if not webhook: + logging.warn('Consider using webhooks for async requests.') + + if audioType not in allowed_values['audioType']: + logging.warn("The supplied audioType '" + str(audioType) + "' is not valid. Defaulting to audioType=callcenter") + audioType = 'callcenter' + + params = {'apikey': DiarizationApi.API_KEY} + if webhook: + params['webhook'] = webhook + if request_id: + params['request_id'] = request_id + + if not PYAV: + if not encoding: + logging.error("Encoding is not valid") + if not sampleRate: + logging.error("sampleRate is not valid") + + else: + pass + + request_json = {} + if audio_file_path: + content = open(audio_file_path, 'rb').read() + content = base64.b64encode(content).decode('utf-8') + request_json['content'] = content + + elif url: + request_json['url'] = url + + request_json['encoding'] = encoding + request_json['sampleRate'] = sampleRate + request_json['languageCode'] = languageCode + request_json['separateSpeakerPerChannel'] = separateSpeakerPerChannel + request_json['speakerCount'] = speakerCount + request_json['audioType'] = audioType + request_json['speakerIds'] = speakerIds + request_json['doVad'] = doVad + + if source: + request_json['source'] = source + + output = requests.post(url=DiarizationApi.URL, json=request_json, params=params).json() + + return output \ No newline at end of file diff --git a/deepaffects/speaker_enrollment.py b/deepaffects/speaker_enrollment.py new file mode 100644 index 0000000..08a1bd7 --- /dev/null +++ b/deepaffects/speaker_enrollment.py @@ -0,0 +1,53 @@ +import logging +import requests +import base64 + +PYAV = False +# try: +# import av +# PYAV = True +# except Exception as ex: +# logging.warn('Install https://github.com/mikeboers/PyAV for ease of use.') + +allowed_values = { + 'speaker_id': set('1234567890_qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM') +} + +class SpeakerEnroll(): + URL = 'https://proxy.api.deepaffects.com/audio/generic/api/v2/sync/diarization/enroll' + API_KEY = None + def __init__(self, api_key): + if not api_key: + logging.error('"' + str(api_key) + '" is an invalid API key') + + SpeakerEnroll.API_KEY = api_key + + def enroll_speaker( + self, + audio_file_path=None, + encoding=None, sampleRate=None, + languageCode='en-US', + speakerId=None + ): + if not (audio_file_path and speakerId): + logging.error("audio_file_path must be supplied.") + + if [c for c in speakerId if c not in allowed_values['speaker_id']]: + logging.error("Only english alphabet, numbers and _ are allowed in speakerId") + + params = {'apikey': SpeakerEnroll.API_KEY} + + request_json = {} + if audio_file_path: + content = open(audio_file_path, 'rb').read() + content = base64.b64encode(content).decode('utf-8') + request_json['content'] = content + + request_json['encoding'] = encoding + request_json['sampleRate'] = sampleRate + request_json['languageCode'] = languageCode + request_json['speakerId'] = speakerId + + output = requests.post(url=SpeakerEnroll.URL, json=request_json, params=params).json() + + return output \ No newline at end of file diff --git a/deepaffects/text_emotion_recognition.py b/deepaffects/text_emotion_recognition.py new file mode 100644 index 0000000..12e5d8e --- /dev/null +++ b/deepaffects/text_emotion_recognition.py @@ -0,0 +1,24 @@ +import logging +import requests + +class EmotionApi(): + URL = 'https://proxy.api.deepaffects.com/text/generic/api/latest/sync/text_recognise_emotion' + API_KEY = None + def __init__(self, api_key): + if not api_key: + logging.error('"' + str(api_key) + '" is an invalid API key') + + EmotionApi.API_KEY = api_key + + def sync_text_recognise_emotion(self, texts): + if not isinstance(texts, list): + logging.warn('Batching multiple texts is much faster than running one by one.') + + output = requests.post( + url=EmotionApi.URL, + json={'content': texts}, + params={'apikey': EmotionApi.API_KEY} + ).json() + + return output + diff --git a/deepaffects/voice_activity_detection.py b/deepaffects/voice_activity_detection.py new file mode 100644 index 0000000..b631e5b --- /dev/null +++ b/deepaffects/voice_activity_detection.py @@ -0,0 +1,68 @@ +import logging +import requests +import base64 + +PYAV = False +# try: +# import av +# PYAV = True +# except Exception as ex: +# logging.warn('Install https://github.com/mikeboers/PyAV for ease of use.') + +class VADApi(): + URL = 'https://proxy.api.deepaffects.com/audio/generic/api/v1/async/vad' + API_KEY = None + def __init__(self, api_key): + if not api_key: + logging.error('"' + str(api_key) + '" is an invalid API key') + + VADApi.API_KEY = api_key + + def async_voice_activity_detect( + self, + audio_file_path=None, url=None, + encoding=None, sampleRate=None, + languageCode='en-US', minNonSpeechDuration=0, + webhook=None, request_id=None + ): + if not (audio_file_path or url): + logging.error("One of audio_file_path or url must be supplied.") + + if audio_file_path and url: + logging.error("Only one of audio_file_path and url must be supplied. Both cannot be true at the same time.") + + if not webhook: + logging.warn('Consider using webhooks for async requests.') + + params = {'apikey': VADApi.API_KEY} + if webhook: + params['webhook'] = webhook + if request_id: + params['request_id'] = request_id + + if not PYAV: + if not encoding: + logging.error("Encoding is not valid") + if not sampleRate: + logging.error("sampleRate is not valid") + + else: + pass + + request_json = {} + if audio_file_path: + content = open(audio_file_path, 'rb').read() + content = base64.b64encode(content).decode('utf-8') + request_json['content'] = content + + elif url: + request_json['url'] = url + + request_json['encoding'] = encoding + request_json['sampleRate'] = sampleRate + request_json['languageCode'] = languageCode + request_json['minNonSpeechDuration'] = minNonSpeechDuration + + output = requests.post(url=VADApi.URL, json=request_json, params=params).json() + + return output \ No newline at end of file diff --git a/docs/AsyncResponse.md b/docs/AsyncResponse.md deleted file mode 100644 index 9fd38f5..0000000 --- a/docs/AsyncResponse.md +++ /dev/null @@ -1,11 +0,0 @@ -# AsyncResponse - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**request_id** | **str** | Unique identifier for the api call | -**api** | **str** | API hit | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/Audio.md b/docs/Audio.md deleted file mode 100644 index 3889982..0000000 --- a/docs/Audio.md +++ /dev/null @@ -1,13 +0,0 @@ -# Audio - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**encoding** | **str** | Encoding of audio file like MP3, WAV etc. | -**sample_rate** | **int** | Sample rate of the audio file. | -**language_code** | **str** | Language spoken in the audio file. | [default to 'en-US'] -**content** | **str** | base64 encoding of the audio file. | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/DenoiseApi.md b/docs/DenoiseApi.md deleted file mode 100644 index c326b33..0000000 --- a/docs/DenoiseApi.md +++ /dev/null @@ -1,113 +0,0 @@ -# deepaffects.DenoiseApi - -All URIs are relative to *https://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**async_denoise_audio**](DenoiseApi.md#async_denoise_audio) | **POST** /api/v1/async/denoise | Denoise an audio file -[**sync_denoise_audio**](DenoiseApi.md#sync_denoise_audio) | **POST** /api/v1/sync/denoise | Denoise an audio file - - -# **async_denoise_audio** -> AsyncResponse async_denoise_audio(body, webhook, request_id=request_id) - -Denoise an audio file. - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.DenoiseApi() -body = deepaffects.Audio.from_file(file_name="/path/to/file") # Audio | Audio object that needs to be denoised. -webhook = 'webhook_example' # str | The webhook url where result from async resource is posted -request_id = 'request_id_example' # str | Unique identifier for the request (optional) - -try: - # Denoise an audio file - api_response = api_instance.async_denoise_audio(body, webhook, request_id=request_id) - pprint(api_response) -except ApiException as e: - print("Exception when calling DenoiseApi->async_denoise_audio: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Audio**](Audio.md)| Audio object that needs to be denoised. | - **webhook** | **str**| The webhook url where result from async resource is posted | - **request_id** | **str**| Unique identifier for the request | [optional] - -### Return type - -[**AsyncResponse**](AsyncResponse.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **sync_denoise_audio** -> Audio sync_denoise_audio(body) - -Denoise an audio file - - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.DenoiseApi() -body = deepaffects.Audio.from_file(file_name="/path/to/file") # Audio | Audio object that needs to be denoised. - -try: - # Denoise an audio file - api_response = api_instance.sync_denoise_audio(body) - pprint(api_response) -except ApiException as e: - print("Exception when calling DenoiseApi->sync_denoise_audio: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Audio**](Audio.md)| Audio object that needs to be denoised. | - -### Return type - -[**Audio**](Audio.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/docs/DiarizeApi.md b/docs/DiarizeApi.md deleted file mode 100644 index 0e63b02..0000000 --- a/docs/DiarizeApi.md +++ /dev/null @@ -1,114 +0,0 @@ -# deepaffects.DiarizeApi - -All URIs are relative to *https://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**async_diarize_audio**](DiarizeApi.md#async_diarize_audio) | **POST** /api/v1/async/diarize | Diarize an audio file -[**sync_diarize_audio**](DiarizeApi.md#sync_diarize_audio) | **POST** /api/v1/sync/diarize | Diarize an audio file - - -# **async_diarize_audio** -> AsyncResponse async_diarize_audio(body, webhook, request_id=request_id) - -Diarize an audio file. - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.DiarizeApi() -body = deepaffects.DiarizeAudio.from_file(file_name="/path/to/file") # Audio | Audio object that needs to be diarized. -webhook = 'https://your_webhook.url' # str | The webhook url where result from async resource is posted -request_id = 'request_id_example' # str | Unique identifier for the request (optional) - -try: - # Diarize an audio file - api_response = api_instance.async_diarize_audio(body, webhook, request_id=request_id) - pprint(api_response) -except ApiException as e: - print("Exception when calling DiarizeApi->async_diarize_audio: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**DiarizeAudio**](DiarizeAudio.md)| Audio object that needs to be diarized. | - **webhook** | **str**| The webhook url where result from async resource is posted | - **request_id** | **str**| Unique identifier for the request | [optional] - -### Return type - -[**AsyncResponse**](AsyncResponse.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **sync_diarize_audio** -> list[Audio] sync_diarize_audio(body) - -Diarize an audio file - -Diarize an audio file. - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.DiarizeApi() -body = deepaffects.DiarizeAudio.from_file(file_name="/path/to/file") # Audio | Audio object that needs to be diarized. - -try: - # Diarize an audio file - api_response = api_instance.sync_diarize_audio(body) - pprint(api_response) -except ApiException as e: - print("Exception when calling DiarizeApi->sync_diarize_audio: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**DiarizeAudio**](DiarizeAudio.md)| Audio object that needs to be diarized. | - -### Return type - -[**list[Audio]**](Audio.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/docs/DiarizeApiV2.md b/docs/DiarizeApiV2.md deleted file mode 100644 index 067c2d2..0000000 --- a/docs/DiarizeApiV2.md +++ /dev/null @@ -1,60 +0,0 @@ -# deepaffects.DiarizeApi - -All URIs are relative to *https://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**async_diarize_audio**](DiarizeApiV2.md#async_diarize_audio) | **POST** /api/v1/async/diarize | Diarize an audio file - - -# **async_diarize_audio** -> AsyncResponse async_diarize_audio(body, webhook, request_id=request_id) - -Diarize an audio file. - -### Example -```python -from __future__ import print_function -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.DiarizeApiV2() -body = deepaffects.DiarizeAudio.from_file(file_name="/path/to/file") # DiarizeAudio | audio object that needs to be diarized. -webhook = 'https://your_webhook.url' # str | The webhook url where result from async resource is posted -request_id = 'request_id_example' # str | Unique identifier for the request (optional) - -try: - # Diarize an audio file - api_response = api_instance.async_diarize_audio(body, webhook, request_id=request_id) - pprint(api_response) -except ApiException as e: - print("Exception when calling DiarizeApi->async_diarize_audio: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**DiarizeAudio**](DiarizeAudio.md)| Audio object that needs to be diarized. | - **webhook** | **str**| The webhook url where result from async resource is posted | - **request_id** | **str**| Unique identifier for the request | [optional] - -### Return type - -[**AsyncResponse**](AsyncResponse.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/docs/DiarizeAudio.md b/docs/DiarizeAudio.md deleted file mode 100644 index 86d3a8c..0000000 --- a/docs/DiarizeAudio.md +++ /dev/null @@ -1,14 +0,0 @@ -# DiarizeAudio - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**encoding** | **str** | Encoding of audio file like MP3, WAV etc. | -**sample_rate** | **int** | Sample rate of the audio file. | -**language_code** | **str** | Language spoken in the audio file. | [default to 'en-US'] -**content** | **str** | base64 encoding of the audio file. | -**speakers** | **int** | Number of speakers in the file (-1 for unknown speakers) | [default to -1] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/EllipsisApi.md b/docs/EllipsisApi.md deleted file mode 100644 index 7c500c7..0000000 --- a/docs/EllipsisApi.md +++ /dev/null @@ -1,59 +0,0 @@ -# deepaffects.EllipsisApi - -All URIs are relative to *https://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**is_depressed**](EllipsisApi.md#is_depressed) | **POST** /api/v1/audio/ellipsis/is_depressed | Find if a person is depressed from audio. - - -# **is_depressed** -> bool is_depressed(body) - -Find if a person is depressed from audio. - - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.EllipsisAPI() -body = deepaffects.Audio.from_file(file_name="/path/to/file") # Audio | Audio object to predict depression. - -try: - # Find if a person is depressed from audio. - api_response = api_instance.sync_is_depressed(body) - pprint(api_response) -except ApiException as e: - print("Exception when calling EllipsisApi->is_depressed: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Audio**](Audio.md)| Audio object that needs to be featurized. | - -### Return type - -**bool** - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/docs/EmotionApi.md b/docs/EmotionApi.md deleted file mode 100644 index 5805fc2..0000000 --- a/docs/EmotionApi.md +++ /dev/null @@ -1,116 +0,0 @@ -# deepaffects.EmotionApi - -All URIs are relative to *https://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**async_recognise_emotion**](EmotionApi.md#async_recognise_emotion) | **POST** /api/v1/async/recognise_emotion | Find emotion in an audio file -[**sync_recognise_emotion**](EmotionApi.md#sync_recognise_emotion) | **POST** /api/v1/sync/recognise_emotion | Find emotion in an audio file - - -# **async_recognise_emotion** -> AsyncResponse async_recognise_emotion(body, webhook, request_id=request_id) - -Find emotion in an audio file - -Extract emotion from an audio file. - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.EmotionApi() -body = deepaffects.Audio.from_file(file_name="/path/to/file") # Audio | Audio object to extract emotions from. -webhook = 'https://your_webhook.url' # str | The webhook url where result from async resource is posted -request_id = 'request_id_example' # str | Unique identifier for the request (optional) - -try: - # Find emotion in an audio file - api_response = api_instance.async_recognise_emotion(body, webhook, request_id=request_id) - pprint(api_response) -except ApiException as e: - print("Exception when calling EmotionApi->async_recognise_emotion: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Audio**](Audio.md)| Audio object that needs to be featurized. | - **webhook** | **str**| The webhook url where result from async resource is posted | - **request_id** | **str**| Unique identifier for the request | [optional] - -### Return type - -[**AsyncResponse**](AsyncResponse.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **sync_recognise_emotion** -> list[EmotionScore] sync_recognise_emotion(body) - -Find emotion in an audio file - -Extract emotion from an audio file. - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.EmotionApi() -body = deepaffects.Audio.from_file(file_name="/path/to/file") # Audio | Audio object to extract emotions from. - -try: - # Find emotion in an audio file - api_response = api_instance.sync_recognise_emotion(body) - pprint(api_response) -except ApiException as e: - print("Exception when calling EmotionApi->sync_recognise_emotion: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Audio**](Audio.md)| Audio object that needs to be featurized. | - -### Return type - -[**list[EmotionScore]**](EmotionScore.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/docs/EmotionScore.md b/docs/EmotionScore.md deleted file mode 100644 index 9e84225..0000000 --- a/docs/EmotionScore.md +++ /dev/null @@ -1,16 +0,0 @@ -# EmotionScore - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**happy** | **float** | Probability of happy emotion | [optional] -**angry** | **float** | Probability of angry emotion | [optional] -**sad** | **float** | Probability of sad emotion | [optional] -**disgust** | **float** | Probability of disgust emotion | [optional] -**pleasant** | **float** | Probability of pleasant emotion | [optional] -**neutral** | **float** | Probability of neutral emotion | [optional] -**fear** | **float** | Probability of fear emotion | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/FeaturizeApi.md b/docs/FeaturizeApi.md deleted file mode 100644 index e3786c2..0000000 --- a/docs/FeaturizeApi.md +++ /dev/null @@ -1,116 +0,0 @@ -# deepaffects.FeaturizeApi - -All URIs are relative to *https://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**async_featurize_audio**](FeaturizeApi.md#async_featurize_audio) | **POST** /api/v1/async/featurize | featurize an audio file -[**sync_featurize_audio**](FeaturizeApi.md#sync_featurize_audio) | **POST** /api/v1/sync/featurize | featurize an audio file - - -# **async_featurize_audio** -> AsyncResponse async_featurize_audio(body, webhook, request_id=request_id) - -featurize an audio file - -Extract paralinguistic feature from an audio file. - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.FeaturizeApi() -body = deepaffects.Audio.from_file('/path/to/file') # Audio | Audio object that needs to be featurized. -webhook = 'webhook_example' # str | The webhook url where result from async resource is posted -request_id = 'request_id_example' # str | Unique identifier for the request (optional) - -try: - # featurize an audio file - api_response = api_instance.async_featurize_audio(body, webhook, request_id=request_id) - pprint(api_response) -except ApiException as e: - print("Exception when calling FeaturizeApi->async_featurize_audio: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Audio**](Audio.md)| Audio object that needs to be featurized. | - **webhook** | **str**| The webhook url where result from async resource is posted | - **request_id** | **str**| Unique identifier for the request | [optional] - -### Return type - -[**AsyncResponse**](AsyncResponse.md) - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **sync_featurize_audio** -> list[list[float]] sync_featurize_audio(body) - -featurize an audio file - -Extract paralinguistic feature from an audio file. - -### Example -```python -from __future__ import print_function -import time -import deepaffects -from deepaffects.rest import ApiException -from pprint import pprint - -# Configure API key authorization: UserSecurity -deepaffects.configuration.api_key['apikey'] = 'YOUR_API_KEY' - -# create an instance of the API class -api_instance = deepaffects.FeaturizeApi() -body = deepaffects.Audio.from_file('/path/to/file') # Audio | Audio object that needs to be featurized. - -try: - # featurize an audio file - api_response = api_instance.sync_featurize_audio(body) - pprint(api_response) -except ApiException as e: - print("Exception when calling FeaturizeApi->sync_featurize_audio: %s\n" % e) -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Audio**](Audio.md)| Audio object that needs to be featurized. | - -### Return type - -**list[list[float]]** - -### Authorization - -[UserSecurity](../README.md#UserSecurity) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/examples/diarize_emotion_example.py b/examples/diarize_emotion_example.py deleted file mode 100644 index 03a055f..0000000 --- a/examples/diarize_emotion_example.py +++ /dev/null @@ -1,67 +0,0 @@ -from deepaffects.realtime.util import get_deepaffects_client, chunk_generator_from_file, chunk_generator_from_url - -TIMEOUT_SECONDS = 10000 -apikey = "YOUR_API_KEY" -file_path = "FILE_PATH" -is_youtube_url = False -languageCode = "en-Us" -sampleRate = "16000" -encoding = "wav" -speakerIds = "list of userids for for speaker verification seperated by ','" -verbose = "True" -# DeepAffects realtime Api client -client = get_deepaffects_client() - -metadata = [ - ('apikey', apikey), - ('encoding', encoding), - ('speakerids', speakerIds), - ('samplerate', sampleRate), - ('languagecode', languageCode), - ('verbose', verbose) -] - -# Implement chunk_generator() is a generator function which yields segment_chunk objects asynchronously -# from deepaffects.realtime.types import segment_chunk -# yield segment_chunk(Args) -"""segment_chunk. - -Args: - encoding : Audio Encoding, - languageCode: language code , - sampleRate: sample rate of audio , - content: base64 encoded audio, - segmentOffset: offset of the segment in complete audio stream -""" - -""" -Sample implementation which reads audio from a file and splits it into -segments more than 3 sec -AudioSegment and yields base64 encoded audio segment objects asynchronously -""" - -"""Stream audio from url or youtube. - -responses = client.DiarizeEmotion( - chunk_generator_from_url(file_path, is_youtube_url=is_youtube_url), TIMEOUT_SECONDS, metadata=metadata) -""" - -"""Stream audio from local file. -""" -responses = client.DiarizeEmotion( - chunk_generator_from_file(file_path), TIMEOUT_SECONDS, metadata=metadata) - - -# responses is the iterator for all the response values -for response in responses: - print("Received message") - print(response) - -"""Response. - response = { - userId: userId of the speaker identified in the segment, - emotion: Emotion identified in the segment, - start: start of the segment, - end: end of the segment - } -""" diff --git a/examples/emotion_identify_example.py b/examples/emotion_identify_example.py deleted file mode 100644 index cd4e114..0000000 --- a/examples/emotion_identify_example.py +++ /dev/null @@ -1,62 +0,0 @@ -from deepaffects.realtime.util import get_deepaffects_client, chunk_generator_from_file, chunk_generator_from_url - -TIMEOUT_SECONDS = 10000 -apikey = "YOUR_API_KEY" -file_path = "FILE_PATH" -is_youtube_url = False -languageCode = "en-Us" -sampleRate = "16000" -encoding = "wav" - -# DeepAffects realtime Api client -client = get_deepaffects_client() - -metadata = [ - ('apikey', apikey), - ('encoding', encoding), - ('samplerate', sampleRate), - ('languagecode', languageCode) -] - -# Implement chunk_generator() is a generator function which yields segment_chunk objects asynchronously -# from deepaffects.realtime.types import segment_chunk -# yield segment_chunk(Args) -"""segment_chunk. - -Args: - encoding : Audio Encoding, - languageCode: language code , - sampleRate: sample rate of audio , - content: base64 encoded audio, - segmentOffset: offset of the segment in complete audio stream -""" - -""" -Sample implementation which reads audio from a file and splits it into -segments more than 3 sec -AudioSegment and yields base64 encoded audio segment objects asynchronously -""" - -"""Stream audio from url or youtube. - -responses = client.IdentifyEmotion( - chunk_generator_from_url(file_path, is_youtube_url=is_youtube_url), TIMEOUT_SECONDS, metadata=metadata) -""" - -"""Stream audio from local file. -""" -responses = client.IdentifyEmotion( - chunk_generator_from_file(file_path), TIMEOUT_SECONDS, metadata=metadata) - -# responses is the iterator for all the response values -for response in responses: - print("Received message") - print(response) - -"""Response. - response = { - emotion: Emotion identified in the segment, - start: start of the segment, - end: end of the segment - } -""" diff --git a/examples/playlist_chunk_generator.py b/examples/playlist_chunk_generator.py deleted file mode 100644 index ff8bbd6..0000000 --- a/examples/playlist_chunk_generator.py +++ /dev/null @@ -1,53 +0,0 @@ -from deepaffects.realtime.util import get_deepaffects_client, chunk_generator_from_file, chunk_generator_from_url, chunk_generator_from_playlist - -TIMEOUT_SECONDS = 10000 -apikey = "YOUR_API_KEY" -file_path = "PLAYLIST_PATH" -speakerIds = "list of userids for for speaker verification seperated by ','" -verbose = "True" - -# DeepAffects realtime Api client -client = get_deepaffects_client() - -metadata = [ - ('apikey', apikey), - ('speakerids', speakerIds), - ('verbose', verbose) -] - -# Implement chunk_generator() is a generator function which yields segment_chunk objects asynchronously -# from deepaffects.realtime.types import segment_chunk -# yield segment_chunk(Args) -"""segment_chunk. - -Args: - encoding : Audio Encoding, - languageCode: language code , - sampleRate: sample rate of audio , - content: base64 encoded audio, - segmentOffset: offset of the segment in complete audio stream -""" - -""" -Sample implementation which reads audio from a file and splits it into -segments more than 3 sec -AudioSegment and yields base64 encoded audio segment objects asynchronously -""" - -"""Stream audio from earningcast. -""" -responses = client.DiarizeEmotion( - chunk_generator_from_playlist(file_path), TIMEOUT_SECONDS, metadata=metadata) - -# responses is the iterator for all the response values -for response in responses: - print("Received message") - print(response) - -"""Response. - response = { - emotion: Emotion identified in the segment, - start: start of the segment, - end: end of the segment - } -""" diff --git a/examples/speaker_identify_example.py b/examples/speaker_identify_example.py deleted file mode 100644 index fcfd6da..0000000 --- a/examples/speaker_identify_example.py +++ /dev/null @@ -1,51 +0,0 @@ -from deepaffects.realtime.util import get_deepaffects_client, chunk_generator_from_file, chunk_generator_from_url - -TIMEOUT_SECONDS = 10000 -apikey = "YOUR_API_KEY" -file_path = "FILE_PATH" -is_youtube_url = False -languageCode = "en-Us" -sampleRate = "16000" -encoding = "wav" -apiVersion = "v2" -speakerIds = "list of userids for for speaker verification seperated by ','" -verbose = "True" - -# DeepAffects realtime Api client -client = get_deepaffects_client() - -# chunk_generator() is a generator function which yields audio segment object asynchronously -metadata = [ - ('apikey', apikey), - ('speakerids', speakerIds), - ('encoding', encoding), - ('samplerate', sampleRate), - ('languagecode', languageCode), - ('apiversion', apiVersion), - ('verbose', verbose) -] - -"""Stream audio from url or youtube. - -responses = client.IdentifySpeaker( - chunk_generator_from_url(file_path, is_youtube_url=is_youtube_url), TIMEOUT_SECONDS, metadata=metadata) -""" - -"""Stream audio from local file. -""" -responses = client.IdentifySpeaker( - chunk_generator_from_file(file_path), TIMEOUT_SECONDS, metadata=metadata) - -# responses is the iterator for all the response values -for response in responses: - print("Received message") - print(response) - -"""Response. - - response = { - userId: userId of the speaker identified in the segment, - start: start of the segment, - end: end of the segment - } -""" diff --git a/examples/ticker_based_earnings_call_identification.py b/examples/ticker_based_earnings_call_identification.py deleted file mode 100644 index 8356ac4..0000000 --- a/examples/ticker_based_earnings_call_identification.py +++ /dev/null @@ -1,54 +0,0 @@ -from deepaffects.realtime.util import get_deepaffects_client, chunk_generator_from_file, chunk_generator_from_url, chunk_generator_from_playlist - -TIMEOUT_SECONDS = 10000 -apikey = "YOUR_API_KEY" -file_path = "PLAYLIST_PATH" -ticker = "TICKER_SYMBOL" -out_file_name = "OUT_FILE_NAME" -verbose = "True" - -metadata = [ - ('apikey', apikey), - ('ticker', ticker), - ('verbose', verbose) -] - -# Implement chunk_generator() is a generator function which yields segment_chunk objects asynchronously -# from deepaffects.realtime.types import segment_chunk -# yield segment_chunk(Args) -"""segment_chunk. - -Args: - encoding : Audio Encoding, - languageCode: language code , - sampleRate: sample rate of audio , - content: base64 encoded audio, - segmentOffset: offset of the segment in complete audio stream -""" - -""" -Sample implementation which reads audio from a file and splits it into -segments more than 3 sec -AudioSegment and yields base64 encoded audio segment objects asynchronously -""" - -"""Stream audio from earningcast. -""" -# DeepAffects realtime Api client -client = get_deepaffects_client() - -responses = client.DiarizeEmotion( - chunk_generator_from_playlist(out_file_name=out_file_name, file_path=file_path), TIMEOUT_SECONDS, metadata=metadata) - -# responses is the iterator for all the response values -for response in responses: - print("Received message") - print(response) - -"""Response. - response = { - emotion: Emotion identified in the segment, - start: start of the segment, - end: end of the segment - } -""" diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 65b6dc9..0000000 --- a/requirements.txt +++ /dev/null @@ -1,12 +0,0 @@ -certifi >= 14.05.14 -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.15.1 -pymediainfo >= 2.1.9 -pydub==0.22.1 -six==1.11.0 -grpcio==1.13.0 -protobuf==3.6.0 -pytube==9.2.2 -m3u8==0.3.6 -requests==2.19.1 \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 8dfb393..0000000 --- a/setup.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - - -from setuptools import setup, find_packages -import os - -NAME = "deepaffects" -VERSION = "1.4.1" -# To install the library, run the following -# -# python setup.py install -# -# prerequisite: setuptools -# http://pypi.python.org/pypi/setuptools - -REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil", "pymediainfo >= 2.1.9", "grpcio==1.13.0", - "protobuf==3.6.0", "pydub==0.22.1", "pytube==9.2.2"] - - -def readme(): - with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: - return readme.read() - -setup( - name=NAME, - version=VERSION, - description="Python bindings for DeepAffects APIs", - author_email="support@seernet.io", - url="https://github.com/SEERNET/deepaffects-python", - author="Sushant Hiray, Venkatesh Duppada", - setup_requires=[ - "six >= 1.3.0", - "pillow >= 2.8.1" - ], - install_requires=REQUIRES, - packages=find_packages(), - include_package_data=True, - long_description=readme(), - long_description_content_type="text/markdown" -) diff --git a/test-requirements.txt b/test-requirements.txt deleted file mode 100644 index 2702246..0000000 --- a/test-requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -coverage>=4.0.3 -nose>=1.3.7 -pluggy>=0.3.1 -py>=1.4.31 -randomize>=0.13 diff --git a/test/__init__.py b/test/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/test/data/clean.wav b/test/data/clean.wav deleted file mode 100644 index 9e6db22..0000000 Binary files a/test/data/clean.wav and /dev/null differ diff --git a/test/data/happy.mp3 b/test/data/happy.mp3 deleted file mode 100644 index d70580b..0000000 Binary files a/test/data/happy.mp3 and /dev/null differ diff --git a/test/data/noisy.wav b/test/data/noisy.wav deleted file mode 100644 index 53c982a..0000000 Binary files a/test/data/noisy.wav and /dev/null differ diff --git a/test/data/reconstructed.wav b/test/data/reconstructed.wav deleted file mode 100644 index fb3c9ec..0000000 Binary files a/test/data/reconstructed.wav and /dev/null differ diff --git a/test/test_async_response.py b/test/test_async_response.py deleted file mode 100644 index 51741cf..0000000 --- a/test/test_async_response.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: 0.1.0 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects.rest import ApiException -from deepaffects.models.async_response import AsyncResponse - - -class TestAsyncResponse(unittest.TestCase): - """ AsyncResponse unit test stubs """ - - def setUp(self): - pass - - def tearDown(self): - pass - - def testAsyncResponse(self): - """ - Test AsyncResponse - """ - model = deepaffects.models.async_response.AsyncResponse() - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_audio.py b/test/test_audio.py deleted file mode 100644 index f7b54ba..0000000 --- a/test/test_audio.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects.rest import ApiException -from deepaffects.models.audio import Audio - - -class TestAudio(unittest.TestCase): - """ Audio unit test stubs """ - - def setUp(self): - pass - - def tearDown(self): - pass - - def testAudio(self): - """ - Test Audio - """ - model = deepaffects.models.audio.Audio() - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_base_setup.py b/test/test_base_setup.py deleted file mode 100644 index 6b8a059..0000000 --- a/test/test_base_setup.py +++ /dev/null @@ -1,28 +0,0 @@ -import os -from unittest import TestCase, SkipTest - -import deepaffects - -DIR = os.path.dirname(os.path.realpath(__file__)) - -class AudioTest(TestCase): - def initialize_api(self): - pass - - def setUp(self): - self.api_key = os.getenv("DEEPAFFECTS_API_KEY") - if not self.api_key: - raise ValueError( - "API Key needs to be defined in an environment variable DEEPAFFECTS_API_KEY to run tests." - ) - deepaffects.configuration.api_key = self.api_key - self.initialize_api() - - @staticmethod - def _require_numpy(): - try: - import numpy as np - return np - except ImportError: - raise SkipTest("Numpy is not installed!") - diff --git a/test/test_denoise_api.py b/test/test_denoise_api.py deleted file mode 100644 index a6be930..0000000 --- a/test/test_denoise_api.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects.models.audio import Audio -from .test_base_setup import DIR - - -class TestDenoiseApi(unittest.TestCase): - """ DenoiseApi unit test stubs """ - - @staticmethod - def sdr(clean, reconstructed): - # TODO: Implement SDR here - return 5.1 - - def setUp(self): - deepaffects.configuration.api_key['apikey'] = os.environ['DEEPAFFECTS_API_KEY'] - self.api = deepaffects.DenoiseApi() - - def tearDown(self): - pass - - def test_sync_denoise_audio(self): - """ - Test case for sync_denoise_audio - - Denoise an audio file - """ - test_noisy_audio = os.path.normpath(os.path.join(DIR, "data/noisy.wav")) - test_clean_audio = os.path.normpath(os.path.join(DIR, "data/clean.wav")) - test_reconstructed_audio = os.path.normpath(os.path.join(DIR, "data/reconstructed.wav")) - body = Audio.from_file(file_name=test_noisy_audio) - api_response = self.api.sync_denoise_audio(body=body) - api_response.to_file(test_reconstructed_audio) - self.assertTrue(TestDenoiseApi.sdr(test_clean_audio, test_reconstructed_audio) > 5) - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_diarize_api.py b/test/test_diarize_api.py deleted file mode 100644 index 1e91cb9..0000000 --- a/test/test_diarize_api.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects.rest import ApiException -from deepaffects.apis.diarize_api import DiarizeApi - - -class TestDiarizeApi(unittest.TestCase): - """ DiarizeApi unit test stubs """ - - def setUp(self): - self.api = deepaffects.apis.diarize_api.DiarizeApi() - - def tearDown(self): - pass - - def test_async_diarize_audio(self): - """ - Test case for diarize_audio - - Diarize an audio file - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_diarize_api_v2.py b/test/test_diarize_api_v2.py deleted file mode 100644 index 2425bdb..0000000 --- a/test/test_diarize_api_v2.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects import Audio -from deepaffects.rest import ApiException -from deepaffects.apis.diarize_api_v2 import DiarizeApiV2 -from .test_base_setup import DIR -import uuid - - -class TestDiarizeApiV2(unittest.TestCase): - """ DiarizeApiV2 unit test stubs """ - - def setUp(self): - deepaffects.configuration.api_key['apikey'] = os.environ['DEEPAFFECTS_API_KEY'] - self.webhook_url = os.environ["DEEPAFFECTS_API_WEBHOOK"] - self.api = deepaffects.apis.diarize_api_v2.DiarizeApiV2() - self.request_id = str(uuid.uuid4()) - - def tearDown(self): - pass - - def test_async_diarize_audio(self): - """ - Test case for diarize_audio - - Diarize an audio file - """ - test_conversation_audio = os.path.normpath(os.path.join(DIR, "data/happy.mp3")) - body = Audio.from_file(file_name=test_conversation_audio) - - api_response = self.api.async_diarize_audio(body=body, webhook=self.webhook_url, request_id=self.request_id) - self.assertTrue(api_response.request_id, self.request_id) - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_diarize_audio.py b/test/test_diarize_audio.py deleted file mode 100644 index c5e7794..0000000 --- a/test/test_diarize_audio.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects.rest import ApiException -from deepaffects.models.diarize_audio import DiarizeAudio - - -class TestDiarizeAudio(unittest.TestCase): - """ DiarizeAudio unit test stubs """ - - def setUp(self): - pass - - def tearDown(self): - pass - - def testDiarizeAudio(self): - """ - Test DiarizeAudio - """ - model = deepaffects.models.diarize_audio.DiarizeAudio() - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_emotion_api.py b/test/test_emotion_api.py deleted file mode 100644 index 932f283..0000000 --- a/test/test_emotion_api.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: v1 -""" - -from __future__ import absolute_import - -import os -import sys -import unittest - -from deepaffects import Audio - -import deepaffects -from deepaffects.rest import ApiException -from deepaffects.apis.emotion_api import EmotionApi -from deepaffects.models.emotion_score import EmotionScore -from .test_base_setup import DIR, AudioTest - - -class TestEmotionApi(unittest.TestCase): - """ EmotionApi unit test stubs """ - - def setUp(self): - deepaffects.configuration.api_key['apikey'] = os.environ['DEEPAFFECTS_API_KEY'] - self.api = deepaffects.apis.emotion_api.EmotionApi() - - def tearDown(self): - pass - - def test_async_recognise_emotion(self): - """ - Test case for async_recognise_emotion - - Find emotion in an audio file - """ - pass - - def test_sync_recognise_emotion(self): - """ - Test case for sync_recognise_emotion - - Find emotion in an audio file - """ - test_happy_audio = os.path.normpath(os.path.join(DIR, "data/happy.mp3")) - body = Audio.from_file(file_name=test_happy_audio) - api_response = self.api.sync_recognise_emotion(body=body) - for obj in api_response: - if obj.emotion == 'Happy': - assert obj.score > 0.8 - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_emotion_score.py b/test/test_emotion_score.py deleted file mode 100644 index 3778a9e..0000000 --- a/test/test_emotion_score.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects.rest import ApiException -from deepaffects.models.emotion_score import EmotionScore - - -class TestEmotionScore(unittest.TestCase): - """ EmotionScore unit test stubs """ - - def setUp(self): - pass - - def tearDown(self): - pass - - def testEmotionScore(self): - """ - Test EmotionScore - """ - model = deepaffects.models.emotion_score.EmotionScore() - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_featurize_api.py b/test/test_featurize_api.py deleted file mode 100644 index 8a41d98..0000000 --- a/test/test_featurize_api.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - DeepAffects - - OpenAPI Specification of DeepAffects APIs - - OpenAPI spec version: v1 -""" - - -from __future__ import absolute_import - -import os -import sys -import unittest - -import deepaffects -from deepaffects.rest import ApiException -from deepaffects.apis.featurize_api import FeaturizeApi - - -class TestFeaturizeApi(unittest.TestCase): - """ FeaturizeApi unit test stubs """ - - def setUp(self): - self.api = deepaffects.apis.featurize_api.FeaturizeApi() - - def tearDown(self): - pass - - def test_async_featurize_audio(self): - """ - Test case for featurize_audio - - featurize an audio file - """ - pass - - -if __name__ == '__main__': - unittest.main()