partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
convert_to_theano_var
Convert neural vars to theano vars. :param obj: NeuralVariable or list or dict or tuple :return: theano var, test var, tensor found, neural var found
deepy/core/tensor_conversion.py
def convert_to_theano_var(obj): """ Convert neural vars to theano vars. :param obj: NeuralVariable or list or dict or tuple :return: theano var, test var, tensor found, neural var found """ from deepy.core.neural_var import NeuralVariable if type(obj) == tuple: return tuple(convert_to_theano_var(list(obj))) if type(obj) == list: unpacked_list = map(convert_to_theano_var, obj) normal_list = [] test_list = [] theano_var_found = False neural_var_found = False for normal_var, tensor_found, neural_found in unpacked_list: normal_list.append(normal_var) if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return normal_list, theano_var_found, neural_var_found elif type(obj) == dict: normal_map = {} theano_var_found = False neural_var_found = False for key in obj: normal_var, tensor_found, neural_found = convert_to_theano_var(obj[key]) normal_map[key] = normal_var if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return normal_map, theano_var_found, neural_var_found elif type(obj) == MapDict: normal_map = {} theano_var_found = False neural_var_found = False for key in obj: normal_var, tensor_found, neural_found = convert_to_theano_var(obj[key]) normal_map[key] = normal_var if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return MapDict(normal_map), theano_var_found, neural_var_found elif type(obj) == NeuralVariable: theano_tensor = obj.tensor theano_tensor.tag.last_dim = obj.dim() return theano_tensor, False, True elif type(obj) == TensorVariable: return obj, True, False elif type(obj) == slice: normal_args = [] theano_var_found = False neural_var_found = False for arg in [obj.start, obj.stop, obj.step]: normal_var, tensor_found, neural_found = convert_to_theano_var(arg) normal_args.append(normal_var) if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return slice(*normal_args), theano_var_found, neural_var_found else: return obj, False, False
def convert_to_theano_var(obj): """ Convert neural vars to theano vars. :param obj: NeuralVariable or list or dict or tuple :return: theano var, test var, tensor found, neural var found """ from deepy.core.neural_var import NeuralVariable if type(obj) == tuple: return tuple(convert_to_theano_var(list(obj))) if type(obj) == list: unpacked_list = map(convert_to_theano_var, obj) normal_list = [] test_list = [] theano_var_found = False neural_var_found = False for normal_var, tensor_found, neural_found in unpacked_list: normal_list.append(normal_var) if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return normal_list, theano_var_found, neural_var_found elif type(obj) == dict: normal_map = {} theano_var_found = False neural_var_found = False for key in obj: normal_var, tensor_found, neural_found = convert_to_theano_var(obj[key]) normal_map[key] = normal_var if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return normal_map, theano_var_found, neural_var_found elif type(obj) == MapDict: normal_map = {} theano_var_found = False neural_var_found = False for key in obj: normal_var, tensor_found, neural_found = convert_to_theano_var(obj[key]) normal_map[key] = normal_var if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return MapDict(normal_map), theano_var_found, neural_var_found elif type(obj) == NeuralVariable: theano_tensor = obj.tensor theano_tensor.tag.last_dim = obj.dim() return theano_tensor, False, True elif type(obj) == TensorVariable: return obj, True, False elif type(obj) == slice: normal_args = [] theano_var_found = False neural_var_found = False for arg in [obj.start, obj.stop, obj.step]: normal_var, tensor_found, neural_found = convert_to_theano_var(arg) normal_args.append(normal_var) if tensor_found: theano_var_found = True if neural_found: neural_var_found = True return slice(*normal_args), theano_var_found, neural_var_found else: return obj, False, False
[ "Convert", "neural", "vars", "to", "theano", "vars", ".", ":", "param", "obj", ":", "NeuralVariable", "or", "list", "or", "dict", "or", "tuple", ":", "return", ":", "theano", "var", "test", "var", "tensor", "found", "neural", "var", "found" ]
zomux/deepy
python
https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/core/tensor_conversion.py#L7-L64
[ "def", "convert_to_theano_var", "(", "obj", ")", ":", "from", "deepy", ".", "core", ".", "neural_var", "import", "NeuralVariable", "if", "type", "(", "obj", ")", "==", "tuple", ":", "return", "tuple", "(", "convert_to_theano_var", "(", "list", "(", "obj", ")", ")", ")", "if", "type", "(", "obj", ")", "==", "list", ":", "unpacked_list", "=", "map", "(", "convert_to_theano_var", ",", "obj", ")", "normal_list", "=", "[", "]", "test_list", "=", "[", "]", "theano_var_found", "=", "False", "neural_var_found", "=", "False", "for", "normal_var", ",", "tensor_found", ",", "neural_found", "in", "unpacked_list", ":", "normal_list", ".", "append", "(", "normal_var", ")", "if", "tensor_found", ":", "theano_var_found", "=", "True", "if", "neural_found", ":", "neural_var_found", "=", "True", "return", "normal_list", ",", "theano_var_found", ",", "neural_var_found", "elif", "type", "(", "obj", ")", "==", "dict", ":", "normal_map", "=", "{", "}", "theano_var_found", "=", "False", "neural_var_found", "=", "False", "for", "key", "in", "obj", ":", "normal_var", ",", "tensor_found", ",", "neural_found", "=", "convert_to_theano_var", "(", "obj", "[", "key", "]", ")", "normal_map", "[", "key", "]", "=", "normal_var", "if", "tensor_found", ":", "theano_var_found", "=", "True", "if", "neural_found", ":", "neural_var_found", "=", "True", "return", "normal_map", ",", "theano_var_found", ",", "neural_var_found", "elif", "type", "(", "obj", ")", "==", "MapDict", ":", "normal_map", "=", "{", "}", "theano_var_found", "=", "False", "neural_var_found", "=", "False", "for", "key", "in", "obj", ":", "normal_var", ",", "tensor_found", ",", "neural_found", "=", "convert_to_theano_var", "(", "obj", "[", "key", "]", ")", "normal_map", "[", "key", "]", "=", "normal_var", "if", "tensor_found", ":", "theano_var_found", "=", "True", "if", "neural_found", ":", "neural_var_found", "=", "True", "return", "MapDict", "(", "normal_map", ")", ",", "theano_var_found", ",", "neural_var_found", "elif", "type", "(", "obj", ")", "==", "NeuralVariable", ":", "theano_tensor", "=", "obj", ".", "tensor", "theano_tensor", ".", "tag", ".", "last_dim", "=", "obj", ".", "dim", "(", ")", "return", "theano_tensor", ",", "False", ",", "True", "elif", "type", "(", "obj", ")", "==", "TensorVariable", ":", "return", "obj", ",", "True", ",", "False", "elif", "type", "(", "obj", ")", "==", "slice", ":", "normal_args", "=", "[", "]", "theano_var_found", "=", "False", "neural_var_found", "=", "False", "for", "arg", "in", "[", "obj", ".", "start", ",", "obj", ".", "stop", ",", "obj", ".", "step", "]", ":", "normal_var", ",", "tensor_found", ",", "neural_found", "=", "convert_to_theano_var", "(", "arg", ")", "normal_args", ".", "append", "(", "normal_var", ")", "if", "tensor_found", ":", "theano_var_found", "=", "True", "if", "neural_found", ":", "neural_var_found", "=", "True", "return", "slice", "(", "*", "normal_args", ")", ",", "theano_var_found", ",", "neural_var_found", "else", ":", "return", "obj", ",", "False", ",", "False" ]
090fbad22a08a809b12951cd0d4984f5bd432698
test
convert_to_neural_var
Convert object and a test object into neural var. :param obj: tensor or list or dict or tuple :param test_obj: NeuralVar or list or dict or tuple :return:
deepy/core/tensor_conversion.py
def convert_to_neural_var(obj): """ Convert object and a test object into neural var. :param obj: tensor or list or dict or tuple :param test_obj: NeuralVar or list or dict or tuple :return: """ from theano.tensor.var import TensorVariable from deepy.core.neural_var import NeuralVariable if type(obj) == list: return [convert_to_neural_var(item) for item in obj] elif type(obj) == tuple: return tuple(convert_to_neural_var(list(obj))) elif type(obj) == dict: merged_map = {} for key in obj: merged_map[key] = convert_to_neural_var(obj[key]) return merged_map elif type(obj) == MapDict: merged_map = {} for key in obj: merged_map[key] = convert_to_neural_var(obj[key]) return MapDict(merged_map) elif type(obj) == TensorVariable: deepy_var = NeuralVariable(obj) if hasattr(obj, 'tag') and hasattr(obj.tag, 'last_dim'): deepy_var.output_dim = obj.tag.last_dim return deepy_var else: return obj
def convert_to_neural_var(obj): """ Convert object and a test object into neural var. :param obj: tensor or list or dict or tuple :param test_obj: NeuralVar or list or dict or tuple :return: """ from theano.tensor.var import TensorVariable from deepy.core.neural_var import NeuralVariable if type(obj) == list: return [convert_to_neural_var(item) for item in obj] elif type(obj) == tuple: return tuple(convert_to_neural_var(list(obj))) elif type(obj) == dict: merged_map = {} for key in obj: merged_map[key] = convert_to_neural_var(obj[key]) return merged_map elif type(obj) == MapDict: merged_map = {} for key in obj: merged_map[key] = convert_to_neural_var(obj[key]) return MapDict(merged_map) elif type(obj) == TensorVariable: deepy_var = NeuralVariable(obj) if hasattr(obj, 'tag') and hasattr(obj.tag, 'last_dim'): deepy_var.output_dim = obj.tag.last_dim return deepy_var else: return obj
[ "Convert", "object", "and", "a", "test", "object", "into", "neural", "var", ".", ":", "param", "obj", ":", "tensor", "or", "list", "or", "dict", "or", "tuple", ":", "param", "test_obj", ":", "NeuralVar", "or", "list", "or", "dict", "or", "tuple", ":", "return", ":" ]
zomux/deepy
python
https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/core/tensor_conversion.py#L66-L95
[ "def", "convert_to_neural_var", "(", "obj", ")", ":", "from", "theano", ".", "tensor", ".", "var", "import", "TensorVariable", "from", "deepy", ".", "core", ".", "neural_var", "import", "NeuralVariable", "if", "type", "(", "obj", ")", "==", "list", ":", "return", "[", "convert_to_neural_var", "(", "item", ")", "for", "item", "in", "obj", "]", "elif", "type", "(", "obj", ")", "==", "tuple", ":", "return", "tuple", "(", "convert_to_neural_var", "(", "list", "(", "obj", ")", ")", ")", "elif", "type", "(", "obj", ")", "==", "dict", ":", "merged_map", "=", "{", "}", "for", "key", "in", "obj", ":", "merged_map", "[", "key", "]", "=", "convert_to_neural_var", "(", "obj", "[", "key", "]", ")", "return", "merged_map", "elif", "type", "(", "obj", ")", "==", "MapDict", ":", "merged_map", "=", "{", "}", "for", "key", "in", "obj", ":", "merged_map", "[", "key", "]", "=", "convert_to_neural_var", "(", "obj", "[", "key", "]", ")", "return", "MapDict", "(", "merged_map", ")", "elif", "type", "(", "obj", ")", "==", "TensorVariable", ":", "deepy_var", "=", "NeuralVariable", "(", "obj", ")", "if", "hasattr", "(", "obj", ",", "'tag'", ")", "and", "hasattr", "(", "obj", ".", "tag", ",", "'last_dim'", ")", ":", "deepy_var", ".", "output_dim", "=", "obj", ".", "tag", ".", "last_dim", "return", "deepy_var", "else", ":", "return", "obj" ]
090fbad22a08a809b12951cd0d4984f5bd432698
test
neural_computation
An annotation to enable theano-based fucntions to be called with NeuralVar. :param original_func: :param prefer_tensor: a switch to return tensors when no inputs :return:
deepy/core/tensor_conversion.py
def neural_computation(original_func, prefer_tensor=False): """ An annotation to enable theano-based fucntions to be called with NeuralVar. :param original_func: :param prefer_tensor: a switch to return tensors when no inputs :return: """ def wrapper(*args, **kwargs): normal_args, tensor_found_in_args, neural_found_in_args = convert_to_theano_var(args) normal_kwargs, tensor_found_in_kwargs, neural_found_in_kwargs = convert_to_theano_var(kwargs) tensor_found = tensor_found_in_args or tensor_found_in_kwargs neural_found = neural_found_in_args or neural_found_in_kwargs if tensor_found and neural_found: raise Exception("Theano tensor variables can not be used together with neural variables.") normal_result = original_func(*normal_args, **normal_kwargs) if tensor_found or (not neural_found and prefer_tensor): # No neural variables are inputted, so output tensors return normal_result else: # Output neural variables, auto set output_dim result_var = convert_to_neural_var(normal_result) if (isinstance(normal_result, TensorVariable) and hasattr(normal_result.tag, "test_value") and hasattr(normal_result.tag.test_value, "shape") and normal_result.tag.test_value.shape): result_var.output_dim = normal_result.tag.test_value.shape[-1] return result_var return wrapper
def neural_computation(original_func, prefer_tensor=False): """ An annotation to enable theano-based fucntions to be called with NeuralVar. :param original_func: :param prefer_tensor: a switch to return tensors when no inputs :return: """ def wrapper(*args, **kwargs): normal_args, tensor_found_in_args, neural_found_in_args = convert_to_theano_var(args) normal_kwargs, tensor_found_in_kwargs, neural_found_in_kwargs = convert_to_theano_var(kwargs) tensor_found = tensor_found_in_args or tensor_found_in_kwargs neural_found = neural_found_in_args or neural_found_in_kwargs if tensor_found and neural_found: raise Exception("Theano tensor variables can not be used together with neural variables.") normal_result = original_func(*normal_args, **normal_kwargs) if tensor_found or (not neural_found and prefer_tensor): # No neural variables are inputted, so output tensors return normal_result else: # Output neural variables, auto set output_dim result_var = convert_to_neural_var(normal_result) if (isinstance(normal_result, TensorVariable) and hasattr(normal_result.tag, "test_value") and hasattr(normal_result.tag.test_value, "shape") and normal_result.tag.test_value.shape): result_var.output_dim = normal_result.tag.test_value.shape[-1] return result_var return wrapper
[ "An", "annotation", "to", "enable", "theano", "-", "based", "fucntions", "to", "be", "called", "with", "NeuralVar", ".", ":", "param", "original_func", ":", ":", "param", "prefer_tensor", ":", "a", "switch", "to", "return", "tensors", "when", "no", "inputs", ":", "return", ":" ]
zomux/deepy
python
https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/core/tensor_conversion.py#L97-L129
[ "def", "neural_computation", "(", "original_func", ",", "prefer_tensor", "=", "False", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "normal_args", ",", "tensor_found_in_args", ",", "neural_found_in_args", "=", "convert_to_theano_var", "(", "args", ")", "normal_kwargs", ",", "tensor_found_in_kwargs", ",", "neural_found_in_kwargs", "=", "convert_to_theano_var", "(", "kwargs", ")", "tensor_found", "=", "tensor_found_in_args", "or", "tensor_found_in_kwargs", "neural_found", "=", "neural_found_in_args", "or", "neural_found_in_kwargs", "if", "tensor_found", "and", "neural_found", ":", "raise", "Exception", "(", "\"Theano tensor variables can not be used together with neural variables.\"", ")", "normal_result", "=", "original_func", "(", "*", "normal_args", ",", "*", "*", "normal_kwargs", ")", "if", "tensor_found", "or", "(", "not", "neural_found", "and", "prefer_tensor", ")", ":", "# No neural variables are inputted, so output tensors", "return", "normal_result", "else", ":", "# Output neural variables, auto set output_dim", "result_var", "=", "convert_to_neural_var", "(", "normal_result", ")", "if", "(", "isinstance", "(", "normal_result", ",", "TensorVariable", ")", "and", "hasattr", "(", "normal_result", ".", "tag", ",", "\"test_value\"", ")", "and", "hasattr", "(", "normal_result", ".", "tag", ".", "test_value", ",", "\"shape\"", ")", "and", "normal_result", ".", "tag", ".", "test_value", ".", "shape", ")", ":", "result_var", ".", "output_dim", "=", "normal_result", ".", "tag", ".", "test_value", ".", "shape", "[", "-", "1", "]", "return", "result_var", "return", "wrapper" ]
090fbad22a08a809b12951cd0d4984f5bd432698
test
onehot_tensor
# batch x time
deepy/tensor/onehot.py
def onehot_tensor(i_matrix, vocab_size): """ # batch x time """ dim0, dim1 = i_matrix.shape i_vector = i_matrix.reshape((-1,)) hot_matrix = T.extra_ops.to_one_hot(i_vector, vocab_size).reshape((dim0, dim1, vocab_size)) return hot_matrix
def onehot_tensor(i_matrix, vocab_size): """ # batch x time """ dim0, dim1 = i_matrix.shape i_vector = i_matrix.reshape((-1,)) hot_matrix = T.extra_ops.to_one_hot(i_vector, vocab_size).reshape((dim0, dim1, vocab_size)) return hot_matrix
[ "#", "batch", "x", "time" ]
zomux/deepy
python
https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/tensor/onehot.py#L9-L16
[ "def", "onehot_tensor", "(", "i_matrix", ",", "vocab_size", ")", ":", "dim0", ",", "dim1", "=", "i_matrix", ".", "shape", "i_vector", "=", "i_matrix", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "hot_matrix", "=", "T", ".", "extra_ops", ".", "to_one_hot", "(", "i_vector", ",", "vocab_size", ")", ".", "reshape", "(", "(", "dim0", ",", "dim1", ",", "vocab_size", ")", ")", "return", "hot_matrix" ]
090fbad22a08a809b12951cd0d4984f5bd432698
test
OAuth2.create_request_elements
Creates |oauth2| request elements.
authomatic/providers/oauth2.py
def create_request_elements( cls, request_type, credentials, url, method='GET', params=None, headers=None, body='', secret=None, redirect_uri='', scope='', csrf='', user_state='' ): """ Creates |oauth2| request elements. """ headers = headers or {} params = params or {} consumer_key = credentials.consumer_key or '' consumer_secret = credentials.consumer_secret or '' token = credentials.token or '' refresh_token = credentials.refresh_token or credentials.token or '' # Separate url base and query parameters. url, base_params = cls._split_url(url) # Add params extracted from URL. params.update(dict(base_params)) if request_type == cls.USER_AUTHORIZATION_REQUEST_TYPE: # User authorization request. # TODO: Raise error for specific message for each missing argument. if consumer_key and redirect_uri and ( csrf or not cls.supports_csrf_protection): params['client_id'] = consumer_key params['redirect_uri'] = redirect_uri params['scope'] = scope if cls.supports_user_state: params['state'] = base64.urlsafe_b64encode( json.dumps( {"csrf": csrf, "user_state": user_state} ).encode('utf-8') ) else: params['state'] = csrf params['response_type'] = 'code' # Add authorization header headers.update(cls._authorization_header(credentials)) else: raise OAuth2Error( 'Credentials with valid consumer_key and arguments ' 'redirect_uri, scope and state are required to create ' 'OAuth 2.0 user authorization request elements!') elif request_type == cls.ACCESS_TOKEN_REQUEST_TYPE: # Access token request. if consumer_key and consumer_secret: params['code'] = token params['client_id'] = consumer_key params['client_secret'] = consumer_secret params['redirect_uri'] = redirect_uri params['grant_type'] = 'authorization_code' # TODO: Check whether all providers accept it headers.update(cls._authorization_header(credentials)) else: raise OAuth2Error( 'Credentials with valid token, consumer_key, ' 'consumer_secret and argument redirect_uri are required ' 'to create OAuth 2.0 access token request elements!') elif request_type == cls.REFRESH_TOKEN_REQUEST_TYPE: # Refresh access token request. if refresh_token and consumer_key and consumer_secret: params['refresh_token'] = refresh_token params['client_id'] = consumer_key params['client_secret'] = consumer_secret params['grant_type'] = 'refresh_token' else: raise OAuth2Error( 'Credentials with valid refresh_token, consumer_key, ' 'consumer_secret are required to create OAuth 2.0 ' 'refresh token request elements!') elif request_type == cls.PROTECTED_RESOURCE_REQUEST_TYPE: # Protected resource request. # Add Authorization header. See: # http://tools.ietf.org/html/rfc6749#section-7.1 if credentials.token_type == cls.BEARER: # http://tools.ietf.org/html/rfc6750#section-2.1 headers.update( {'Authorization': 'Bearer {0}'.format(credentials.token)}) elif token: params['access_token'] = token else: raise OAuth2Error( 'Credentials with valid token are required to create ' 'OAuth 2.0 protected resources request elements!') request_elements = core.RequestElements( url, method, params, headers, body) return cls._x_request_elements_filter( request_type, request_elements, credentials)
def create_request_elements( cls, request_type, credentials, url, method='GET', params=None, headers=None, body='', secret=None, redirect_uri='', scope='', csrf='', user_state='' ): """ Creates |oauth2| request elements. """ headers = headers or {} params = params or {} consumer_key = credentials.consumer_key or '' consumer_secret = credentials.consumer_secret or '' token = credentials.token or '' refresh_token = credentials.refresh_token or credentials.token or '' # Separate url base and query parameters. url, base_params = cls._split_url(url) # Add params extracted from URL. params.update(dict(base_params)) if request_type == cls.USER_AUTHORIZATION_REQUEST_TYPE: # User authorization request. # TODO: Raise error for specific message for each missing argument. if consumer_key and redirect_uri and ( csrf or not cls.supports_csrf_protection): params['client_id'] = consumer_key params['redirect_uri'] = redirect_uri params['scope'] = scope if cls.supports_user_state: params['state'] = base64.urlsafe_b64encode( json.dumps( {"csrf": csrf, "user_state": user_state} ).encode('utf-8') ) else: params['state'] = csrf params['response_type'] = 'code' # Add authorization header headers.update(cls._authorization_header(credentials)) else: raise OAuth2Error( 'Credentials with valid consumer_key and arguments ' 'redirect_uri, scope and state are required to create ' 'OAuth 2.0 user authorization request elements!') elif request_type == cls.ACCESS_TOKEN_REQUEST_TYPE: # Access token request. if consumer_key and consumer_secret: params['code'] = token params['client_id'] = consumer_key params['client_secret'] = consumer_secret params['redirect_uri'] = redirect_uri params['grant_type'] = 'authorization_code' # TODO: Check whether all providers accept it headers.update(cls._authorization_header(credentials)) else: raise OAuth2Error( 'Credentials with valid token, consumer_key, ' 'consumer_secret and argument redirect_uri are required ' 'to create OAuth 2.0 access token request elements!') elif request_type == cls.REFRESH_TOKEN_REQUEST_TYPE: # Refresh access token request. if refresh_token and consumer_key and consumer_secret: params['refresh_token'] = refresh_token params['client_id'] = consumer_key params['client_secret'] = consumer_secret params['grant_type'] = 'refresh_token' else: raise OAuth2Error( 'Credentials with valid refresh_token, consumer_key, ' 'consumer_secret are required to create OAuth 2.0 ' 'refresh token request elements!') elif request_type == cls.PROTECTED_RESOURCE_REQUEST_TYPE: # Protected resource request. # Add Authorization header. See: # http://tools.ietf.org/html/rfc6749#section-7.1 if credentials.token_type == cls.BEARER: # http://tools.ietf.org/html/rfc6750#section-2.1 headers.update( {'Authorization': 'Bearer {0}'.format(credentials.token)}) elif token: params['access_token'] = token else: raise OAuth2Error( 'Credentials with valid token are required to create ' 'OAuth 2.0 protected resources request elements!') request_elements = core.RequestElements( url, method, params, headers, body) return cls._x_request_elements_filter( request_type, request_elements, credentials)
[ "Creates", "|oauth2|", "request", "elements", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth2.py#L115-L215
[ "def", "create_request_elements", "(", "cls", ",", "request_type", ",", "credentials", ",", "url", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "secret", "=", "None", ",", "redirect_uri", "=", "''", ",", "scope", "=", "''", ",", "csrf", "=", "''", ",", "user_state", "=", "''", ")", ":", "headers", "=", "headers", "or", "{", "}", "params", "=", "params", "or", "{", "}", "consumer_key", "=", "credentials", ".", "consumer_key", "or", "''", "consumer_secret", "=", "credentials", ".", "consumer_secret", "or", "''", "token", "=", "credentials", ".", "token", "or", "''", "refresh_token", "=", "credentials", ".", "refresh_token", "or", "credentials", ".", "token", "or", "''", "# Separate url base and query parameters.", "url", ",", "base_params", "=", "cls", ".", "_split_url", "(", "url", ")", "# Add params extracted from URL.", "params", ".", "update", "(", "dict", "(", "base_params", ")", ")", "if", "request_type", "==", "cls", ".", "USER_AUTHORIZATION_REQUEST_TYPE", ":", "# User authorization request.", "# TODO: Raise error for specific message for each missing argument.", "if", "consumer_key", "and", "redirect_uri", "and", "(", "csrf", "or", "not", "cls", ".", "supports_csrf_protection", ")", ":", "params", "[", "'client_id'", "]", "=", "consumer_key", "params", "[", "'redirect_uri'", "]", "=", "redirect_uri", "params", "[", "'scope'", "]", "=", "scope", "if", "cls", ".", "supports_user_state", ":", "params", "[", "'state'", "]", "=", "base64", ".", "urlsafe_b64encode", "(", "json", ".", "dumps", "(", "{", "\"csrf\"", ":", "csrf", ",", "\"user_state\"", ":", "user_state", "}", ")", ".", "encode", "(", "'utf-8'", ")", ")", "else", ":", "params", "[", "'state'", "]", "=", "csrf", "params", "[", "'response_type'", "]", "=", "'code'", "# Add authorization header", "headers", ".", "update", "(", "cls", ".", "_authorization_header", "(", "credentials", ")", ")", "else", ":", "raise", "OAuth2Error", "(", "'Credentials with valid consumer_key and arguments '", "'redirect_uri, scope and state are required to create '", "'OAuth 2.0 user authorization request elements!'", ")", "elif", "request_type", "==", "cls", ".", "ACCESS_TOKEN_REQUEST_TYPE", ":", "# Access token request.", "if", "consumer_key", "and", "consumer_secret", ":", "params", "[", "'code'", "]", "=", "token", "params", "[", "'client_id'", "]", "=", "consumer_key", "params", "[", "'client_secret'", "]", "=", "consumer_secret", "params", "[", "'redirect_uri'", "]", "=", "redirect_uri", "params", "[", "'grant_type'", "]", "=", "'authorization_code'", "# TODO: Check whether all providers accept it", "headers", ".", "update", "(", "cls", ".", "_authorization_header", "(", "credentials", ")", ")", "else", ":", "raise", "OAuth2Error", "(", "'Credentials with valid token, consumer_key, '", "'consumer_secret and argument redirect_uri are required '", "'to create OAuth 2.0 access token request elements!'", ")", "elif", "request_type", "==", "cls", ".", "REFRESH_TOKEN_REQUEST_TYPE", ":", "# Refresh access token request.", "if", "refresh_token", "and", "consumer_key", "and", "consumer_secret", ":", "params", "[", "'refresh_token'", "]", "=", "refresh_token", "params", "[", "'client_id'", "]", "=", "consumer_key", "params", "[", "'client_secret'", "]", "=", "consumer_secret", "params", "[", "'grant_type'", "]", "=", "'refresh_token'", "else", ":", "raise", "OAuth2Error", "(", "'Credentials with valid refresh_token, consumer_key, '", "'consumer_secret are required to create OAuth 2.0 '", "'refresh token request elements!'", ")", "elif", "request_type", "==", "cls", ".", "PROTECTED_RESOURCE_REQUEST_TYPE", ":", "# Protected resource request.", "# Add Authorization header. See:", "# http://tools.ietf.org/html/rfc6749#section-7.1", "if", "credentials", ".", "token_type", "==", "cls", ".", "BEARER", ":", "# http://tools.ietf.org/html/rfc6750#section-2.1", "headers", ".", "update", "(", "{", "'Authorization'", ":", "'Bearer {0}'", ".", "format", "(", "credentials", ".", "token", ")", "}", ")", "elif", "token", ":", "params", "[", "'access_token'", "]", "=", "token", "else", ":", "raise", "OAuth2Error", "(", "'Credentials with valid token are required to create '", "'OAuth 2.0 protected resources request elements!'", ")", "request_elements", "=", "core", ".", "RequestElements", "(", "url", ",", "method", ",", "params", ",", "headers", ",", "body", ")", "return", "cls", ".", "_x_request_elements_filter", "(", "request_type", ",", "request_elements", ",", "credentials", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
OAuth2.decode_state
Decode state and return param. :param str state: state parameter passed through by provider :param str param: key to query from decoded state variable. Options include 'csrf' and 'user_state'. :returns: string value from decoded state
authomatic/providers/oauth2.py
def decode_state(cls, state, param='user_state'): """ Decode state and return param. :param str state: state parameter passed through by provider :param str param: key to query from decoded state variable. Options include 'csrf' and 'user_state'. :returns: string value from decoded state """ if state and cls.supports_user_state: # urlsafe_b64 may include = which the browser quotes so must # unquote Cast to str to void b64decode translation error. Base64 # should be str compatible. return json.loads(base64.urlsafe_b64decode( unquote(str(state))).decode('utf-8'))[param] else: return state if param == 'csrf' else ''
def decode_state(cls, state, param='user_state'): """ Decode state and return param. :param str state: state parameter passed through by provider :param str param: key to query from decoded state variable. Options include 'csrf' and 'user_state'. :returns: string value from decoded state """ if state and cls.supports_user_state: # urlsafe_b64 may include = which the browser quotes so must # unquote Cast to str to void b64decode translation error. Base64 # should be str compatible. return json.loads(base64.urlsafe_b64decode( unquote(str(state))).decode('utf-8'))[param] else: return state if param == 'csrf' else ''
[ "Decode", "state", "and", "return", "param", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth2.py#L262-L284
[ "def", "decode_state", "(", "cls", ",", "state", ",", "param", "=", "'user_state'", ")", ":", "if", "state", "and", "cls", ".", "supports_user_state", ":", "# urlsafe_b64 may include = which the browser quotes so must", "# unquote Cast to str to void b64decode translation error. Base64", "# should be str compatible.", "return", "json", ".", "loads", "(", "base64", ".", "urlsafe_b64decode", "(", "unquote", "(", "str", "(", "state", ")", ")", ")", ".", "decode", "(", "'utf-8'", ")", ")", "[", "param", "]", "else", ":", "return", "state", "if", "param", "==", "'csrf'", "else", "''" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
OAuth2.refresh_credentials
Refreshes :class:`.Credentials` if it gives sense. :param credentials: :class:`.Credentials` to be refreshed. :returns: :class:`.Response`.
authomatic/providers/oauth2.py
def refresh_credentials(self, credentials): """ Refreshes :class:`.Credentials` if it gives sense. :param credentials: :class:`.Credentials` to be refreshed. :returns: :class:`.Response`. """ if not self._x_refresh_credentials_if(credentials): return # We need consumer key and secret to make this kind of request. cfg = credentials.config.get(credentials.provider_name) credentials.consumer_key = cfg.get('consumer_key') credentials.consumer_secret = cfg.get('consumer_secret') request_elements = self.create_request_elements( request_type=self.REFRESH_TOKEN_REQUEST_TYPE, credentials=credentials, url=self.access_token_url, method='POST' ) self._log(logging.INFO, u'Refreshing credentials.') response = self._fetch(*request_elements) # We no longer need consumer info. credentials.consumer_key = None credentials.consumer_secret = None # Extract the refreshed data. access_token = response.data.get('access_token') refresh_token = response.data.get('refresh_token') # Update credentials only if there is access token. if access_token: credentials.token = access_token credentials.expire_in = response.data.get('expires_in') # Update refresh token only if there is a new one. if refresh_token: credentials.refresh_token = refresh_token # Handle different naming conventions across providers. credentials = self._x_credentials_parser( credentials, response.data) return response
def refresh_credentials(self, credentials): """ Refreshes :class:`.Credentials` if it gives sense. :param credentials: :class:`.Credentials` to be refreshed. :returns: :class:`.Response`. """ if not self._x_refresh_credentials_if(credentials): return # We need consumer key and secret to make this kind of request. cfg = credentials.config.get(credentials.provider_name) credentials.consumer_key = cfg.get('consumer_key') credentials.consumer_secret = cfg.get('consumer_secret') request_elements = self.create_request_elements( request_type=self.REFRESH_TOKEN_REQUEST_TYPE, credentials=credentials, url=self.access_token_url, method='POST' ) self._log(logging.INFO, u'Refreshing credentials.') response = self._fetch(*request_elements) # We no longer need consumer info. credentials.consumer_key = None credentials.consumer_secret = None # Extract the refreshed data. access_token = response.data.get('access_token') refresh_token = response.data.get('refresh_token') # Update credentials only if there is access token. if access_token: credentials.token = access_token credentials.expire_in = response.data.get('expires_in') # Update refresh token only if there is a new one. if refresh_token: credentials.refresh_token = refresh_token # Handle different naming conventions across providers. credentials = self._x_credentials_parser( credentials, response.data) return response
[ "Refreshes", ":", "class", ":", ".", "Credentials", "if", "it", "gives", "sense", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth2.py#L286-L337
[ "def", "refresh_credentials", "(", "self", ",", "credentials", ")", ":", "if", "not", "self", ".", "_x_refresh_credentials_if", "(", "credentials", ")", ":", "return", "# We need consumer key and secret to make this kind of request.", "cfg", "=", "credentials", ".", "config", ".", "get", "(", "credentials", ".", "provider_name", ")", "credentials", ".", "consumer_key", "=", "cfg", ".", "get", "(", "'consumer_key'", ")", "credentials", ".", "consumer_secret", "=", "cfg", ".", "get", "(", "'consumer_secret'", ")", "request_elements", "=", "self", ".", "create_request_elements", "(", "request_type", "=", "self", ".", "REFRESH_TOKEN_REQUEST_TYPE", ",", "credentials", "=", "credentials", ",", "url", "=", "self", ".", "access_token_url", ",", "method", "=", "'POST'", ")", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Refreshing credentials.'", ")", "response", "=", "self", ".", "_fetch", "(", "*", "request_elements", ")", "# We no longer need consumer info.", "credentials", ".", "consumer_key", "=", "None", "credentials", ".", "consumer_secret", "=", "None", "# Extract the refreshed data.", "access_token", "=", "response", ".", "data", ".", "get", "(", "'access_token'", ")", "refresh_token", "=", "response", ".", "data", ".", "get", "(", "'refresh_token'", ")", "# Update credentials only if there is access token.", "if", "access_token", ":", "credentials", ".", "token", "=", "access_token", "credentials", ".", "expire_in", "=", "response", ".", "data", ".", "get", "(", "'expires_in'", ")", "# Update refresh token only if there is a new one.", "if", "refresh_token", ":", "credentials", ".", "refresh_token", "=", "refresh_token", "# Handle different naming conventions across providers.", "credentials", "=", "self", ".", "_x_credentials_parser", "(", "credentials", ",", "response", ".", "data", ")", "return", "response" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Facebook._x_credentials_parser
We need to override this method to fix Facebooks naming deviation.
authomatic/providers/oauth2.py
def _x_credentials_parser(credentials, data): """ We need to override this method to fix Facebooks naming deviation. """ # Facebook returns "expires" instead of "expires_in". credentials.expire_in = data.get('expires') if data.get('token_type') == 'bearer': # TODO: cls is not available here, hardcode for now. credentials.token_type = 'Bearer' return credentials
def _x_credentials_parser(credentials, data): """ We need to override this method to fix Facebooks naming deviation. """ # Facebook returns "expires" instead of "expires_in". credentials.expire_in = data.get('expires') if data.get('token_type') == 'bearer': # TODO: cls is not available here, hardcode for now. credentials.token_type = 'Bearer' return credentials
[ "We", "need", "to", "override", "this", "method", "to", "fix", "Facebooks", "naming", "deviation", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth2.py#L976-L988
[ "def", "_x_credentials_parser", "(", "credentials", ",", "data", ")", ":", "# Facebook returns \"expires\" instead of \"expires_in\".", "credentials", ".", "expire_in", "=", "data", ".", "get", "(", "'expires'", ")", "if", "data", ".", "get", "(", "'token_type'", ")", "==", "'bearer'", ":", "# TODO: cls is not available here, hardcode for now.", "credentials", ".", "token_type", "=", "'Bearer'", "return", "credentials" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Google._x_request_elements_filter
Google doesn't accept client ID and secret to be at the same time in request parameters and in the basic authorization header in the access token request.
authomatic/providers/oauth2.py
def _x_request_elements_filter(cls, request_type, request_elements, credentials): """ Google doesn't accept client ID and secret to be at the same time in request parameters and in the basic authorization header in the access token request. """ if request_type is cls.ACCESS_TOKEN_REQUEST_TYPE: params = request_elements[2] del params['client_id'] del params['client_secret'] return request_elements
def _x_request_elements_filter(cls, request_type, request_elements, credentials): """ Google doesn't accept client ID and secret to be at the same time in request parameters and in the basic authorization header in the access token request. """ if request_type is cls.ACCESS_TOKEN_REQUEST_TYPE: params = request_elements[2] del params['client_id'] del params['client_secret'] return request_elements
[ "Google", "doesn", "t", "accept", "client", "ID", "and", "secret", "to", "be", "at", "the", "same", "time", "in", "request", "parameters", "and", "in", "the", "basic", "authorization", "header", "in", "the", "access", "token", "request", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth2.py#L1283-L1294
[ "def", "_x_request_elements_filter", "(", "cls", ",", "request_type", ",", "request_elements", ",", "credentials", ")", ":", "if", "request_type", "is", "cls", ".", "ACCESS_TOKEN_REQUEST_TYPE", ":", "params", "=", "request_elements", "[", "2", "]", "del", "params", "[", "'client_id'", "]", "del", "params", "[", "'client_secret'", "]", "return", "request_elements" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
login
Login handler, must accept both GET and POST to be able to use OpenID.
examples/flask/werkzeug_adapter/main.py
def login(provider_name): """ Login handler, must accept both GET and POST to be able to use OpenID. """ # We need response object for the WerkzeugAdapter. response = make_response() # Log the user in, pass it the adapter and the provider name. result = authomatic.login( WerkzeugAdapter( request, response), provider_name) # If there is no LoginResult object, the login procedure is still pending. if result: if result.user: # We need to update the user to get more info. result.user.update() # The rest happens inside the template. return render_template('login.html', result=result) # Don't forget to return the response. return response
def login(provider_name): """ Login handler, must accept both GET and POST to be able to use OpenID. """ # We need response object for the WerkzeugAdapter. response = make_response() # Log the user in, pass it the adapter and the provider name. result = authomatic.login( WerkzeugAdapter( request, response), provider_name) # If there is no LoginResult object, the login procedure is still pending. if result: if result.user: # We need to update the user to get more info. result.user.update() # The rest happens inside the template. return render_template('login.html', result=result) # Don't forget to return the response. return response
[ "Login", "handler", "must", "accept", "both", "GET", "and", "POST", "to", "be", "able", "to", "use", "OpenID", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/examples/flask/werkzeug_adapter/main.py#L29-L54
[ "def", "login", "(", "provider_name", ")", ":", "# We need response object for the WerkzeugAdapter.", "response", "=", "make_response", "(", ")", "# Log the user in, pass it the adapter and the provider name.", "result", "=", "authomatic", ".", "login", "(", "WerkzeugAdapter", "(", "request", ",", "response", ")", ",", "provider_name", ")", "# If there is no LoginResult object, the login procedure is still pending.", "if", "result", ":", "if", "result", ".", "user", ":", "# We need to update the user to get more info.", "result", ".", "user", ".", "update", "(", ")", "# The rest happens inside the template.", "return", "render_template", "(", "'login.html'", ",", "result", "=", "result", ")", "# Don't forget to return the response.", "return", "response" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
normalize_dict
Replaces all values that are single-item iterables with the value of its index 0. :param dict dict_: Dictionary to normalize. :returns: Normalized dictionary.
authomatic/core.py
def normalize_dict(dict_): """ Replaces all values that are single-item iterables with the value of its index 0. :param dict dict_: Dictionary to normalize. :returns: Normalized dictionary. """ return dict([(k, v[0] if not isinstance(v, str) and len(v) == 1 else v) for k, v in list(dict_.items())])
def normalize_dict(dict_): """ Replaces all values that are single-item iterables with the value of its index 0. :param dict dict_: Dictionary to normalize. :returns: Normalized dictionary. """ return dict([(k, v[0] if not isinstance(v, str) and len(v) == 1 else v) for k, v in list(dict_.items())])
[ "Replaces", "all", "values", "that", "are", "single", "-", "item", "iterables", "with", "the", "value", "of", "its", "index", "0", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L40-L54
[ "def", "normalize_dict", "(", "dict_", ")", ":", "return", "dict", "(", "[", "(", "k", ",", "v", "[", "0", "]", "if", "not", "isinstance", "(", "v", ",", "str", ")", "and", "len", "(", "v", ")", "==", "1", "else", "v", ")", "for", "k", ",", "v", "in", "list", "(", "dict_", ".", "items", "(", ")", ")", "]", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
items_to_dict
Converts list of tuples to dictionary with duplicate keys converted to lists. :param list items: List of tuples. :returns: :class:`dict`
authomatic/core.py
def items_to_dict(items): """ Converts list of tuples to dictionary with duplicate keys converted to lists. :param list items: List of tuples. :returns: :class:`dict` """ res = collections.defaultdict(list) for k, v in items: res[k].append(v) return normalize_dict(dict(res))
def items_to_dict(items): """ Converts list of tuples to dictionary with duplicate keys converted to lists. :param list items: List of tuples. :returns: :class:`dict` """ res = collections.defaultdict(list) for k, v in items: res[k].append(v) return normalize_dict(dict(res))
[ "Converts", "list", "of", "tuples", "to", "dictionary", "with", "duplicate", "keys", "converted", "to", "lists", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L57-L75
[ "def", "items_to_dict", "(", "items", ")", ":", "res", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "k", ",", "v", "in", "items", ":", "res", "[", "k", "]", ".", "append", "(", "v", ")", "return", "normalize_dict", "(", "dict", "(", "res", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
json_qs_parser
Parses response body from JSON, XML or query string. :param body: string :returns: :class:`dict`, :class:`list` if input is JSON or query string, :class:`xml.etree.ElementTree.Element` if XML.
authomatic/core.py
def json_qs_parser(body): """ Parses response body from JSON, XML or query string. :param body: string :returns: :class:`dict`, :class:`list` if input is JSON or query string, :class:`xml.etree.ElementTree.Element` if XML. """ try: # Try JSON first. return json.loads(body) except (OverflowError, TypeError, ValueError): pass try: # Then XML. return ElementTree.fromstring(body) except (ElementTree.ParseError, TypeError, ValueError): pass # Finally query string. return dict(parse.parse_qsl(body))
def json_qs_parser(body): """ Parses response body from JSON, XML or query string. :param body: string :returns: :class:`dict`, :class:`list` if input is JSON or query string, :class:`xml.etree.ElementTree.Element` if XML. """ try: # Try JSON first. return json.loads(body) except (OverflowError, TypeError, ValueError): pass try: # Then XML. return ElementTree.fromstring(body) except (ElementTree.ParseError, TypeError, ValueError): pass # Finally query string. return dict(parse.parse_qsl(body))
[ "Parses", "response", "body", "from", "JSON", "XML", "or", "query", "string", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L143-L168
[ "def", "json_qs_parser", "(", "body", ")", ":", "try", ":", "# Try JSON first.", "return", "json", ".", "loads", "(", "body", ")", "except", "(", "OverflowError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "try", ":", "# Then XML.", "return", "ElementTree", ".", "fromstring", "(", "body", ")", "except", "(", "ElementTree", ".", "ParseError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "# Finally query string.", "return", "dict", "(", "parse", ".", "parse_qsl", "(", "body", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
resolve_provider_class
Returns a provider class. :param class_name: :class:`string` or :class:`authomatic.providers.BaseProvider` subclass.
authomatic/core.py
def resolve_provider_class(class_): """ Returns a provider class. :param class_name: :class:`string` or :class:`authomatic.providers.BaseProvider` subclass. """ if isinstance(class_, str): # prepare path for authomatic.providers package path = '.'.join([__package__, 'providers', class_]) # try to import class by string from providers module or by fully # qualified path return import_string(class_, True) or import_string(path) else: return class_
def resolve_provider_class(class_): """ Returns a provider class. :param class_name: :class:`string` or :class:`authomatic.providers.BaseProvider` subclass. """ if isinstance(class_, str): # prepare path for authomatic.providers package path = '.'.join([__package__, 'providers', class_]) # try to import class by string from providers module or by fully # qualified path return import_string(class_, True) or import_string(path) else: return class_
[ "Returns", "a", "provider", "class", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L192-L209
[ "def", "resolve_provider_class", "(", "class_", ")", ":", "if", "isinstance", "(", "class_", ",", "str", ")", ":", "# prepare path for authomatic.providers package", "path", "=", "'.'", ".", "join", "(", "[", "__package__", ",", "'providers'", ",", "class_", "]", ")", "# try to import class by string from providers module or by fully", "# qualified path", "return", "import_string", "(", "class_", ",", "True", ")", "or", "import_string", "(", "path", ")", "else", ":", "return", "class_" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
id_to_name
Returns the provider :doc:`config` key based on it's ``id`` value. :param dict config: :doc:`config`. :param id: Value of the id parameter in the :ref:`config` to search for.
authomatic/core.py
def id_to_name(config, short_name): """ Returns the provider :doc:`config` key based on it's ``id`` value. :param dict config: :doc:`config`. :param id: Value of the id parameter in the :ref:`config` to search for. """ for k, v in list(config.items()): if v.get('id') == short_name: return k raise Exception( 'No provider with id={0} found in the config!'.format(short_name))
def id_to_name(config, short_name): """ Returns the provider :doc:`config` key based on it's ``id`` value. :param dict config: :doc:`config`. :param id: Value of the id parameter in the :ref:`config` to search for. """ for k, v in list(config.items()): if v.get('id') == short_name: return k raise Exception( 'No provider with id={0} found in the config!'.format(short_name))
[ "Returns", "the", "provider", ":", "doc", ":", "config", "key", "based", "on", "it", "s", "id", "value", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L212-L228
[ "def", "id_to_name", "(", "config", ",", "short_name", ")", ":", "for", "k", ",", "v", "in", "list", "(", "config", ".", "items", "(", ")", ")", ":", "if", "v", ".", "get", "(", "'id'", ")", "==", "short_name", ":", "return", "k", "raise", "Exception", "(", "'No provider with id={0} found in the config!'", ".", "format", "(", "short_name", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Session.create_cookie
Creates the value for ``Set-Cookie`` HTTP header. :param bool delete: If ``True`` the cookie value will be ``deleted`` and the Expires value will be ``Thu, 01-Jan-1970 00:00:01 GMT``.
authomatic/core.py
def create_cookie(self, delete=None): """ Creates the value for ``Set-Cookie`` HTTP header. :param bool delete: If ``True`` the cookie value will be ``deleted`` and the Expires value will be ``Thu, 01-Jan-1970 00:00:01 GMT``. """ value = 'deleted' if delete else self._serialize(self.data) split_url = parse.urlsplit(self.adapter.url) domain = split_url.netloc.split(':')[0] # Work-around for issue #11, failure of WebKit-based browsers to accept # cookies set as part of a redirect response in some circumstances. if '.' not in domain: template = '{name}={value}; Path={path}; HttpOnly{secure}{expires}' else: template = ('{name}={value}; Domain={domain}; Path={path}; ' 'HttpOnly{secure}{expires}') return template.format( name=self.name, value=value, domain=domain, path=split_url.path, secure='; Secure' if self.secure else '', expires='; Expires=Thu, 01-Jan-1970 00:00:01 GMT' if delete else '' )
def create_cookie(self, delete=None): """ Creates the value for ``Set-Cookie`` HTTP header. :param bool delete: If ``True`` the cookie value will be ``deleted`` and the Expires value will be ``Thu, 01-Jan-1970 00:00:01 GMT``. """ value = 'deleted' if delete else self._serialize(self.data) split_url = parse.urlsplit(self.adapter.url) domain = split_url.netloc.split(':')[0] # Work-around for issue #11, failure of WebKit-based browsers to accept # cookies set as part of a redirect response in some circumstances. if '.' not in domain: template = '{name}={value}; Path={path}; HttpOnly{secure}{expires}' else: template = ('{name}={value}; Domain={domain}; Path={path}; ' 'HttpOnly{secure}{expires}') return template.format( name=self.name, value=value, domain=domain, path=split_url.path, secure='; Secure' if self.secure else '', expires='; Expires=Thu, 01-Jan-1970 00:00:01 GMT' if delete else '' )
[ "Creates", "the", "value", "for", "Set", "-", "Cookie", "HTTP", "header", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L364-L392
[ "def", "create_cookie", "(", "self", ",", "delete", "=", "None", ")", ":", "value", "=", "'deleted'", "if", "delete", "else", "self", ".", "_serialize", "(", "self", ".", "data", ")", "split_url", "=", "parse", ".", "urlsplit", "(", "self", ".", "adapter", ".", "url", ")", "domain", "=", "split_url", ".", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", "# Work-around for issue #11, failure of WebKit-based browsers to accept", "# cookies set as part of a redirect response in some circumstances.", "if", "'.'", "not", "in", "domain", ":", "template", "=", "'{name}={value}; Path={path}; HttpOnly{secure}{expires}'", "else", ":", "template", "=", "(", "'{name}={value}; Domain={domain}; Path={path}; '", "'HttpOnly{secure}{expires}'", ")", "return", "template", ".", "format", "(", "name", "=", "self", ".", "name", ",", "value", "=", "value", ",", "domain", "=", "domain", ",", "path", "=", "split_url", ".", "path", ",", "secure", "=", "'; Secure'", "if", "self", ".", "secure", "else", "''", ",", "expires", "=", "'; Expires=Thu, 01-Jan-1970 00:00:01 GMT'", "if", "delete", "else", "''", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Session.save
Adds the session cookie to headers.
authomatic/core.py
def save(self): """ Adds the session cookie to headers. """ if self.data: cookie = self.create_cookie() cookie_len = len(cookie) if cookie_len > 4093: raise SessionError('Cookie too long! The cookie size {0} ' 'is more than 4093 bytes.' .format(cookie_len)) self.adapter.set_header('Set-Cookie', cookie) # Reset data self._data = {}
def save(self): """ Adds the session cookie to headers. """ if self.data: cookie = self.create_cookie() cookie_len = len(cookie) if cookie_len > 4093: raise SessionError('Cookie too long! The cookie size {0} ' 'is more than 4093 bytes.' .format(cookie_len)) self.adapter.set_header('Set-Cookie', cookie) # Reset data self._data = {}
[ "Adds", "the", "session", "cookie", "to", "headers", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L394-L410
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "data", ":", "cookie", "=", "self", ".", "create_cookie", "(", ")", "cookie_len", "=", "len", "(", "cookie", ")", "if", "cookie_len", ">", "4093", ":", "raise", "SessionError", "(", "'Cookie too long! The cookie size {0} '", "'is more than 4093 bytes.'", ".", "format", "(", "cookie_len", ")", ")", "self", ".", "adapter", ".", "set_header", "(", "'Set-Cookie'", ",", "cookie", ")", "# Reset data", "self", ".", "_data", "=", "{", "}" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Session._get_data
Extracts the session data from cookie.
authomatic/core.py
def _get_data(self): """ Extracts the session data from cookie. """ cookie = self.adapter.cookies.get(self.name) return self._deserialize(cookie) if cookie else {}
def _get_data(self): """ Extracts the session data from cookie. """ cookie = self.adapter.cookies.get(self.name) return self._deserialize(cookie) if cookie else {}
[ "Extracts", "the", "session", "data", "from", "cookie", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L415-L420
[ "def", "_get_data", "(", "self", ")", ":", "cookie", "=", "self", ".", "adapter", ".", "cookies", ".", "get", "(", "self", ".", "name", ")", "return", "self", ".", "_deserialize", "(", "cookie", ")", "if", "cookie", "else", "{", "}" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Session.data
Gets session data lazily.
authomatic/core.py
def data(self): """ Gets session data lazily. """ if not self._data: self._data = self._get_data() # Always return a dict, even if deserialization returned nothing if self._data is None: self._data = {} return self._data
def data(self): """ Gets session data lazily. """ if not self._data: self._data = self._get_data() # Always return a dict, even if deserialization returned nothing if self._data is None: self._data = {} return self._data
[ "Gets", "session", "data", "lazily", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L423-L432
[ "def", "data", "(", "self", ")", ":", "if", "not", "self", ".", "_data", ":", "self", ".", "_data", "=", "self", ".", "_get_data", "(", ")", "# Always return a dict, even if deserialization returned nothing", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_data", "=", "{", "}", "return", "self", ".", "_data" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Session._signature
Creates signature for the session.
authomatic/core.py
def _signature(self, *parts): """ Creates signature for the session. """ signature = hmac.new(six.b(self.secret), digestmod=hashlib.sha1) signature.update(six.b('|'.join(parts))) return signature.hexdigest()
def _signature(self, *parts): """ Creates signature for the session. """ signature = hmac.new(six.b(self.secret), digestmod=hashlib.sha1) signature.update(six.b('|'.join(parts))) return signature.hexdigest()
[ "Creates", "signature", "for", "the", "session", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L434-L440
[ "def", "_signature", "(", "self", ",", "*", "parts", ")", ":", "signature", "=", "hmac", ".", "new", "(", "six", ".", "b", "(", "self", ".", "secret", ")", ",", "digestmod", "=", "hashlib", ".", "sha1", ")", "signature", ".", "update", "(", "six", ".", "b", "(", "'|'", ".", "join", "(", "parts", ")", ")", ")", "return", "signature", ".", "hexdigest", "(", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Session._serialize
Converts the value to a signed string with timestamp. :param value: Object to be serialized. :returns: Serialized value.
authomatic/core.py
def _serialize(self, value): """ Converts the value to a signed string with timestamp. :param value: Object to be serialized. :returns: Serialized value. """ # data = copy.deepcopy(value) data = value # 1. Serialize serialized = pickle.dumps(data).decode('latin-1') # 2. Encode # Percent encoding produces smaller result then urlsafe base64. encoded = parse.quote(serialized, '') # 3. Concatenate timestamp = str(int(time.time())) signature = self._signature(self.name, encoded, timestamp) concatenated = '|'.join([encoded, timestamp, signature]) return concatenated
def _serialize(self, value): """ Converts the value to a signed string with timestamp. :param value: Object to be serialized. :returns: Serialized value. """ # data = copy.deepcopy(value) data = value # 1. Serialize serialized = pickle.dumps(data).decode('latin-1') # 2. Encode # Percent encoding produces smaller result then urlsafe base64. encoded = parse.quote(serialized, '') # 3. Concatenate timestamp = str(int(time.time())) signature = self._signature(self.name, encoded, timestamp) concatenated = '|'.join([encoded, timestamp, signature]) return concatenated
[ "Converts", "the", "value", "to", "a", "signed", "string", "with", "timestamp", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L442-L469
[ "def", "_serialize", "(", "self", ",", "value", ")", ":", "# data = copy.deepcopy(value)", "data", "=", "value", "# 1. Serialize", "serialized", "=", "pickle", ".", "dumps", "(", "data", ")", ".", "decode", "(", "'latin-1'", ")", "# 2. Encode", "# Percent encoding produces smaller result then urlsafe base64.", "encoded", "=", "parse", ".", "quote", "(", "serialized", ",", "''", ")", "# 3. Concatenate", "timestamp", "=", "str", "(", "int", "(", "time", ".", "time", "(", ")", ")", ")", "signature", "=", "self", ".", "_signature", "(", "self", ".", "name", ",", "encoded", ",", "timestamp", ")", "concatenated", "=", "'|'", ".", "join", "(", "[", "encoded", ",", "timestamp", ",", "signature", "]", ")", "return", "concatenated" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Session._deserialize
Deserializes and verifies the value created by :meth:`._serialize`. :param str value: The serialized value. :returns: Deserialized object.
authomatic/core.py
def _deserialize(self, value): """ Deserializes and verifies the value created by :meth:`._serialize`. :param str value: The serialized value. :returns: Deserialized object. """ # 3. Split encoded, timestamp, signature = value.split('|') # Verify signature if not signature == self._signature(self.name, encoded, timestamp): raise SessionError('Invalid signature "{0}"!'.format(signature)) # Verify timestamp if int(timestamp) < int(time.time()) - self.max_age: return None # 2. Decode decoded = parse.unquote(encoded) # 1. Deserialize deserialized = pickle.loads(decoded.encode('latin-1')) return deserialized
def _deserialize(self, value): """ Deserializes and verifies the value created by :meth:`._serialize`. :param str value: The serialized value. :returns: Deserialized object. """ # 3. Split encoded, timestamp, signature = value.split('|') # Verify signature if not signature == self._signature(self.name, encoded, timestamp): raise SessionError('Invalid signature "{0}"!'.format(signature)) # Verify timestamp if int(timestamp) < int(time.time()) - self.max_age: return None # 2. Decode decoded = parse.unquote(encoded) # 1. Deserialize deserialized = pickle.loads(decoded.encode('latin-1')) return deserialized
[ "Deserializes", "and", "verifies", "the", "value", "created", "by", ":", "meth", ":", ".", "_serialize", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L471-L500
[ "def", "_deserialize", "(", "self", ",", "value", ")", ":", "# 3. Split", "encoded", ",", "timestamp", ",", "signature", "=", "value", ".", "split", "(", "'|'", ")", "# Verify signature", "if", "not", "signature", "==", "self", ".", "_signature", "(", "self", ".", "name", ",", "encoded", ",", "timestamp", ")", ":", "raise", "SessionError", "(", "'Invalid signature \"{0}\"!'", ".", "format", "(", "signature", ")", ")", "# Verify timestamp", "if", "int", "(", "timestamp", ")", "<", "int", "(", "time", ".", "time", "(", ")", ")", "-", "self", ".", "max_age", ":", "return", "None", "# 2. Decode", "decoded", "=", "parse", ".", "unquote", "(", "encoded", ")", "# 1. Deserialize", "deserialized", "=", "pickle", ".", "loads", "(", "decoded", ".", "encode", "(", "'latin-1'", ")", ")", "return", "deserialized" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
User.to_dict
Converts the :class:`.User` instance to a :class:`dict`. :returns: :class:`dict`
authomatic/core.py
def to_dict(self): """ Converts the :class:`.User` instance to a :class:`dict`. :returns: :class:`dict` """ # copy the dictionary d = copy.copy(self.__dict__) # Keep only the provider name to avoid circular reference d['provider'] = self.provider.name d['credentials'] = self.credentials.serialize( ) if self.credentials else None d['birth_date'] = str(d['birth_date']) # Remove content d.pop('content') if isinstance(self.data, ElementTree.Element): d['data'] = None return d
def to_dict(self): """ Converts the :class:`.User` instance to a :class:`dict`. :returns: :class:`dict` """ # copy the dictionary d = copy.copy(self.__dict__) # Keep only the provider name to avoid circular reference d['provider'] = self.provider.name d['credentials'] = self.credentials.serialize( ) if self.credentials else None d['birth_date'] = str(d['birth_date']) # Remove content d.pop('content') if isinstance(self.data, ElementTree.Element): d['data'] = None return d
[ "Converts", "the", ":", "class", ":", ".", "User", "instance", "to", "a", ":", "class", ":", "dict", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L608-L632
[ "def", "to_dict", "(", "self", ")", ":", "# copy the dictionary", "d", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", "# Keep only the provider name to avoid circular reference", "d", "[", "'provider'", "]", "=", "self", ".", "provider", ".", "name", "d", "[", "'credentials'", "]", "=", "self", ".", "credentials", ".", "serialize", "(", ")", "if", "self", ".", "credentials", "else", "None", "d", "[", "'birth_date'", "]", "=", "str", "(", "d", "[", "'birth_date'", "]", ")", "# Remove content", "d", ".", "pop", "(", "'content'", ")", "if", "isinstance", "(", "self", ".", "data", ",", "ElementTree", ".", "Element", ")", ":", "d", "[", "'data'", "]", "=", "None", "return", "d" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Credentials.expire_in
Computes :attr:`.expiration_time` when the value is set.
authomatic/core.py
def expire_in(self, value): """ Computes :attr:`.expiration_time` when the value is set. """ # pylint:disable=attribute-defined-outside-init if value: self._expiration_time = int(time.time()) + int(value) self._expire_in = value
def expire_in(self, value): """ Computes :attr:`.expiration_time` when the value is set. """ # pylint:disable=attribute-defined-outside-init if value: self._expiration_time = int(time.time()) + int(value) self._expire_in = value
[ "Computes", ":", "attr", ":", ".", "expiration_time", "when", "the", "value", "is", "set", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L727-L735
[ "def", "expire_in", "(", "self", ",", "value", ")", ":", "# pylint:disable=attribute-defined-outside-init", "if", "value", ":", "self", ".", "_expiration_time", "=", "int", "(", "time", ".", "time", "(", ")", ")", "+", "int", "(", "value", ")", "self", ".", "_expire_in", "=", "value" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Credentials.valid
``True`` if credentials are valid, ``False`` if expired.
authomatic/core.py
def valid(self): """ ``True`` if credentials are valid, ``False`` if expired. """ if self.expiration_time: return self.expiration_time > int(time.time()) else: return True
def valid(self): """ ``True`` if credentials are valid, ``False`` if expired. """ if self.expiration_time: return self.expiration_time > int(time.time()) else: return True
[ "True", "if", "credentials", "are", "valid", "False", "if", "expired", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L761-L769
[ "def", "valid", "(", "self", ")", ":", "if", "self", ".", "expiration_time", ":", "return", "self", ".", "expiration_time", ">", "int", "(", "time", ".", "time", "(", ")", ")", "else", ":", "return", "True" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Credentials.expire_soon
Returns ``True`` if credentials expire sooner than specified. :param int seconds: Number of seconds. :returns: ``True`` if credentials expire sooner than specified, else ``False``.
authomatic/core.py
def expire_soon(self, seconds): """ Returns ``True`` if credentials expire sooner than specified. :param int seconds: Number of seconds. :returns: ``True`` if credentials expire sooner than specified, else ``False``. """ if self.expiration_time: return self.expiration_time < int(time.time()) + int(seconds) else: return False
def expire_soon(self, seconds): """ Returns ``True`` if credentials expire sooner than specified. :param int seconds: Number of seconds. :returns: ``True`` if credentials expire sooner than specified, else ``False``. """ if self.expiration_time: return self.expiration_time < int(time.time()) + int(seconds) else: return False
[ "Returns", "True", "if", "credentials", "expire", "sooner", "than", "specified", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L771-L787
[ "def", "expire_soon", "(", "self", ",", "seconds", ")", ":", "if", "self", ".", "expiration_time", ":", "return", "self", ".", "expiration_time", "<", "int", "(", "time", ".", "time", "(", ")", ")", "+", "int", "(", "seconds", ")", "else", ":", "return", "False" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Credentials.refresh
Refreshes the credentials only if the **provider** supports it and if it will expire in less than one day. It does nothing in other cases. .. note:: The credentials will be refreshed only if it gives sense i.e. only |oauth2|_ has the notion of credentials *refreshment/extension*. And there are also differences across providers e.g. Google supports refreshment only if there is a ``refresh_token`` in the credentials and that in turn is present only if the ``access_type`` parameter was set to ``offline`` in the **user authorization request**. :param bool force: If ``True`` the credentials will be refreshed even if they won't expire soon. :param int soon: Number of seconds specifying what means *soon*.
authomatic/core.py
def refresh(self, force=False, soon=86400): """ Refreshes the credentials only if the **provider** supports it and if it will expire in less than one day. It does nothing in other cases. .. note:: The credentials will be refreshed only if it gives sense i.e. only |oauth2|_ has the notion of credentials *refreshment/extension*. And there are also differences across providers e.g. Google supports refreshment only if there is a ``refresh_token`` in the credentials and that in turn is present only if the ``access_type`` parameter was set to ``offline`` in the **user authorization request**. :param bool force: If ``True`` the credentials will be refreshed even if they won't expire soon. :param int soon: Number of seconds specifying what means *soon*. """ if hasattr(self.provider_class, 'refresh_credentials'): if force or self.expire_soon(soon): logging.info('PROVIDER NAME: {0}'.format(self.provider_name)) return self.provider_class( self, None, self.provider_name).refresh_credentials(self)
def refresh(self, force=False, soon=86400): """ Refreshes the credentials only if the **provider** supports it and if it will expire in less than one day. It does nothing in other cases. .. note:: The credentials will be refreshed only if it gives sense i.e. only |oauth2|_ has the notion of credentials *refreshment/extension*. And there are also differences across providers e.g. Google supports refreshment only if there is a ``refresh_token`` in the credentials and that in turn is present only if the ``access_type`` parameter was set to ``offline`` in the **user authorization request**. :param bool force: If ``True`` the credentials will be refreshed even if they won't expire soon. :param int soon: Number of seconds specifying what means *soon*. """ if hasattr(self.provider_class, 'refresh_credentials'): if force or self.expire_soon(soon): logging.info('PROVIDER NAME: {0}'.format(self.provider_name)) return self.provider_class( self, None, self.provider_name).refresh_credentials(self)
[ "Refreshes", "the", "credentials", "only", "if", "the", "**", "provider", "**", "supports", "it", "and", "if", "it", "will", "expire", "in", "less", "than", "one", "day", ".", "It", "does", "nothing", "in", "other", "cases", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L789-L818
[ "def", "refresh", "(", "self", ",", "force", "=", "False", ",", "soon", "=", "86400", ")", ":", "if", "hasattr", "(", "self", ".", "provider_class", ",", "'refresh_credentials'", ")", ":", "if", "force", "or", "self", ".", "expire_soon", "(", "soon", ")", ":", "logging", ".", "info", "(", "'PROVIDER NAME: {0}'", ".", "format", "(", "self", ".", "provider_name", ")", ")", "return", "self", ".", "provider_class", "(", "self", ",", "None", ",", "self", ".", "provider_name", ")", ".", "refresh_credentials", "(", "self", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Credentials.serialize
Converts the credentials to a percent encoded string to be stored for later use. :returns: :class:`string`
authomatic/core.py
def serialize(self): """ Converts the credentials to a percent encoded string to be stored for later use. :returns: :class:`string` """ if self.provider_id is None: raise ConfigError( 'To serialize credentials you need to specify a ' 'unique integer under the "id" key in the config ' 'for each provider!') # Get the provider type specific items. rest = self.provider_type_class().to_tuple(self) # Provider ID and provider type ID are always the first two items. result = (self.provider_id, self.provider_type_id) + rest # Make sure that all items are strings. stringified = [str(i) for i in result] # Concatenate by newline. concatenated = '\n'.join(stringified) # Percent encode. return parse.quote(concatenated, '')
def serialize(self): """ Converts the credentials to a percent encoded string to be stored for later use. :returns: :class:`string` """ if self.provider_id is None: raise ConfigError( 'To serialize credentials you need to specify a ' 'unique integer under the "id" key in the config ' 'for each provider!') # Get the provider type specific items. rest = self.provider_type_class().to_tuple(self) # Provider ID and provider type ID are always the first two items. result = (self.provider_id, self.provider_type_id) + rest # Make sure that all items are strings. stringified = [str(i) for i in result] # Concatenate by newline. concatenated = '\n'.join(stringified) # Percent encode. return parse.quote(concatenated, '')
[ "Converts", "the", "credentials", "to", "a", "percent", "encoded", "string", "to", "be", "stored", "for", "later", "use", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L847-L876
[ "def", "serialize", "(", "self", ")", ":", "if", "self", ".", "provider_id", "is", "None", ":", "raise", "ConfigError", "(", "'To serialize credentials you need to specify a '", "'unique integer under the \"id\" key in the config '", "'for each provider!'", ")", "# Get the provider type specific items.", "rest", "=", "self", ".", "provider_type_class", "(", ")", ".", "to_tuple", "(", "self", ")", "# Provider ID and provider type ID are always the first two items.", "result", "=", "(", "self", ".", "provider_id", ",", "self", ".", "provider_type_id", ")", "+", "rest", "# Make sure that all items are strings.", "stringified", "=", "[", "str", "(", "i", ")", "for", "i", "in", "result", "]", "# Concatenate by newline.", "concatenated", "=", "'\\n'", ".", "join", "(", "stringified", ")", "# Percent encode.", "return", "parse", ".", "quote", "(", "concatenated", ",", "''", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Credentials.deserialize
A *class method* which reconstructs credentials created by :meth:`serialize`. You can also pass it a :class:`.Credentials` instance. :param dict config: The same :doc:`config` used in the :func:`.login` to get the credentials. :param str credentials: :class:`string` The serialized credentials or :class:`.Credentials` instance. :returns: :class:`.Credentials`
authomatic/core.py
def deserialize(cls, config, credentials): """ A *class method* which reconstructs credentials created by :meth:`serialize`. You can also pass it a :class:`.Credentials` instance. :param dict config: The same :doc:`config` used in the :func:`.login` to get the credentials. :param str credentials: :class:`string` The serialized credentials or :class:`.Credentials` instance. :returns: :class:`.Credentials` """ # Accept both serialized and normal. if isinstance(credentials, Credentials): return credentials decoded = parse.unquote(credentials) split = decoded.split('\n') # We need the provider ID to move forward. if split[0] is None: raise CredentialsError( 'To deserialize credentials you need to specify a unique ' 'integer under the "id" key in the config for each provider!') # Get provider config by short name. provider_name = id_to_name(config, int(split[0])) cfg = config.get(provider_name) # Get the provider class. ProviderClass = resolve_provider_class(cfg.get('class_')) deserialized = Credentials(config) deserialized.provider_id = provider_id deserialized.provider_type = ProviderClass.get_type() deserialized.provider_type_id = split[1] deserialized.provider_class = ProviderClass deserialized.provider_name = provider_name deserialized.provider_class = ProviderClass # Add provider type specific properties. return ProviderClass.reconstruct(split[2:], deserialized, cfg)
def deserialize(cls, config, credentials): """ A *class method* which reconstructs credentials created by :meth:`serialize`. You can also pass it a :class:`.Credentials` instance. :param dict config: The same :doc:`config` used in the :func:`.login` to get the credentials. :param str credentials: :class:`string` The serialized credentials or :class:`.Credentials` instance. :returns: :class:`.Credentials` """ # Accept both serialized and normal. if isinstance(credentials, Credentials): return credentials decoded = parse.unquote(credentials) split = decoded.split('\n') # We need the provider ID to move forward. if split[0] is None: raise CredentialsError( 'To deserialize credentials you need to specify a unique ' 'integer under the "id" key in the config for each provider!') # Get provider config by short name. provider_name = id_to_name(config, int(split[0])) cfg = config.get(provider_name) # Get the provider class. ProviderClass = resolve_provider_class(cfg.get('class_')) deserialized = Credentials(config) deserialized.provider_id = provider_id deserialized.provider_type = ProviderClass.get_type() deserialized.provider_type_id = split[1] deserialized.provider_class = ProviderClass deserialized.provider_name = provider_name deserialized.provider_class = ProviderClass # Add provider type specific properties. return ProviderClass.reconstruct(split[2:], deserialized, cfg)
[ "A", "*", "class", "method", "*", "which", "reconstructs", "credentials", "created", "by", ":", "meth", ":", "serialize", ".", "You", "can", "also", "pass", "it", "a", ":", "class", ":", ".", "Credentials", "instance", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L879-L928
[ "def", "deserialize", "(", "cls", ",", "config", ",", "credentials", ")", ":", "# Accept both serialized and normal.", "if", "isinstance", "(", "credentials", ",", "Credentials", ")", ":", "return", "credentials", "decoded", "=", "parse", ".", "unquote", "(", "credentials", ")", "split", "=", "decoded", ".", "split", "(", "'\\n'", ")", "# We need the provider ID to move forward.", "if", "split", "[", "0", "]", "is", "None", ":", "raise", "CredentialsError", "(", "'To deserialize credentials you need to specify a unique '", "'integer under the \"id\" key in the config for each provider!'", ")", "# Get provider config by short name.", "provider_name", "=", "id_to_name", "(", "config", ",", "int", "(", "split", "[", "0", "]", ")", ")", "cfg", "=", "config", ".", "get", "(", "provider_name", ")", "# Get the provider class.", "ProviderClass", "=", "resolve_provider_class", "(", "cfg", ".", "get", "(", "'class_'", ")", ")", "deserialized", "=", "Credentials", "(", "config", ")", "deserialized", ".", "provider_id", "=", "provider_id", "deserialized", ".", "provider_type", "=", "ProviderClass", ".", "get_type", "(", ")", "deserialized", ".", "provider_type_id", "=", "split", "[", "1", "]", "deserialized", ".", "provider_class", "=", "ProviderClass", "deserialized", ".", "provider_name", "=", "provider_name", "deserialized", ".", "provider_class", "=", "ProviderClass", "# Add provider type specific properties.", "return", "ProviderClass", ".", "reconstruct", "(", "split", "[", "2", ":", "]", ",", "deserialized", ",", "cfg", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
LoginResult.popup_js
Returns JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javascript.js <js>`. #. Calls the JavasScript callback specified by :data:`callback_name` on the opener of the *login handler popup* and passes it the *login result* JSON object as first argument and the `closer` function which you should call in your callback to close the popup. :param str callback_name: The name of the javascript callback e.g ``foo.bar.loginCallback`` will result in ``window.opener.foo.bar.loginCallback(result);`` in the HTML. :param int indent: The number of spaces to indent the JSON result object. If ``0`` or negative, only newlines are added. If ``None``, no newlines are added. :param custom: Any JSON serializable object that will be passed to the ``result.custom`` attribute. :param str stay_open: If ``True``, the popup will stay open. :returns: :class:`str` with JavaScript.
authomatic/core.py
def popup_js(self, callback_name=None, indent=None, custom=None, stay_open=False): """ Returns JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javascript.js <js>`. #. Calls the JavasScript callback specified by :data:`callback_name` on the opener of the *login handler popup* and passes it the *login result* JSON object as first argument and the `closer` function which you should call in your callback to close the popup. :param str callback_name: The name of the javascript callback e.g ``foo.bar.loginCallback`` will result in ``window.opener.foo.bar.loginCallback(result);`` in the HTML. :param int indent: The number of spaces to indent the JSON result object. If ``0`` or negative, only newlines are added. If ``None``, no newlines are added. :param custom: Any JSON serializable object that will be passed to the ``result.custom`` attribute. :param str stay_open: If ``True``, the popup will stay open. :returns: :class:`str` with JavaScript. """ custom_callback = """ try {{ window.opener.{cb}(result, closer); }} catch(e) {{}} """.format(cb=callback_name) if callback_name else '' # TODO: Move the window.close() to the opener return """ (function(){{ closer = function(){{ window.close(); }}; var result = {result}; result.custom = {custom}; {custom_callback} try {{ window.opener.authomatic.loginComplete(result, closer); }} catch(e) {{}} }})(); """.format(result=self.to_json(indent), custom=json.dumps(custom), custom_callback=custom_callback, stay_open='// ' if stay_open else '')
def popup_js(self, callback_name=None, indent=None, custom=None, stay_open=False): """ Returns JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javascript.js <js>`. #. Calls the JavasScript callback specified by :data:`callback_name` on the opener of the *login handler popup* and passes it the *login result* JSON object as first argument and the `closer` function which you should call in your callback to close the popup. :param str callback_name: The name of the javascript callback e.g ``foo.bar.loginCallback`` will result in ``window.opener.foo.bar.loginCallback(result);`` in the HTML. :param int indent: The number of spaces to indent the JSON result object. If ``0`` or negative, only newlines are added. If ``None``, no newlines are added. :param custom: Any JSON serializable object that will be passed to the ``result.custom`` attribute. :param str stay_open: If ``True``, the popup will stay open. :returns: :class:`str` with JavaScript. """ custom_callback = """ try {{ window.opener.{cb}(result, closer); }} catch(e) {{}} """.format(cb=callback_name) if callback_name else '' # TODO: Move the window.close() to the opener return """ (function(){{ closer = function(){{ window.close(); }}; var result = {result}; result.custom = {custom}; {custom_callback} try {{ window.opener.authomatic.loginComplete(result, closer); }} catch(e) {{}} }})(); """.format(result=self.to_json(indent), custom=json.dumps(custom), custom_callback=custom_callback, stay_open='// ' if stay_open else '')
[ "Returns", "JavaScript", "that", ":" ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L943-L1004
[ "def", "popup_js", "(", "self", ",", "callback_name", "=", "None", ",", "indent", "=", "None", ",", "custom", "=", "None", ",", "stay_open", "=", "False", ")", ":", "custom_callback", "=", "\"\"\"\n try {{ window.opener.{cb}(result, closer); }} catch(e) {{}}\n \"\"\"", ".", "format", "(", "cb", "=", "callback_name", ")", "if", "callback_name", "else", "''", "# TODO: Move the window.close() to the opener", "return", "\"\"\"\n (function(){{\n\n closer = function(){{\n window.close();\n }};\n\n var result = {result};\n result.custom = {custom};\n\n {custom_callback}\n\n try {{\n window.opener.authomatic.loginComplete(result, closer);\n }} catch(e) {{}}\n\n }})();\n\n \"\"\"", ".", "format", "(", "result", "=", "self", ".", "to_json", "(", "indent", ")", ",", "custom", "=", "json", ".", "dumps", "(", "custom", ")", ",", "custom_callback", "=", "custom_callback", ",", "stay_open", "=", "'// '", "if", "stay_open", "else", "''", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
LoginResult.popup_html
Returns a HTML with JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javascript.js <js>`. #. Calls the JavasScript callback specified by :data:`callback_name` on the opener of the *login handler popup* and passes it the *login result* JSON object as first argument and the `closer` function which you should call in your callback to close the popup. :param str callback_name: The name of the javascript callback e.g ``foo.bar.loginCallback`` will result in ``window.opener.foo.bar.loginCallback(result);`` in the HTML. :param int indent: The number of spaces to indent the JSON result object. If ``0`` or negative, only newlines are added. If ``None``, no newlines are added. :param str title: The text of the HTML title. You can use ``{0}`` tag inside, which will be replaced by the provider name. :param custom: Any JSON serializable object that will be passed to the ``result.custom`` attribute. :param str stay_open: If ``True``, the popup will stay open. :returns: :class:`str` with HTML.
authomatic/core.py
def popup_html(self, callback_name=None, indent=None, title='Login | {0}', custom=None, stay_open=False): """ Returns a HTML with JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javascript.js <js>`. #. Calls the JavasScript callback specified by :data:`callback_name` on the opener of the *login handler popup* and passes it the *login result* JSON object as first argument and the `closer` function which you should call in your callback to close the popup. :param str callback_name: The name of the javascript callback e.g ``foo.bar.loginCallback`` will result in ``window.opener.foo.bar.loginCallback(result);`` in the HTML. :param int indent: The number of spaces to indent the JSON result object. If ``0`` or negative, only newlines are added. If ``None``, no newlines are added. :param str title: The text of the HTML title. You can use ``{0}`` tag inside, which will be replaced by the provider name. :param custom: Any JSON serializable object that will be passed to the ``result.custom`` attribute. :param str stay_open: If ``True``, the popup will stay open. :returns: :class:`str` with HTML. """ return """ <!DOCTYPE html> <html> <head><title>{title}</title></head> <body> <script type="text/javascript"> {js} </script> </body> </html> """.format( title=title.format(self.provider.name if self.provider else ''), js=self.popup_js(callback_name, indent, custom, stay_open) )
def popup_html(self, callback_name=None, indent=None, title='Login | {0}', custom=None, stay_open=False): """ Returns a HTML with JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javascript.js <js>`. #. Calls the JavasScript callback specified by :data:`callback_name` on the opener of the *login handler popup* and passes it the *login result* JSON object as first argument and the `closer` function which you should call in your callback to close the popup. :param str callback_name: The name of the javascript callback e.g ``foo.bar.loginCallback`` will result in ``window.opener.foo.bar.loginCallback(result);`` in the HTML. :param int indent: The number of spaces to indent the JSON result object. If ``0`` or negative, only newlines are added. If ``None``, no newlines are added. :param str title: The text of the HTML title. You can use ``{0}`` tag inside, which will be replaced by the provider name. :param custom: Any JSON serializable object that will be passed to the ``result.custom`` attribute. :param str stay_open: If ``True``, the popup will stay open. :returns: :class:`str` with HTML. """ return """ <!DOCTYPE html> <html> <head><title>{title}</title></head> <body> <script type="text/javascript"> {js} </script> </body> </html> """.format( title=title.format(self.provider.name if self.provider else ''), js=self.popup_js(callback_name, indent, custom, stay_open) )
[ "Returns", "a", "HTML", "with", "JavaScript", "that", ":" ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1006-L1058
[ "def", "popup_html", "(", "self", ",", "callback_name", "=", "None", ",", "indent", "=", "None", ",", "title", "=", "'Login | {0}'", ",", "custom", "=", "None", ",", "stay_open", "=", "False", ")", ":", "return", "\"\"\"\n <!DOCTYPE html>\n <html>\n <head><title>{title}</title></head>\n <body>\n <script type=\"text/javascript\">\n {js}\n </script>\n </body>\n </html>\n \"\"\"", ".", "format", "(", "title", "=", "title", ".", "format", "(", "self", ".", "provider", ".", "name", "if", "self", ".", "provider", "else", "''", ")", ",", "js", "=", "self", ".", "popup_js", "(", "callback_name", ",", "indent", ",", "custom", ",", "stay_open", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Response.is_binary_string
Return true if string is binary data.
authomatic/core.py
def is_binary_string(content): """ Return true if string is binary data. """ textchars = (bytearray([7, 8, 9, 10, 12, 13, 27]) + bytearray(range(0x20, 0x100))) return bool(content.translate(None, textchars))
def is_binary_string(content): """ Return true if string is binary data. """ textchars = (bytearray([7, 8, 9, 10, 12, 13, 27]) + bytearray(range(0x20, 0x100))) return bool(content.translate(None, textchars))
[ "Return", "true", "if", "string", "is", "binary", "data", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1142-L1149
[ "def", "is_binary_string", "(", "content", ")", ":", "textchars", "=", "(", "bytearray", "(", "[", "7", ",", "8", ",", "9", ",", "10", ",", "12", ",", "13", ",", "27", "]", ")", "+", "bytearray", "(", "range", "(", "0x20", ",", "0x100", ")", ")", ")", "return", "bool", "(", "content", ".", "translate", "(", "None", ",", "textchars", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Response.content
The whole response content.
authomatic/core.py
def content(self): """ The whole response content. """ if not self._content: content = self.httplib_response.read() if self.is_binary_string(content): self._content = content else: self._content = content.decode('utf-8') return self._content
def content(self): """ The whole response content. """ if not self._content: content = self.httplib_response.read() if self.is_binary_string(content): self._content = content else: self._content = content.decode('utf-8') return self._content
[ "The", "whole", "response", "content", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1152-L1163
[ "def", "content", "(", "self", ")", ":", "if", "not", "self", ".", "_content", ":", "content", "=", "self", ".", "httplib_response", ".", "read", "(", ")", "if", "self", ".", "is_binary_string", "(", "content", ")", ":", "self", ".", "_content", "=", "content", "else", ":", "self", ".", "_content", "=", "content", ".", "decode", "(", "'utf-8'", ")", "return", "self", ".", "_content" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Response.data
A :class:`dict` of data parsed from :attr:`.content`.
authomatic/core.py
def data(self): """ A :class:`dict` of data parsed from :attr:`.content`. """ if not self._data: self._data = self.content_parser(self.content) return self._data
def data(self): """ A :class:`dict` of data parsed from :attr:`.content`. """ if not self._data: self._data = self.content_parser(self.content) return self._data
[ "A", ":", "class", ":", "dict", "of", "data", "parsed", "from", ":", "attr", ":", ".", "content", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1166-L1173
[ "def", "data", "(", "self", ")", ":", "if", "not", "self", ".", "_data", ":", "self", ".", "_data", "=", "self", ".", "content_parser", "(", "self", ".", "content", ")", "return", "self", ".", "_data" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Authomatic.login
If :data:`provider_name` specified, launches the login procedure for corresponding :doc:`provider </reference/providers>` and returns :class:`.LoginResult`. If :data:`provider_name` is empty, acts like :meth:`.Authomatic.backend`. .. warning:: The method redirects the **user** to the **provider** which in turn redirects **him/her** back to the *request handler* where it has been called. :param str provider_name: Name of the provider as specified in the keys of the :doc:`config`. :param callable callback: If specified the method will call the callback with :class:`.LoginResult` passed as argument and will return nothing. :param bool report_errors: .. note:: Accepts additional keyword arguments that will be passed to :doc:`provider <providers>` constructor. :returns: :class:`.LoginResult`
authomatic/core.py
def login(self, adapter, provider_name, callback=None, session=None, session_saver=None, **kwargs): """ If :data:`provider_name` specified, launches the login procedure for corresponding :doc:`provider </reference/providers>` and returns :class:`.LoginResult`. If :data:`provider_name` is empty, acts like :meth:`.Authomatic.backend`. .. warning:: The method redirects the **user** to the **provider** which in turn redirects **him/her** back to the *request handler* where it has been called. :param str provider_name: Name of the provider as specified in the keys of the :doc:`config`. :param callable callback: If specified the method will call the callback with :class:`.LoginResult` passed as argument and will return nothing. :param bool report_errors: .. note:: Accepts additional keyword arguments that will be passed to :doc:`provider <providers>` constructor. :returns: :class:`.LoginResult` """ if provider_name: # retrieve required settings for current provider and raise # exceptions if missing provider_settings = self.config.get(provider_name) if not provider_settings: raise ConfigError('Provider name "{0}" not specified!' .format(provider_name)) if not (session is None or session_saver is None): session = session session_saver = session_saver else: session = Session(adapter=adapter, secret=self.secret, max_age=self.session_max_age, name=self.prefix, secure=self.secure_cookie) session_saver = session.save # Resolve provider class. class_ = provider_settings.get('class_') if not class_: raise ConfigError( 'The "class_" key not specified in the config' ' for provider {0}!'.format(provider_name)) ProviderClass = resolve_provider_class(class_) # FIXME: Find a nicer solution ProviderClass._logger = self._logger # instantiate provider class provider = ProviderClass(self, adapter=adapter, provider_name=provider_name, callback=callback, session=session, session_saver=session_saver, **kwargs) # return login result return provider.login() else: # Act like backend. self.backend(adapter)
def login(self, adapter, provider_name, callback=None, session=None, session_saver=None, **kwargs): """ If :data:`provider_name` specified, launches the login procedure for corresponding :doc:`provider </reference/providers>` and returns :class:`.LoginResult`. If :data:`provider_name` is empty, acts like :meth:`.Authomatic.backend`. .. warning:: The method redirects the **user** to the **provider** which in turn redirects **him/her** back to the *request handler* where it has been called. :param str provider_name: Name of the provider as specified in the keys of the :doc:`config`. :param callable callback: If specified the method will call the callback with :class:`.LoginResult` passed as argument and will return nothing. :param bool report_errors: .. note:: Accepts additional keyword arguments that will be passed to :doc:`provider <providers>` constructor. :returns: :class:`.LoginResult` """ if provider_name: # retrieve required settings for current provider and raise # exceptions if missing provider_settings = self.config.get(provider_name) if not provider_settings: raise ConfigError('Provider name "{0}" not specified!' .format(provider_name)) if not (session is None or session_saver is None): session = session session_saver = session_saver else: session = Session(adapter=adapter, secret=self.secret, max_age=self.session_max_age, name=self.prefix, secure=self.secure_cookie) session_saver = session.save # Resolve provider class. class_ = provider_settings.get('class_') if not class_: raise ConfigError( 'The "class_" key not specified in the config' ' for provider {0}!'.format(provider_name)) ProviderClass = resolve_provider_class(class_) # FIXME: Find a nicer solution ProviderClass._logger = self._logger # instantiate provider class provider = ProviderClass(self, adapter=adapter, provider_name=provider_name, callback=callback, session=session, session_saver=session_saver, **kwargs) # return login result return provider.login() else: # Act like backend. self.backend(adapter)
[ "If", ":", "data", ":", "provider_name", "specified", "launches", "the", "login", "procedure", "for", "corresponding", ":", "doc", ":", "provider", "<", "/", "reference", "/", "providers", ">", "and", "returns", ":", "class", ":", ".", "LoginResult", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1336-L1416
[ "def", "login", "(", "self", ",", "adapter", ",", "provider_name", ",", "callback", "=", "None", ",", "session", "=", "None", ",", "session_saver", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "provider_name", ":", "# retrieve required settings for current provider and raise", "# exceptions if missing", "provider_settings", "=", "self", ".", "config", ".", "get", "(", "provider_name", ")", "if", "not", "provider_settings", ":", "raise", "ConfigError", "(", "'Provider name \"{0}\" not specified!'", ".", "format", "(", "provider_name", ")", ")", "if", "not", "(", "session", "is", "None", "or", "session_saver", "is", "None", ")", ":", "session", "=", "session", "session_saver", "=", "session_saver", "else", ":", "session", "=", "Session", "(", "adapter", "=", "adapter", ",", "secret", "=", "self", ".", "secret", ",", "max_age", "=", "self", ".", "session_max_age", ",", "name", "=", "self", ".", "prefix", ",", "secure", "=", "self", ".", "secure_cookie", ")", "session_saver", "=", "session", ".", "save", "# Resolve provider class.", "class_", "=", "provider_settings", ".", "get", "(", "'class_'", ")", "if", "not", "class_", ":", "raise", "ConfigError", "(", "'The \"class_\" key not specified in the config'", "' for provider {0}!'", ".", "format", "(", "provider_name", ")", ")", "ProviderClass", "=", "resolve_provider_class", "(", "class_", ")", "# FIXME: Find a nicer solution", "ProviderClass", ".", "_logger", "=", "self", ".", "_logger", "# instantiate provider class", "provider", "=", "ProviderClass", "(", "self", ",", "adapter", "=", "adapter", ",", "provider_name", "=", "provider_name", ",", "callback", "=", "callback", ",", "session", "=", "session", ",", "session_saver", "=", "session_saver", ",", "*", "*", "kwargs", ")", "# return login result", "return", "provider", ".", "login", "(", ")", "else", ":", "# Act like backend.", "self", ".", "backend", "(", "adapter", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Authomatic.access
Accesses **protected resource** on behalf of the **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). :param str url: The **protected resource** URL. :param str method: HTTP method of the request. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Maximum number of HTTP redirects to follow. :param function content_parser: A function to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. :returns: :class:`.Response`
authomatic/core.py
def access(self, credentials, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None): """ Accesses **protected resource** on behalf of the **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). :param str url: The **protected resource** URL. :param str method: HTTP method of the request. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Maximum number of HTTP redirects to follow. :param function content_parser: A function to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. :returns: :class:`.Response` """ # Deserialize credentials. credentials = Credentials.deserialize(self.config, credentials) # Resolve provider class. ProviderClass = credentials.provider_class logging.info('ACCESS HEADERS: {0}'.format(headers)) # Access resource and return response. provider = ProviderClass( self, adapter=None, provider_name=credentials.provider_name) provider.credentials = credentials return provider.access(url=url, params=params, method=method, headers=headers, body=body, max_redirects=max_redirects, content_parser=content_parser)
def access(self, credentials, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None): """ Accesses **protected resource** on behalf of the **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). :param str url: The **protected resource** URL. :param str method: HTTP method of the request. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Maximum number of HTTP redirects to follow. :param function content_parser: A function to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. :returns: :class:`.Response` """ # Deserialize credentials. credentials = Credentials.deserialize(self.config, credentials) # Resolve provider class. ProviderClass = credentials.provider_class logging.info('ACCESS HEADERS: {0}'.format(headers)) # Access resource and return response. provider = ProviderClass( self, adapter=None, provider_name=credentials.provider_name) provider.credentials = credentials return provider.access(url=url, params=params, method=method, headers=headers, body=body, max_redirects=max_redirects, content_parser=content_parser)
[ "Accesses", "**", "protected", "resource", "**", "on", "behalf", "of", "the", "**", "user", "**", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1433-L1483
[ "def", "access", "(", "self", ",", "credentials", ",", "url", ",", "params", "=", "None", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "max_redirects", "=", "5", ",", "content_parser", "=", "None", ")", ":", "# Deserialize credentials.", "credentials", "=", "Credentials", ".", "deserialize", "(", "self", ".", "config", ",", "credentials", ")", "# Resolve provider class.", "ProviderClass", "=", "credentials", ".", "provider_class", "logging", ".", "info", "(", "'ACCESS HEADERS: {0}'", ".", "format", "(", "headers", ")", ")", "# Access resource and return response.", "provider", "=", "ProviderClass", "(", "self", ",", "adapter", "=", "None", ",", "provider_name", "=", "credentials", ".", "provider_name", ")", "provider", ".", "credentials", "=", "credentials", "return", "provider", ".", "access", "(", "url", "=", "url", ",", "params", "=", "params", ",", "method", "=", "method", ",", "headers", "=", "headers", ",", "body", "=", "body", ",", "max_redirects", "=", "max_redirects", ",", "content_parser", "=", "content_parser", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Authomatic.request_elements
Creates request elements for accessing **protected resource of a user**. Required arguments are :data:`credentials` and :data:`url`. You can pass :data:`credentials`, :data:`url`, :data:`method`, and :data:`params` as a JSON object. :param credentials: The **user's** credentials (can be serialized). :param str url: The url of the protected resource. :param str method: The HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: Dictionary of request headers. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param str json_input: you can pass :data:`credentials`, :data:`url`, :data:`method`, :data:`params` and :data:`headers` in a JSON object. Values from arguments will be used for missing properties. :: { "credentials": "###", "url": "https://example.com/api", "method": "POST", "params": { "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." } :param bool return_json: if ``True`` the function returns a json object. :: { "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." } :returns: :class:`.RequestElements` or JSON string.
authomatic/core.py
def request_elements( self, credentials=None, url=None, method='GET', params=None, headers=None, body='', json_input=None, return_json=False ): """ Creates request elements for accessing **protected resource of a user**. Required arguments are :data:`credentials` and :data:`url`. You can pass :data:`credentials`, :data:`url`, :data:`method`, and :data:`params` as a JSON object. :param credentials: The **user's** credentials (can be serialized). :param str url: The url of the protected resource. :param str method: The HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: Dictionary of request headers. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param str json_input: you can pass :data:`credentials`, :data:`url`, :data:`method`, :data:`params` and :data:`headers` in a JSON object. Values from arguments will be used for missing properties. :: { "credentials": "###", "url": "https://example.com/api", "method": "POST", "params": { "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." } :param bool return_json: if ``True`` the function returns a json object. :: { "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." } :returns: :class:`.RequestElements` or JSON string. """ # Parse values from JSON if json_input: parsed_input = json.loads(json_input) credentials = parsed_input.get('credentials', credentials) url = parsed_input.get('url', url) method = parsed_input.get('method', method) params = parsed_input.get('params', params) headers = parsed_input.get('headers', headers) body = parsed_input.get('body', body) if not credentials and url: raise RequestElementsError( 'To create request elements, you must provide credentials ' 'and URL either as keyword arguments or in the JSON object!') # Get the provider class credentials = Credentials.deserialize(self.config, credentials) ProviderClass = credentials.provider_class # Create request elements request_elements = ProviderClass.create_request_elements( ProviderClass.PROTECTED_RESOURCE_REQUEST_TYPE, credentials=credentials, url=url, method=method, params=params, headers=headers, body=body) if return_json: return request_elements.to_json() else: return request_elements
def request_elements( self, credentials=None, url=None, method='GET', params=None, headers=None, body='', json_input=None, return_json=False ): """ Creates request elements for accessing **protected resource of a user**. Required arguments are :data:`credentials` and :data:`url`. You can pass :data:`credentials`, :data:`url`, :data:`method`, and :data:`params` as a JSON object. :param credentials: The **user's** credentials (can be serialized). :param str url: The url of the protected resource. :param str method: The HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: Dictionary of request headers. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param str json_input: you can pass :data:`credentials`, :data:`url`, :data:`method`, :data:`params` and :data:`headers` in a JSON object. Values from arguments will be used for missing properties. :: { "credentials": "###", "url": "https://example.com/api", "method": "POST", "params": { "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." } :param bool return_json: if ``True`` the function returns a json object. :: { "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." } :returns: :class:`.RequestElements` or JSON string. """ # Parse values from JSON if json_input: parsed_input = json.loads(json_input) credentials = parsed_input.get('credentials', credentials) url = parsed_input.get('url', url) method = parsed_input.get('method', method) params = parsed_input.get('params', params) headers = parsed_input.get('headers', headers) body = parsed_input.get('body', body) if not credentials and url: raise RequestElementsError( 'To create request elements, you must provide credentials ' 'and URL either as keyword arguments or in the JSON object!') # Get the provider class credentials = Credentials.deserialize(self.config, credentials) ProviderClass = credentials.provider_class # Create request elements request_elements = ProviderClass.create_request_elements( ProviderClass.PROTECTED_RESOURCE_REQUEST_TYPE, credentials=credentials, url=url, method=method, params=params, headers=headers, body=body) if return_json: return request_elements.to_json() else: return request_elements
[ "Creates", "request", "elements", "for", "accessing", "**", "protected", "resource", "of", "a", "user", "**", ".", "Required", "arguments", "are", ":", "data", ":", "credentials", "and", ":", "data", ":", "url", ".", "You", "can", "pass", ":", "data", ":", "credentials", ":", "data", ":", "url", ":", "data", ":", "method", "and", ":", "data", ":", "params", "as", "a", "JSON", "object", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1501-L1608
[ "def", "request_elements", "(", "self", ",", "credentials", "=", "None", ",", "url", "=", "None", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "json_input", "=", "None", ",", "return_json", "=", "False", ")", ":", "# Parse values from JSON", "if", "json_input", ":", "parsed_input", "=", "json", ".", "loads", "(", "json_input", ")", "credentials", "=", "parsed_input", ".", "get", "(", "'credentials'", ",", "credentials", ")", "url", "=", "parsed_input", ".", "get", "(", "'url'", ",", "url", ")", "method", "=", "parsed_input", ".", "get", "(", "'method'", ",", "method", ")", "params", "=", "parsed_input", ".", "get", "(", "'params'", ",", "params", ")", "headers", "=", "parsed_input", ".", "get", "(", "'headers'", ",", "headers", ")", "body", "=", "parsed_input", ".", "get", "(", "'body'", ",", "body", ")", "if", "not", "credentials", "and", "url", ":", "raise", "RequestElementsError", "(", "'To create request elements, you must provide credentials '", "'and URL either as keyword arguments or in the JSON object!'", ")", "# Get the provider class", "credentials", "=", "Credentials", ".", "deserialize", "(", "self", ".", "config", ",", "credentials", ")", "ProviderClass", "=", "credentials", ".", "provider_class", "# Create request elements", "request_elements", "=", "ProviderClass", ".", "create_request_elements", "(", "ProviderClass", ".", "PROTECTED_RESOURCE_REQUEST_TYPE", ",", "credentials", "=", "credentials", ",", "url", "=", "url", ",", "method", "=", "method", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "body", "=", "body", ")", "if", "return_json", ":", "return", "request_elements", ".", "to_json", "(", ")", "else", ":", "return", "request_elements" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Authomatic.backend
Converts a *request handler* to a JSON backend which you can use with :ref:`authomatic.js <js>`. Just call it inside a *request handler* like this: :: class JSONHandler(webapp2.RequestHandler): def get(self): authomatic.backend(Webapp2Adapter(self)) :param adapter: The only argument is an :doc:`adapter <adapters>`. The *request handler* will now accept these request parameters: :param str type: Type of the request. Either ``auto``, ``fetch`` or ``elements``. Default is ``auto``. :param str credentials: Serialized :class:`.Credentials`. :param str url: URL of the **protected resource** request. :param str method: HTTP method of the **protected resource** request. :param str body: HTTP body of the **protected resource** request. :param JSON params: HTTP params of the **protected resource** request as a JSON object. :param JSON headers: HTTP headers of the **protected resource** request as a JSON object. :param JSON json: You can pass all of the aforementioned params except ``type`` in a JSON object. .. code-block:: javascript { "credentials": "######", "url": "https://example.com", "method": "POST", "params": {"foo": "bar"}, "headers": {"baz": "bing"}, "body": "the body of the request" } Depending on the ``type`` param, the handler will either write a JSON object with *request elements* to the response, and add an ``Authomatic-Response-To: elements`` response header, ... .. code-block:: javascript { "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" } } ... or make a fetch to the **protected resource** and forward it's response content, status and headers with an additional ``Authomatic-Response-To: fetch`` header to the response. .. warning:: The backend will not work if you write anything to the response in the handler!
authomatic/core.py
def backend(self, adapter): """ Converts a *request handler* to a JSON backend which you can use with :ref:`authomatic.js <js>`. Just call it inside a *request handler* like this: :: class JSONHandler(webapp2.RequestHandler): def get(self): authomatic.backend(Webapp2Adapter(self)) :param adapter: The only argument is an :doc:`adapter <adapters>`. The *request handler* will now accept these request parameters: :param str type: Type of the request. Either ``auto``, ``fetch`` or ``elements``. Default is ``auto``. :param str credentials: Serialized :class:`.Credentials`. :param str url: URL of the **protected resource** request. :param str method: HTTP method of the **protected resource** request. :param str body: HTTP body of the **protected resource** request. :param JSON params: HTTP params of the **protected resource** request as a JSON object. :param JSON headers: HTTP headers of the **protected resource** request as a JSON object. :param JSON json: You can pass all of the aforementioned params except ``type`` in a JSON object. .. code-block:: javascript { "credentials": "######", "url": "https://example.com", "method": "POST", "params": {"foo": "bar"}, "headers": {"baz": "bing"}, "body": "the body of the request" } Depending on the ``type`` param, the handler will either write a JSON object with *request elements* to the response, and add an ``Authomatic-Response-To: elements`` response header, ... .. code-block:: javascript { "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" } } ... or make a fetch to the **protected resource** and forward it's response content, status and headers with an additional ``Authomatic-Response-To: fetch`` header to the response. .. warning:: The backend will not work if you write anything to the response in the handler! """ AUTHOMATIC_HEADER = 'Authomatic-Response-To' # Collect request params request_type = adapter.params.get('type', 'auto') json_input = adapter.params.get('json') credentials = adapter.params.get('credentials') url = adapter.params.get('url') method = adapter.params.get('method', 'GET') body = adapter.params.get('body', '') params = adapter.params.get('params') params = json.loads(params) if params else {} headers = adapter.params.get('headers') headers = json.loads(headers) if headers else {} ProviderClass = Credentials.deserialize( self.config, credentials).provider_class if request_type == 'auto': # If there is a "callback" param, it's a JSONP request. jsonp = params.get('callback') # JSONP is possible only with GET method. if ProviderClass.supports_jsonp and method is 'GET': request_type = 'elements' else: # Remove the JSONP callback if jsonp: params.pop('callback') request_type = 'fetch' if request_type == 'fetch': # Access protected resource response = self.access( credentials, url, params, method, headers, body) result = response.content # Forward status adapter.status = str(response.status) + ' ' + str(response.reason) # Forward headers for k, v in response.getheaders(): logging.info(' {0}: {1}'.format(k, v)) adapter.set_header(k, v) elif request_type == 'elements': # Create request elements if json_input: result = self.request_elements( json_input=json_input, return_json=True) else: result = self.request_elements(credentials=credentials, url=url, method=method, params=params, headers=headers, body=body, return_json=True) adapter.set_header('Content-Type', 'application/json') else: result = '{"error": "Bad Request!"}' # Add the authomatic header adapter.set_header(AUTHOMATIC_HEADER, request_type) # Write result to response adapter.write(result)
def backend(self, adapter): """ Converts a *request handler* to a JSON backend which you can use with :ref:`authomatic.js <js>`. Just call it inside a *request handler* like this: :: class JSONHandler(webapp2.RequestHandler): def get(self): authomatic.backend(Webapp2Adapter(self)) :param adapter: The only argument is an :doc:`adapter <adapters>`. The *request handler* will now accept these request parameters: :param str type: Type of the request. Either ``auto``, ``fetch`` or ``elements``. Default is ``auto``. :param str credentials: Serialized :class:`.Credentials`. :param str url: URL of the **protected resource** request. :param str method: HTTP method of the **protected resource** request. :param str body: HTTP body of the **protected resource** request. :param JSON params: HTTP params of the **protected resource** request as a JSON object. :param JSON headers: HTTP headers of the **protected resource** request as a JSON object. :param JSON json: You can pass all of the aforementioned params except ``type`` in a JSON object. .. code-block:: javascript { "credentials": "######", "url": "https://example.com", "method": "POST", "params": {"foo": "bar"}, "headers": {"baz": "bing"}, "body": "the body of the request" } Depending on the ``type`` param, the handler will either write a JSON object with *request elements* to the response, and add an ``Authomatic-Response-To: elements`` response header, ... .. code-block:: javascript { "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" } } ... or make a fetch to the **protected resource** and forward it's response content, status and headers with an additional ``Authomatic-Response-To: fetch`` header to the response. .. warning:: The backend will not work if you write anything to the response in the handler! """ AUTHOMATIC_HEADER = 'Authomatic-Response-To' # Collect request params request_type = adapter.params.get('type', 'auto') json_input = adapter.params.get('json') credentials = adapter.params.get('credentials') url = adapter.params.get('url') method = adapter.params.get('method', 'GET') body = adapter.params.get('body', '') params = adapter.params.get('params') params = json.loads(params) if params else {} headers = adapter.params.get('headers') headers = json.loads(headers) if headers else {} ProviderClass = Credentials.deserialize( self.config, credentials).provider_class if request_type == 'auto': # If there is a "callback" param, it's a JSONP request. jsonp = params.get('callback') # JSONP is possible only with GET method. if ProviderClass.supports_jsonp and method is 'GET': request_type = 'elements' else: # Remove the JSONP callback if jsonp: params.pop('callback') request_type = 'fetch' if request_type == 'fetch': # Access protected resource response = self.access( credentials, url, params, method, headers, body) result = response.content # Forward status adapter.status = str(response.status) + ' ' + str(response.reason) # Forward headers for k, v in response.getheaders(): logging.info(' {0}: {1}'.format(k, v)) adapter.set_header(k, v) elif request_type == 'elements': # Create request elements if json_input: result = self.request_elements( json_input=json_input, return_json=True) else: result = self.request_elements(credentials=credentials, url=url, method=method, params=params, headers=headers, body=body, return_json=True) adapter.set_header('Content-Type', 'application/json') else: result = '{"error": "Bad Request!"}' # Add the authomatic header adapter.set_header(AUTHOMATIC_HEADER, request_type) # Write result to response adapter.write(result)
[ "Converts", "a", "*", "request", "handler", "*", "to", "a", "JSON", "backend", "which", "you", "can", "use", "with", ":", "ref", ":", "authomatic", ".", "js", "<js", ">", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L1610-L1764
[ "def", "backend", "(", "self", ",", "adapter", ")", ":", "AUTHOMATIC_HEADER", "=", "'Authomatic-Response-To'", "# Collect request params", "request_type", "=", "adapter", ".", "params", ".", "get", "(", "'type'", ",", "'auto'", ")", "json_input", "=", "adapter", ".", "params", ".", "get", "(", "'json'", ")", "credentials", "=", "adapter", ".", "params", ".", "get", "(", "'credentials'", ")", "url", "=", "adapter", ".", "params", ".", "get", "(", "'url'", ")", "method", "=", "adapter", ".", "params", ".", "get", "(", "'method'", ",", "'GET'", ")", "body", "=", "adapter", ".", "params", ".", "get", "(", "'body'", ",", "''", ")", "params", "=", "adapter", ".", "params", ".", "get", "(", "'params'", ")", "params", "=", "json", ".", "loads", "(", "params", ")", "if", "params", "else", "{", "}", "headers", "=", "adapter", ".", "params", ".", "get", "(", "'headers'", ")", "headers", "=", "json", ".", "loads", "(", "headers", ")", "if", "headers", "else", "{", "}", "ProviderClass", "=", "Credentials", ".", "deserialize", "(", "self", ".", "config", ",", "credentials", ")", ".", "provider_class", "if", "request_type", "==", "'auto'", ":", "# If there is a \"callback\" param, it's a JSONP request.", "jsonp", "=", "params", ".", "get", "(", "'callback'", ")", "# JSONP is possible only with GET method.", "if", "ProviderClass", ".", "supports_jsonp", "and", "method", "is", "'GET'", ":", "request_type", "=", "'elements'", "else", ":", "# Remove the JSONP callback", "if", "jsonp", ":", "params", ".", "pop", "(", "'callback'", ")", "request_type", "=", "'fetch'", "if", "request_type", "==", "'fetch'", ":", "# Access protected resource", "response", "=", "self", ".", "access", "(", "credentials", ",", "url", ",", "params", ",", "method", ",", "headers", ",", "body", ")", "result", "=", "response", ".", "content", "# Forward status", "adapter", ".", "status", "=", "str", "(", "response", ".", "status", ")", "+", "' '", "+", "str", "(", "response", ".", "reason", ")", "# Forward headers", "for", "k", ",", "v", "in", "response", ".", "getheaders", "(", ")", ":", "logging", ".", "info", "(", "' {0}: {1}'", ".", "format", "(", "k", ",", "v", ")", ")", "adapter", ".", "set_header", "(", "k", ",", "v", ")", "elif", "request_type", "==", "'elements'", ":", "# Create request elements", "if", "json_input", ":", "result", "=", "self", ".", "request_elements", "(", "json_input", "=", "json_input", ",", "return_json", "=", "True", ")", "else", ":", "result", "=", "self", ".", "request_elements", "(", "credentials", "=", "credentials", ",", "url", "=", "url", ",", "method", "=", "method", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "body", "=", "body", ",", "return_json", "=", "True", ")", "adapter", ".", "set_header", "(", "'Content-Type'", ",", "'application/json'", ")", "else", ":", "result", "=", "'{\"error\": \"Bad Request!\"}'", "# Add the authomatic header", "adapter", ".", "set_header", "(", "AUTHOMATIC_HEADER", ",", "request_type", ")", "# Write result to response", "adapter", ".", "write", "(", "result", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
_normalize_params
Returns a normalized query string sorted first by key, then by value excluding the ``realm`` and ``oauth_signature`` parameters as specified here: http://oauth.net/core/1.0a/#rfc.section.9.1.1. :param params: :class:`dict` or :class:`list` of tuples.
authomatic/providers/oauth1.py
def _normalize_params(params): """ Returns a normalized query string sorted first by key, then by value excluding the ``realm`` and ``oauth_signature`` parameters as specified here: http://oauth.net/core/1.0a/#rfc.section.9.1.1. :param params: :class:`dict` or :class:`list` of tuples. """ if isinstance(params, dict): params = list(params.items()) # remove "realm" and "oauth_signature" params = sorted([ (k, v) for k, v in params if k not in ('oauth_signature', 'realm') ]) # sort # convert to query string qs = parse.urlencode(params) # replace "+" to "%20" qs = qs.replace('+', '%20') # replace "%7E" to "%20" qs = qs.replace('%7E', '~') return qs
def _normalize_params(params): """ Returns a normalized query string sorted first by key, then by value excluding the ``realm`` and ``oauth_signature`` parameters as specified here: http://oauth.net/core/1.0a/#rfc.section.9.1.1. :param params: :class:`dict` or :class:`list` of tuples. """ if isinstance(params, dict): params = list(params.items()) # remove "realm" and "oauth_signature" params = sorted([ (k, v) for k, v in params if k not in ('oauth_signature', 'realm') ]) # sort # convert to query string qs = parse.urlencode(params) # replace "+" to "%20" qs = qs.replace('+', '%20') # replace "%7E" to "%20" qs = qs.replace('%7E', '~') return qs
[ "Returns", "a", "normalized", "query", "string", "sorted", "first", "by", "key", "then", "by", "value", "excluding", "the", "realm", "and", "oauth_signature", "parameters", "as", "specified", "here", ":", "http", ":", "//", "oauth", ".", "net", "/", "core", "/", "1", ".", "0a", "/", "#rfc", ".", "section", ".", "9", ".", "1", ".", "1", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth1.py#L61-L88
[ "def", "_normalize_params", "(", "params", ")", ":", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "params", "=", "list", "(", "params", ".", "items", "(", ")", ")", "# remove \"realm\" and \"oauth_signature\"", "params", "=", "sorted", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "params", "if", "k", "not", "in", "(", "'oauth_signature'", ",", "'realm'", ")", "]", ")", "# sort", "# convert to query string", "qs", "=", "parse", ".", "urlencode", "(", "params", ")", "# replace \"+\" to \"%20\"", "qs", "=", "qs", ".", "replace", "(", "'+'", ",", "'%20'", ")", "# replace \"%7E\" to \"%20\"", "qs", "=", "qs", ".", "replace", "(", "'%7E'", ",", "'~'", ")", "return", "qs" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
_create_base_string
Returns base string for HMAC-SHA1 signature as specified in: http://oauth.net/core/1.0a/#rfc.section.9.1.3.
authomatic/providers/oauth1.py
def _create_base_string(method, base, params): """ Returns base string for HMAC-SHA1 signature as specified in: http://oauth.net/core/1.0a/#rfc.section.9.1.3. """ normalized_qs = _normalize_params(params) return _join_by_ampersand(method, base, normalized_qs)
def _create_base_string(method, base, params): """ Returns base string for HMAC-SHA1 signature as specified in: http://oauth.net/core/1.0a/#rfc.section.9.1.3. """ normalized_qs = _normalize_params(params) return _join_by_ampersand(method, base, normalized_qs)
[ "Returns", "base", "string", "for", "HMAC", "-", "SHA1", "signature", "as", "specified", "in", ":", "http", ":", "//", "oauth", ".", "net", "/", "core", "/", "1", ".", "0a", "/", "#rfc", ".", "section", ".", "9", ".", "1", ".", "3", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth1.py#L95-L102
[ "def", "_create_base_string", "(", "method", ",", "base", ",", "params", ")", ":", "normalized_qs", "=", "_normalize_params", "(", "params", ")", "return", "_join_by_ampersand", "(", "method", ",", "base", ",", "normalized_qs", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
HMACSHA1SignatureGenerator.create_signature
Returns HMAC-SHA1 signature as specified at: http://oauth.net/core/1.0a/#rfc.section.9.2. :param str method: HTTP method of the request to be signed. :param str base: Base URL of the request without query string an fragment. :param dict params: Dictionary or list of tuples of the request parameters. :param str consumer_secret: :attr:`.core.Consumer.secret` :param str token_secret: Access token secret as specified in http://oauth.net/core/1.0a/#anchor3. :returns: The signature string.
authomatic/providers/oauth1.py
def create_signature(cls, method, base, params, consumer_secret, token_secret=''): """ Returns HMAC-SHA1 signature as specified at: http://oauth.net/core/1.0a/#rfc.section.9.2. :param str method: HTTP method of the request to be signed. :param str base: Base URL of the request without query string an fragment. :param dict params: Dictionary or list of tuples of the request parameters. :param str consumer_secret: :attr:`.core.Consumer.secret` :param str token_secret: Access token secret as specified in http://oauth.net/core/1.0a/#anchor3. :returns: The signature string. """ base_string = _create_base_string(method, base, params) key = cls._create_key(consumer_secret, token_secret) hashed = hmac.new( six.b(key), base_string.encode('utf-8'), hashlib.sha1) base64_encoded = binascii.b2a_base64(hashed.digest())[:-1] return base64_encoded
def create_signature(cls, method, base, params, consumer_secret, token_secret=''): """ Returns HMAC-SHA1 signature as specified at: http://oauth.net/core/1.0a/#rfc.section.9.2. :param str method: HTTP method of the request to be signed. :param str base: Base URL of the request without query string an fragment. :param dict params: Dictionary or list of tuples of the request parameters. :param str consumer_secret: :attr:`.core.Consumer.secret` :param str token_secret: Access token secret as specified in http://oauth.net/core/1.0a/#anchor3. :returns: The signature string. """ base_string = _create_base_string(method, base, params) key = cls._create_key(consumer_secret, token_secret) hashed = hmac.new( six.b(key), base_string.encode('utf-8'), hashlib.sha1) base64_encoded = binascii.b2a_base64(hashed.digest())[:-1] return base64_encoded
[ "Returns", "HMAC", "-", "SHA1", "signature", "as", "specified", "at", ":", "http", ":", "//", "oauth", ".", "net", "/", "core", "/", "1", ".", "0a", "/", "#rfc", ".", "section", ".", "9", ".", "2", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth1.py#L179-L216
[ "def", "create_signature", "(", "cls", ",", "method", ",", "base", ",", "params", ",", "consumer_secret", ",", "token_secret", "=", "''", ")", ":", "base_string", "=", "_create_base_string", "(", "method", ",", "base", ",", "params", ")", "key", "=", "cls", ".", "_create_key", "(", "consumer_secret", ",", "token_secret", ")", "hashed", "=", "hmac", ".", "new", "(", "six", ".", "b", "(", "key", ")", ",", "base_string", ".", "encode", "(", "'utf-8'", ")", ",", "hashlib", ".", "sha1", ")", "base64_encoded", "=", "binascii", ".", "b2a_base64", "(", "hashed", ".", "digest", "(", ")", ")", "[", ":", "-", "1", "]", "return", "base64_encoded" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
OAuth1.create_request_elements
Creates |oauth1| request elements.
authomatic/providers/oauth1.py
def create_request_elements( cls, request_type, credentials, url, params=None, headers=None, body='', method='GET', verifier='', callback='' ): """ Creates |oauth1| request elements. """ params = params or {} headers = headers or {} consumer_key = credentials.consumer_key or '' consumer_secret = credentials.consumer_secret or '' token = credentials.token or '' token_secret = credentials.token_secret or '' # separate url base and query parameters url, base_params = cls._split_url(url) # add extracted params to future params params.update(dict(base_params)) if request_type == cls.USER_AUTHORIZATION_REQUEST_TYPE: # no need for signature if token: params['oauth_token'] = token else: raise OAuth1Error( 'Credentials with valid token are required to create ' 'User Authorization URL!') else: # signature needed if request_type == cls.REQUEST_TOKEN_REQUEST_TYPE: # Request Token URL if consumer_key and consumer_secret and callback: params['oauth_consumer_key'] = consumer_key params['oauth_callback'] = callback else: raise OAuth1Error( 'Credentials with valid consumer_key, consumer_secret ' 'and callback are required to create Request Token ' 'URL!') elif request_type == cls.ACCESS_TOKEN_REQUEST_TYPE: # Access Token URL if consumer_key and consumer_secret and token and verifier: params['oauth_token'] = token params['oauth_consumer_key'] = consumer_key params['oauth_verifier'] = verifier else: raise OAuth1Error( 'Credentials with valid consumer_key, ' 'consumer_secret, token and argument verifier' ' are required to create Access Token URL!') elif request_type == cls.PROTECTED_RESOURCE_REQUEST_TYPE: # Protected Resources URL if consumer_key and consumer_secret and token and token_secret: params['oauth_token'] = token params['oauth_consumer_key'] = consumer_key else: raise OAuth1Error( 'Credentials with valid consumer_key, ' + 'consumer_secret, token and token_secret are required ' 'to create Protected Resources URL!') # Sign request. # http://oauth.net/core/1.0a/#anchor13 # Prepare parameters for signature base string # http://oauth.net/core/1.0a/#rfc.section.9.1 params['oauth_signature_method'] = cls._signature_generator.method params['oauth_timestamp'] = str(int(time.time())) params['oauth_nonce'] = cls.csrf_generator(str(uuid.uuid4())) params['oauth_version'] = '1.0' # add signature to params params['oauth_signature'] = cls._signature_generator.create_signature( # noqa method, url, params, consumer_secret, token_secret) request_elements = core.RequestElements( url, method, params, headers, body) return cls._x_request_elements_filter( request_type, request_elements, credentials)
def create_request_elements( cls, request_type, credentials, url, params=None, headers=None, body='', method='GET', verifier='', callback='' ): """ Creates |oauth1| request elements. """ params = params or {} headers = headers or {} consumer_key = credentials.consumer_key or '' consumer_secret = credentials.consumer_secret or '' token = credentials.token or '' token_secret = credentials.token_secret or '' # separate url base and query parameters url, base_params = cls._split_url(url) # add extracted params to future params params.update(dict(base_params)) if request_type == cls.USER_AUTHORIZATION_REQUEST_TYPE: # no need for signature if token: params['oauth_token'] = token else: raise OAuth1Error( 'Credentials with valid token are required to create ' 'User Authorization URL!') else: # signature needed if request_type == cls.REQUEST_TOKEN_REQUEST_TYPE: # Request Token URL if consumer_key and consumer_secret and callback: params['oauth_consumer_key'] = consumer_key params['oauth_callback'] = callback else: raise OAuth1Error( 'Credentials with valid consumer_key, consumer_secret ' 'and callback are required to create Request Token ' 'URL!') elif request_type == cls.ACCESS_TOKEN_REQUEST_TYPE: # Access Token URL if consumer_key and consumer_secret and token and verifier: params['oauth_token'] = token params['oauth_consumer_key'] = consumer_key params['oauth_verifier'] = verifier else: raise OAuth1Error( 'Credentials with valid consumer_key, ' 'consumer_secret, token and argument verifier' ' are required to create Access Token URL!') elif request_type == cls.PROTECTED_RESOURCE_REQUEST_TYPE: # Protected Resources URL if consumer_key and consumer_secret and token and token_secret: params['oauth_token'] = token params['oauth_consumer_key'] = consumer_key else: raise OAuth1Error( 'Credentials with valid consumer_key, ' + 'consumer_secret, token and token_secret are required ' 'to create Protected Resources URL!') # Sign request. # http://oauth.net/core/1.0a/#anchor13 # Prepare parameters for signature base string # http://oauth.net/core/1.0a/#rfc.section.9.1 params['oauth_signature_method'] = cls._signature_generator.method params['oauth_timestamp'] = str(int(time.time())) params['oauth_nonce'] = cls.csrf_generator(str(uuid.uuid4())) params['oauth_version'] = '1.0' # add signature to params params['oauth_signature'] = cls._signature_generator.create_signature( # noqa method, url, params, consumer_secret, token_secret) request_elements = core.RequestElements( url, method, params, headers, body) return cls._x_request_elements_filter( request_type, request_elements, credentials)
[ "Creates", "|oauth1|", "request", "elements", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth1.py#L299-L383
[ "def", "create_request_elements", "(", "cls", ",", "request_type", ",", "credentials", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "method", "=", "'GET'", ",", "verifier", "=", "''", ",", "callback", "=", "''", ")", ":", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "consumer_key", "=", "credentials", ".", "consumer_key", "or", "''", "consumer_secret", "=", "credentials", ".", "consumer_secret", "or", "''", "token", "=", "credentials", ".", "token", "or", "''", "token_secret", "=", "credentials", ".", "token_secret", "or", "''", "# separate url base and query parameters", "url", ",", "base_params", "=", "cls", ".", "_split_url", "(", "url", ")", "# add extracted params to future params", "params", ".", "update", "(", "dict", "(", "base_params", ")", ")", "if", "request_type", "==", "cls", ".", "USER_AUTHORIZATION_REQUEST_TYPE", ":", "# no need for signature", "if", "token", ":", "params", "[", "'oauth_token'", "]", "=", "token", "else", ":", "raise", "OAuth1Error", "(", "'Credentials with valid token are required to create '", "'User Authorization URL!'", ")", "else", ":", "# signature needed", "if", "request_type", "==", "cls", ".", "REQUEST_TOKEN_REQUEST_TYPE", ":", "# Request Token URL", "if", "consumer_key", "and", "consumer_secret", "and", "callback", ":", "params", "[", "'oauth_consumer_key'", "]", "=", "consumer_key", "params", "[", "'oauth_callback'", "]", "=", "callback", "else", ":", "raise", "OAuth1Error", "(", "'Credentials with valid consumer_key, consumer_secret '", "'and callback are required to create Request Token '", "'URL!'", ")", "elif", "request_type", "==", "cls", ".", "ACCESS_TOKEN_REQUEST_TYPE", ":", "# Access Token URL", "if", "consumer_key", "and", "consumer_secret", "and", "token", "and", "verifier", ":", "params", "[", "'oauth_token'", "]", "=", "token", "params", "[", "'oauth_consumer_key'", "]", "=", "consumer_key", "params", "[", "'oauth_verifier'", "]", "=", "verifier", "else", ":", "raise", "OAuth1Error", "(", "'Credentials with valid consumer_key, '", "'consumer_secret, token and argument verifier'", "' are required to create Access Token URL!'", ")", "elif", "request_type", "==", "cls", ".", "PROTECTED_RESOURCE_REQUEST_TYPE", ":", "# Protected Resources URL", "if", "consumer_key", "and", "consumer_secret", "and", "token", "and", "token_secret", ":", "params", "[", "'oauth_token'", "]", "=", "token", "params", "[", "'oauth_consumer_key'", "]", "=", "consumer_key", "else", ":", "raise", "OAuth1Error", "(", "'Credentials with valid consumer_key, '", "+", "'consumer_secret, token and token_secret are required '", "'to create Protected Resources URL!'", ")", "# Sign request.", "# http://oauth.net/core/1.0a/#anchor13", "# Prepare parameters for signature base string", "# http://oauth.net/core/1.0a/#rfc.section.9.1", "params", "[", "'oauth_signature_method'", "]", "=", "cls", ".", "_signature_generator", ".", "method", "params", "[", "'oauth_timestamp'", "]", "=", "str", "(", "int", "(", "time", ".", "time", "(", ")", ")", ")", "params", "[", "'oauth_nonce'", "]", "=", "cls", ".", "csrf_generator", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "params", "[", "'oauth_version'", "]", "=", "'1.0'", "# add signature to params", "params", "[", "'oauth_signature'", "]", "=", "cls", ".", "_signature_generator", ".", "create_signature", "(", "# noqa", "method", ",", "url", ",", "params", ",", "consumer_secret", ",", "token_secret", ")", "request_elements", "=", "core", ".", "RequestElements", "(", "url", ",", "method", ",", "params", ",", "headers", ",", "body", ")", "return", "cls", ".", "_x_request_elements_filter", "(", "request_type", ",", "request_elements", ",", "credentials", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Bitbucket._access_user_info
Email is available in separate method so second request is needed.
authomatic/providers/oauth1.py
def _access_user_info(self): """ Email is available in separate method so second request is needed. """ response = super(Bitbucket, self)._access_user_info() response.data.setdefault("email", None) email_response = self.access(self.user_email_url) if email_response.data: for item in email_response.data: if item.get("primary", False): response.data.update(email=item.get("email", None)) return response
def _access_user_info(self): """ Email is available in separate method so second request is needed. """ response = super(Bitbucket, self)._access_user_info() response.data.setdefault("email", None) email_response = self.access(self.user_email_url) if email_response.data: for item in email_response.data: if item.get("primary", False): response.data.update(email=item.get("email", None)) return response
[ "Email", "is", "available", "in", "separate", "method", "so", "second", "request", "is", "needed", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth1.py#L621-L635
[ "def", "_access_user_info", "(", "self", ")", ":", "response", "=", "super", "(", "Bitbucket", ",", "self", ")", ".", "_access_user_info", "(", ")", "response", ".", "data", ".", "setdefault", "(", "\"email\"", ",", "None", ")", "email_response", "=", "self", ".", "access", "(", "self", ".", "user_email_url", ")", "if", "email_response", ".", "data", ":", "for", "item", "in", "email_response", ".", "data", ":", "if", "item", ".", "get", "(", "\"primary\"", ",", "False", ")", ":", "response", ".", "data", ".", "update", "(", "email", "=", "item", ".", "get", "(", "\"email\"", ",", "None", ")", ")", "return", "response" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
Vimeo._access_user_info
Vimeo requires the user ID to access the user info endpoint, so we need to make two requests: one to get user ID and second to get user info.
authomatic/providers/oauth1.py
def _access_user_info(self): """ Vimeo requires the user ID to access the user info endpoint, so we need to make two requests: one to get user ID and second to get user info. """ response = super(Vimeo, self)._access_user_info() uid = response.data.get('oauth', {}).get('user', {}).get('id') if uid: return self.access('http://vimeo.com/api/v2/{0}/info.json' .format(uid)) return response
def _access_user_info(self): """ Vimeo requires the user ID to access the user info endpoint, so we need to make two requests: one to get user ID and second to get user info. """ response = super(Vimeo, self)._access_user_info() uid = response.data.get('oauth', {}).get('user', {}).get('id') if uid: return self.access('http://vimeo.com/api/v2/{0}/info.json' .format(uid)) return response
[ "Vimeo", "requires", "the", "user", "ID", "to", "access", "the", "user", "info", "endpoint", "so", "we", "need", "to", "make", "two", "requests", ":", "one", "to", "get", "user", "ID", "and", "second", "to", "get", "user", "info", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/oauth1.py#L1089-L1099
[ "def", "_access_user_info", "(", "self", ")", ":", "response", "=", "super", "(", "Vimeo", ",", "self", ")", ".", "_access_user_info", "(", ")", "uid", "=", "response", ".", "data", ".", "get", "(", "'oauth'", ",", "{", "}", ")", ".", "get", "(", "'user'", ",", "{", "}", ")", ".", "get", "(", "'id'", ")", "if", "uid", ":", "return", "self", ".", "access", "(", "'http://vimeo.com/api/v2/{0}/info.json'", ".", "format", "(", "uid", ")", ")", "return", "response" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
FlaskAuthomatic.login
Decorator for Flask view functions.
authomatic/extras/flask.py
def login(self, *login_args, **login_kwargs): """ Decorator for Flask view functions. """ def decorator(f): @wraps(f) def decorated(*args, **kwargs): self.response = make_response() adapter = WerkzeugAdapter(request, self.response) login_kwargs.setdefault('session', session) login_kwargs.setdefault('session_saver', self.session_saver) self.result = super(FlaskAuthomatic, self).login( adapter, *login_args, **login_kwargs) return f(*args, **kwargs) return decorated return decorator
def login(self, *login_args, **login_kwargs): """ Decorator for Flask view functions. """ def decorator(f): @wraps(f) def decorated(*args, **kwargs): self.response = make_response() adapter = WerkzeugAdapter(request, self.response) login_kwargs.setdefault('session', session) login_kwargs.setdefault('session_saver', self.session_saver) self.result = super(FlaskAuthomatic, self).login( adapter, *login_args, **login_kwargs) return f(*args, **kwargs) return decorated return decorator
[ "Decorator", "for", "Flask", "view", "functions", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/extras/flask.py#L26-L44
[ "def", "login", "(", "self", ",", "*", "login_args", ",", "*", "*", "login_kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "response", "=", "make_response", "(", ")", "adapter", "=", "WerkzeugAdapter", "(", "request", ",", "self", ".", "response", ")", "login_kwargs", ".", "setdefault", "(", "'session'", ",", "session", ")", "login_kwargs", ".", "setdefault", "(", "'session_saver'", ",", "self", ".", "session_saver", ")", "self", ".", "result", "=", "super", "(", "FlaskAuthomatic", ",", "self", ")", ".", "login", "(", "adapter", ",", "*", "login_args", ",", "*", "*", "login_kwargs", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decorated", "return", "decorator" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
NDBConfig.get
Resembles the :meth:`dict.get` method. :returns: A configuration dictionary for specified provider.
authomatic/extras/gae/__init__.py
def get(cls, key, default=None): """ Resembles the :meth:`dict.get` method. :returns: A configuration dictionary for specified provider. """ # Query datastore. result = cls.query(cls.provider_name == key).get() if result: result_dict = result.to_dict() # Use NDBOpenIDStore by default result_dict['store'] = NDBOpenIDStore # Convert coma-separated values to list. Currently only scope is # csv. for i in ('scope', ): prop = result_dict.get(i) if prop: result_dict[i] = [s.strip() for s in prop.split(',')] else: result_dict[i] = None return result_dict else: return default
def get(cls, key, default=None): """ Resembles the :meth:`dict.get` method. :returns: A configuration dictionary for specified provider. """ # Query datastore. result = cls.query(cls.provider_name == key).get() if result: result_dict = result.to_dict() # Use NDBOpenIDStore by default result_dict['store'] = NDBOpenIDStore # Convert coma-separated values to list. Currently only scope is # csv. for i in ('scope', ): prop = result_dict.get(i) if prop: result_dict[i] = [s.strip() for s in prop.split(',')] else: result_dict[i] = None return result_dict else: return default
[ "Resembles", "the", ":", "meth", ":", "dict", ".", "get", "method", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/extras/gae/__init__.py#L128-L157
[ "def", "get", "(", "cls", ",", "key", ",", "default", "=", "None", ")", ":", "# Query datastore.", "result", "=", "cls", ".", "query", "(", "cls", ".", "provider_name", "==", "key", ")", ".", "get", "(", ")", "if", "result", ":", "result_dict", "=", "result", ".", "to_dict", "(", ")", "# Use NDBOpenIDStore by default", "result_dict", "[", "'store'", "]", "=", "NDBOpenIDStore", "# Convert coma-separated values to list. Currently only scope is", "# csv.", "for", "i", "in", "(", "'scope'", ",", ")", ":", "prop", "=", "result_dict", ".", "get", "(", "i", ")", "if", "prop", ":", "result_dict", "[", "i", "]", "=", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "prop", ".", "split", "(", "','", ")", "]", "else", ":", "result_dict", "[", "i", "]", "=", "None", "return", "result_dict", "else", ":", "return", "default" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
NDBConfig.values
Resembles the :meth:`dict.values` method.
authomatic/extras/gae/__init__.py
def values(cls): """ Resembles the :meth:`dict.values` method. """ # get all items results = cls.query().fetch() # return list of dictionaries return [result.to_dict() for result in results]
def values(cls): """ Resembles the :meth:`dict.values` method. """ # get all items results = cls.query().fetch() # return list of dictionaries return [result.to_dict() for result in results]
[ "Resembles", "the", ":", "meth", ":", "dict", ".", "values", "method", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/extras/gae/__init__.py#L160-L168
[ "def", "values", "(", "cls", ")", ":", "# get all items", "results", "=", "cls", ".", "query", "(", ")", ".", "fetch", "(", ")", "# return list of dictionaries", "return", "[", "result", ".", "to_dict", "(", ")", "for", "result", "in", "results", "]" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
NDBConfig.initialize
Creates an **"Example"** entity of kind **"NDBConfig"** in the datastore if the model is empty and raises and error to inform you that you should populate the model with data. .. note:: The *Datastore Viewer* in the ``_ah/admin/`` won't let you add properties to a model if there is not an entity with that property already. Therefore it is a good idea to keep the **"Example"** entity (which has all possible properties set) in the datastore.
authomatic/extras/gae/__init__.py
def initialize(cls): """ Creates an **"Example"** entity of kind **"NDBConfig"** in the datastore if the model is empty and raises and error to inform you that you should populate the model with data. .. note:: The *Datastore Viewer* in the ``_ah/admin/`` won't let you add properties to a model if there is not an entity with that property already. Therefore it is a good idea to keep the **"Example"** entity (which has all possible properties set) in the datastore. """ if not len(cls.query().fetch()): example = cls.get_or_insert('Example') example.class_ = 'Provider class e.g. ' + \ '"authomatic.providers.oauth2.Facebook".' example.provider_name = 'Your custom provider name e.g. "fb".' # AuthorizationProvider example.consumer_key = 'Consumer key.' example.consumer_secret = 'Consumer secret' example.provider_id = 1 # OAuth2 example.scope = 'coma, separated, list, of, scopes' # AuthenticationProvider example.identifier_param = 'Querystring parameter for claimed ' + \ 'id. default is "id"' # Save the example example.put() # Raise an information error. raise GAEError( 'A NDBConfig data model was created! Go to Datastore Viewer ' 'in your dashboard and populate it with data!')
def initialize(cls): """ Creates an **"Example"** entity of kind **"NDBConfig"** in the datastore if the model is empty and raises and error to inform you that you should populate the model with data. .. note:: The *Datastore Viewer* in the ``_ah/admin/`` won't let you add properties to a model if there is not an entity with that property already. Therefore it is a good idea to keep the **"Example"** entity (which has all possible properties set) in the datastore. """ if not len(cls.query().fetch()): example = cls.get_or_insert('Example') example.class_ = 'Provider class e.g. ' + \ '"authomatic.providers.oauth2.Facebook".' example.provider_name = 'Your custom provider name e.g. "fb".' # AuthorizationProvider example.consumer_key = 'Consumer key.' example.consumer_secret = 'Consumer secret' example.provider_id = 1 # OAuth2 example.scope = 'coma, separated, list, of, scopes' # AuthenticationProvider example.identifier_param = 'Querystring parameter for claimed ' + \ 'id. default is "id"' # Save the example example.put() # Raise an information error. raise GAEError( 'A NDBConfig data model was created! Go to Datastore Viewer ' 'in your dashboard and populate it with data!')
[ "Creates", "an", "**", "Example", "**", "entity", "of", "kind", "**", "NDBConfig", "**", "in", "the", "datastore", "if", "the", "model", "is", "empty", "and", "raises", "and", "error", "to", "inform", "you", "that", "you", "should", "populate", "the", "model", "with", "data", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/extras/gae/__init__.py#L171-L213
[ "def", "initialize", "(", "cls", ")", ":", "if", "not", "len", "(", "cls", ".", "query", "(", ")", ".", "fetch", "(", ")", ")", ":", "example", "=", "cls", ".", "get_or_insert", "(", "'Example'", ")", "example", ".", "class_", "=", "'Provider class e.g. '", "+", "'\"authomatic.providers.oauth2.Facebook\".'", "example", ".", "provider_name", "=", "'Your custom provider name e.g. \"fb\".'", "# AuthorizationProvider", "example", ".", "consumer_key", "=", "'Consumer key.'", "example", ".", "consumer_secret", "=", "'Consumer secret'", "example", ".", "provider_id", "=", "1", "# OAuth2", "example", ".", "scope", "=", "'coma, separated, list, of, scopes'", "# AuthenticationProvider", "example", ".", "identifier_param", "=", "'Querystring parameter for claimed '", "+", "'id. default is \"id\"'", "# Save the example", "example", ".", "put", "(", ")", "# Raise an information error.", "raise", "GAEError", "(", "'A NDBConfig data model was created! Go to Datastore Viewer '", "'in your dashboard and populate it with data!'", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
GAEOpenID.login
Launches the OpenID authentication procedure.
authomatic/providers/gaeopenid.py
def login(self): """ Launches the OpenID authentication procedure. """ if self.params.get(self.identifier_param): # ================================================================= # Phase 1 before redirect. # ================================================================= self._log( logging.INFO, u'Starting OpenID authentication procedure.') url = users.create_login_url( dest_url=self.url, federated_identity=self.identifier) self._log(logging.INFO, u'Redirecting user to {0}.'.format(url)) self.redirect(url) else: # ================================================================= # Phase 2 after redirect. # ================================================================= self._log( logging.INFO, u'Continuing OpenID authentication procedure after redirect.') user = users.get_current_user() if user: self._log(logging.INFO, u'Authentication successful.') self._log(logging.INFO, u'Creating user.') self.user = core.User(self, id=user.federated_identity(), email=user.email(), gae_user=user) # ============================================================= # We're done # ============================================================= else: raise FailureError( 'Unable to authenticate identifier "{0}"!'.format( self.identifier))
def login(self): """ Launches the OpenID authentication procedure. """ if self.params.get(self.identifier_param): # ================================================================= # Phase 1 before redirect. # ================================================================= self._log( logging.INFO, u'Starting OpenID authentication procedure.') url = users.create_login_url( dest_url=self.url, federated_identity=self.identifier) self._log(logging.INFO, u'Redirecting user to {0}.'.format(url)) self.redirect(url) else: # ================================================================= # Phase 2 after redirect. # ================================================================= self._log( logging.INFO, u'Continuing OpenID authentication procedure after redirect.') user = users.get_current_user() if user: self._log(logging.INFO, u'Authentication successful.') self._log(logging.INFO, u'Creating user.') self.user = core.User(self, id=user.federated_identity(), email=user.email(), gae_user=user) # ============================================================= # We're done # ============================================================= else: raise FailureError( 'Unable to authenticate identifier "{0}"!'.format( self.identifier))
[ "Launches", "the", "OpenID", "authentication", "procedure", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/gaeopenid.py#L50-L94
[ "def", "login", "(", "self", ")", ":", "if", "self", ".", "params", ".", "get", "(", "self", ".", "identifier_param", ")", ":", "# =================================================================", "# Phase 1 before redirect.", "# =================================================================", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Starting OpenID authentication procedure.'", ")", "url", "=", "users", ".", "create_login_url", "(", "dest_url", "=", "self", ".", "url", ",", "federated_identity", "=", "self", ".", "identifier", ")", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Redirecting user to {0}.'", ".", "format", "(", "url", ")", ")", "self", ".", "redirect", "(", "url", ")", "else", ":", "# =================================================================", "# Phase 2 after redirect.", "# =================================================================", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Continuing OpenID authentication procedure after redirect.'", ")", "user", "=", "users", ".", "get_current_user", "(", ")", "if", "user", ":", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Authentication successful.'", ")", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Creating user.'", ")", "self", ".", "user", "=", "core", ".", "User", "(", "self", ",", "id", "=", "user", ".", "federated_identity", "(", ")", ",", "email", "=", "user", ".", "email", "(", ")", ",", "gae_user", "=", "user", ")", "# =============================================================", "# We're done", "# =============================================================", "else", ":", "raise", "FailureError", "(", "'Unable to authenticate identifier \"{0}\"!'", ".", "format", "(", "self", ".", "identifier", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
_error_traceback_html
Generates error traceback HTML. :param tuple exc_info: Output of :func:`sys.exc_info` function. :param traceback: Output of :func:`traceback.format_exc` function.
authomatic/providers/__init__.py
def _error_traceback_html(exc_info, traceback_): """ Generates error traceback HTML. :param tuple exc_info: Output of :func:`sys.exc_info` function. :param traceback: Output of :func:`traceback.format_exc` function. """ html = """ <html> <head> <title>ERROR: {error}</title> </head> <body style="font-family: sans-serif"> <h4>The Authomatic library encountered an error!</h4> <h1>{error}</h1> <pre>{traceback}</pre> </body> </html> """ return html.format(error=exc_info[1], traceback=traceback_)
def _error_traceback_html(exc_info, traceback_): """ Generates error traceback HTML. :param tuple exc_info: Output of :func:`sys.exc_info` function. :param traceback: Output of :func:`traceback.format_exc` function. """ html = """ <html> <head> <title>ERROR: {error}</title> </head> <body style="font-family: sans-serif"> <h4>The Authomatic library encountered an error!</h4> <h1>{error}</h1> <pre>{traceback}</pre> </body> </html> """ return html.format(error=exc_info[1], traceback=traceback_)
[ "Generates", "error", "traceback", "HTML", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L49-L74
[ "def", "_error_traceback_html", "(", "exc_info", ",", "traceback_", ")", ":", "html", "=", "\"\"\"\n <html>\n <head>\n <title>ERROR: {error}</title>\n </head>\n <body style=\"font-family: sans-serif\">\n <h4>The Authomatic library encountered an error!</h4>\n <h1>{error}</h1>\n <pre>{traceback}</pre>\n </body>\n </html>\n \"\"\"", "return", "html", ".", "format", "(", "error", "=", "exc_info", "[", "1", "]", ",", "traceback", "=", "traceback_", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
login_decorator
Decorate the :meth:`.BaseProvider.login` implementations with this decorator. Provides mechanism for error reporting and returning result which makes the :meth:`.BaseProvider.login` implementation cleaner.
authomatic/providers/__init__.py
def login_decorator(func): """ Decorate the :meth:`.BaseProvider.login` implementations with this decorator. Provides mechanism for error reporting and returning result which makes the :meth:`.BaseProvider.login` implementation cleaner. """ def wrap(provider, *args, **kwargs): error = None result = authomatic.core.LoginResult(provider) try: func(provider, *args, **kwargs) except Exception as e: # pylint:disable=broad-except if provider.settings.report_errors: error = e if not isinstance(error, CancellationError): provider._log( logging.ERROR, u'Reported suppressed exception: {0}!'.format( repr(error)), exc_info=1) else: if provider.settings.debug: # TODO: Check whether it actually works without middleware provider.write( _error_traceback_html( sys.exc_info(), traceback.format_exc())) raise # If there is user or error the login procedure has finished if provider.user or error: result = authomatic.core.LoginResult(provider) # Add error to result result.error = error # delete session cookie if isinstance(provider.session, authomatic.core.Session): provider.session.delete() provider._log(logging.INFO, u'Procedure finished.') if provider.callback: provider.callback(result) return result else: # Save session provider.save_session() return wrap
def login_decorator(func): """ Decorate the :meth:`.BaseProvider.login` implementations with this decorator. Provides mechanism for error reporting and returning result which makes the :meth:`.BaseProvider.login` implementation cleaner. """ def wrap(provider, *args, **kwargs): error = None result = authomatic.core.LoginResult(provider) try: func(provider, *args, **kwargs) except Exception as e: # pylint:disable=broad-except if provider.settings.report_errors: error = e if not isinstance(error, CancellationError): provider._log( logging.ERROR, u'Reported suppressed exception: {0}!'.format( repr(error)), exc_info=1) else: if provider.settings.debug: # TODO: Check whether it actually works without middleware provider.write( _error_traceback_html( sys.exc_info(), traceback.format_exc())) raise # If there is user or error the login procedure has finished if provider.user or error: result = authomatic.core.LoginResult(provider) # Add error to result result.error = error # delete session cookie if isinstance(provider.session, authomatic.core.Session): provider.session.delete() provider._log(logging.INFO, u'Procedure finished.') if provider.callback: provider.callback(result) return result else: # Save session provider.save_session() return wrap
[ "Decorate", "the", ":", "meth", ":", ".", "BaseProvider", ".", "login", "implementations", "with", "this", "decorator", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L77-L130
[ "def", "login_decorator", "(", "func", ")", ":", "def", "wrap", "(", "provider", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "error", "=", "None", "result", "=", "authomatic", ".", "core", ".", "LoginResult", "(", "provider", ")", "try", ":", "func", "(", "provider", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "# pylint:disable=broad-except", "if", "provider", ".", "settings", ".", "report_errors", ":", "error", "=", "e", "if", "not", "isinstance", "(", "error", ",", "CancellationError", ")", ":", "provider", ".", "_log", "(", "logging", ".", "ERROR", ",", "u'Reported suppressed exception: {0}!'", ".", "format", "(", "repr", "(", "error", ")", ")", ",", "exc_info", "=", "1", ")", "else", ":", "if", "provider", ".", "settings", ".", "debug", ":", "# TODO: Check whether it actually works without middleware", "provider", ".", "write", "(", "_error_traceback_html", "(", "sys", ".", "exc_info", "(", ")", ",", "traceback", ".", "format_exc", "(", ")", ")", ")", "raise", "# If there is user or error the login procedure has finished", "if", "provider", ".", "user", "or", "error", ":", "result", "=", "authomatic", ".", "core", ".", "LoginResult", "(", "provider", ")", "# Add error to result", "result", ".", "error", "=", "error", "# delete session cookie", "if", "isinstance", "(", "provider", ".", "session", ",", "authomatic", ".", "core", ".", "Session", ")", ":", "provider", ".", "session", ".", "delete", "(", ")", "provider", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Procedure finished.'", ")", "if", "provider", ".", "callback", ":", "provider", ".", "callback", "(", "result", ")", "return", "result", "else", ":", "# Save session", "provider", ".", "save_session", "(", ")", "return", "wrap" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider.to_dict
Converts the provider instance to a :class:`dict`. :returns: :class:`dict`
authomatic/providers/__init__.py
def to_dict(self): """ Converts the provider instance to a :class:`dict`. :returns: :class:`dict` """ return dict(name=self.name, id=getattr(self, 'id', None), type_id=self.type_id, type=self.get_type(), scope=getattr(self, 'scope', None), user=self.user.id if self.user else None)
def to_dict(self): """ Converts the provider instance to a :class:`dict`. :returns: :class:`dict` """ return dict(name=self.name, id=getattr(self, 'id', None), type_id=self.type_id, type=self.get_type(), scope=getattr(self, 'scope', None), user=self.user.id if self.user else None)
[ "Converts", "the", "provider", "instance", "to", "a", ":", "class", ":", "dict", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L217-L231
[ "def", "to_dict", "(", "self", ")", ":", "return", "dict", "(", "name", "=", "self", ".", "name", ",", "id", "=", "getattr", "(", "self", ",", "'id'", ",", "None", ")", ",", "type_id", "=", "self", ".", "type_id", ",", "type", "=", "self", ".", "get_type", "(", ")", ",", "scope", "=", "getattr", "(", "self", ",", "'scope'", ",", "None", ")", ",", "user", "=", "self", ".", "user", ".", "id", "if", "self", ".", "user", "else", "None", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider._kwarg
Resolves keyword arguments from constructor or :doc:`config`. .. note:: The keyword arguments take this order of precedence: 1. Arguments passed to constructor through the :func:`authomatic.login`. 2. Provider specific arguments from :doc:`config`. 3. Arguments from :doc:`config` set in the ``__defaults__`` key. 2. The value from :data:`default` argument. :param dict kwargs: Keyword arguments dictionary. :param str kwname: Name of the desired keyword argument.
authomatic/providers/__init__.py
def _kwarg(self, kwargs, kwname, default=None): """ Resolves keyword arguments from constructor or :doc:`config`. .. note:: The keyword arguments take this order of precedence: 1. Arguments passed to constructor through the :func:`authomatic.login`. 2. Provider specific arguments from :doc:`config`. 3. Arguments from :doc:`config` set in the ``__defaults__`` key. 2. The value from :data:`default` argument. :param dict kwargs: Keyword arguments dictionary. :param str kwname: Name of the desired keyword argument. """ return kwargs.get(kwname) or \ self.settings.config.get(self.name, {}).get(kwname) or \ self.settings.config.get('__defaults__', {}).get(kwname) or \ default
def _kwarg(self, kwargs, kwname, default=None): """ Resolves keyword arguments from constructor or :doc:`config`. .. note:: The keyword arguments take this order of precedence: 1. Arguments passed to constructor through the :func:`authomatic.login`. 2. Provider specific arguments from :doc:`config`. 3. Arguments from :doc:`config` set in the ``__defaults__`` key. 2. The value from :data:`default` argument. :param dict kwargs: Keyword arguments dictionary. :param str kwname: Name of the desired keyword argument. """ return kwargs.get(kwname) or \ self.settings.config.get(self.name, {}).get(kwname) or \ self.settings.config.get('__defaults__', {}).get(kwname) or \ default
[ "Resolves", "keyword", "arguments", "from", "constructor", "or", ":", "doc", ":", "config", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L263-L287
[ "def", "_kwarg", "(", "self", ",", "kwargs", ",", "kwname", ",", "default", "=", "None", ")", ":", "return", "kwargs", ".", "get", "(", "kwname", ")", "or", "self", ".", "settings", ".", "config", ".", "get", "(", "self", ".", "name", ",", "{", "}", ")", ".", "get", "(", "kwname", ")", "or", "self", ".", "settings", ".", "config", ".", "get", "(", "'__defaults__'", ",", "{", "}", ")", ".", "get", "(", "kwname", ")", "or", "default" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider._session_key
Generates session key string. :param str key: e.g. ``"authomatic:facebook:key"``
authomatic/providers/__init__.py
def _session_key(self, key): """ Generates session key string. :param str key: e.g. ``"authomatic:facebook:key"`` """ return '{0}:{1}:{2}'.format(self.settings.prefix, self.name, key)
def _session_key(self, key): """ Generates session key string. :param str key: e.g. ``"authomatic:facebook:key"`` """ return '{0}:{1}:{2}'.format(self.settings.prefix, self.name, key)
[ "Generates", "session", "key", "string", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L289-L298
[ "def", "_session_key", "(", "self", ",", "key", ")", ":", "return", "'{0}:{1}:{2}'", ".", "format", "(", "self", ".", "settings", ".", "prefix", ",", "self", ".", "name", ",", "key", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider._session_set
Saves a value to session.
authomatic/providers/__init__.py
def _session_set(self, key, value): """ Saves a value to session. """ self.session[self._session_key(key)] = value
def _session_set(self, key, value): """ Saves a value to session. """ self.session[self._session_key(key)] = value
[ "Saves", "a", "value", "to", "session", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L300-L305
[ "def", "_session_set", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "session", "[", "self", ".", "_session_key", "(", "key", ")", "]", "=", "value" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider.csrf_generator
Generates CSRF token. Inspired by this article: http://blog.ptsecurity.com/2012/10/random-number-security-in-python.html :returns: :class:`str` Random unguessable string.
authomatic/providers/__init__.py
def csrf_generator(secret): """ Generates CSRF token. Inspired by this article: http://blog.ptsecurity.com/2012/10/random-number-security-in-python.html :returns: :class:`str` Random unguessable string. """ # Create hash from random string plus salt. hashed = hashlib.md5(uuid.uuid4().bytes + six.b(secret)).hexdigest() # Each time return random portion of the hash. span = 5 shift = random.randint(0, span) return hashed[shift:shift - span - 1]
def csrf_generator(secret): """ Generates CSRF token. Inspired by this article: http://blog.ptsecurity.com/2012/10/random-number-security-in-python.html :returns: :class:`str` Random unguessable string. """ # Create hash from random string plus salt. hashed = hashlib.md5(uuid.uuid4().bytes + six.b(secret)).hexdigest() # Each time return random portion of the hash. span = 5 shift = random.randint(0, span) return hashed[shift:shift - span - 1]
[ "Generates", "CSRF", "token", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L315-L333
[ "def", "csrf_generator", "(", "secret", ")", ":", "# Create hash from random string plus salt.", "hashed", "=", "hashlib", ".", "md5", "(", "uuid", ".", "uuid4", "(", ")", ".", "bytes", "+", "six", ".", "b", "(", "secret", ")", ")", ".", "hexdigest", "(", ")", "# Each time return random portion of the hash.", "span", "=", "5", "shift", "=", "random", ".", "randint", "(", "0", ",", "span", ")", "return", "hashed", "[", "shift", ":", "shift", "-", "span", "-", "1", "]" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider._log
Logs a message with pre-formatted prefix. :param int level: Logging level as specified in the `login module <http://docs.python.org/2/library/logging.html>`_ of Python standard library. :param str msg: The actual message.
authomatic/providers/__init__.py
def _log(cls, level, msg, **kwargs): """ Logs a message with pre-formatted prefix. :param int level: Logging level as specified in the `login module <http://docs.python.org/2/library/logging.html>`_ of Python standard library. :param str msg: The actual message. """ logger = getattr(cls, '_logger', None) or authomatic.core._logger logger.log( level, ': '.join( ('authomatic', cls.__name__, msg)), **kwargs)
def _log(cls, level, msg, **kwargs): """ Logs a message with pre-formatted prefix. :param int level: Logging level as specified in the `login module <http://docs.python.org/2/library/logging.html>`_ of Python standard library. :param str msg: The actual message. """ logger = getattr(cls, '_logger', None) or authomatic.core._logger logger.log( level, ': '.join( ('authomatic', cls.__name__, msg)), **kwargs)
[ "Logs", "a", "message", "with", "pre", "-", "formatted", "prefix", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L336-L353
[ "def", "_log", "(", "cls", ",", "level", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "logger", "=", "getattr", "(", "cls", ",", "'_logger'", ",", "None", ")", "or", "authomatic", ".", "core", ".", "_logger", "logger", ".", "log", "(", "level", ",", "': '", ".", "join", "(", "(", "'authomatic'", ",", "cls", ".", "__name__", ",", "msg", ")", ")", ",", "*", "*", "kwargs", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider._fetch
Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Number of maximum HTTP redirects to follow. :param function content_parser: A callable to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`.
authomatic/providers/__init__.py
def _fetch(self, url, method='GET', params=None, headers=None, body='', max_redirects=5, content_parser=None): """ Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Number of maximum HTTP redirects to follow. :param function content_parser: A callable to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. """ # 'magic' using _kwarg method # pylint:disable=no-member params = params or {} params.update(self.access_params) headers = headers or {} headers.update(self.access_headers) scheme, host, path, query, fragment = parse.urlsplit(url) query = parse.urlencode(params) if method in ('POST', 'PUT', 'PATCH'): if not body: # Put querystring to body body = query query = '' headers.update( {'Content-Type': 'application/x-www-form-urlencoded'}) request_path = parse.urlunsplit(('', '', path or '', query or '', '')) self._log(logging.DEBUG, u' \u251C\u2500 host: {0}'.format(host)) self._log( logging.DEBUG, u' \u251C\u2500 path: {0}'.format(request_path)) self._log(logging.DEBUG, u' \u251C\u2500 method: {0}'.format(method)) self._log(logging.DEBUG, u' \u251C\u2500 body: {0}'.format(body)) self._log(logging.DEBUG, u' \u251C\u2500 params: {0}'.format(params)) self._log(logging.DEBUG, u' \u2514\u2500 headers: {0}'.format(headers)) # Connect if scheme.lower() == 'https': connection = http_client.HTTPSConnection(host) else: connection = http_client.HTTPConnection(host) try: connection.request(method, request_path, body, headers) except Exception as e: raise FetchError('Fetching URL failed', original_message=str(e), url=request_path) response = connection.getresponse() location = response.getheader('Location') if response.status in (300, 301, 302, 303, 307) and location: if location == url: raise FetchError('Url redirects to itself!', url=location, status=response.status) elif max_redirects > 0: remaining_redirects = max_redirects - 1 self._log(logging.DEBUG, u'Redirecting to {0}'.format(url)) self._log(logging.DEBUG, u'Remaining redirects: {0}' .format(remaining_redirects)) # Call this method again. response = self._fetch(url=location, params=params, method=method, headers=headers, max_redirects=remaining_redirects) else: raise FetchError('Max redirects reached!', url=location, status=response.status) else: self._log(logging.DEBUG, u'Got response:') self._log(logging.DEBUG, u' \u251C\u2500 url: {0}'.format(url)) self._log( logging.DEBUG, u' \u251C\u2500 status: {0}'.format( response.status)) self._log( logging.DEBUG, u' \u2514\u2500 headers: {0}'.format( response.getheaders())) return authomatic.core.Response(response, content_parser)
def _fetch(self, url, method='GET', params=None, headers=None, body='', max_redirects=5, content_parser=None): """ Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: Dictionary of request parameters. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Number of maximum HTTP redirects to follow. :param function content_parser: A callable to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. """ # 'magic' using _kwarg method # pylint:disable=no-member params = params or {} params.update(self.access_params) headers = headers or {} headers.update(self.access_headers) scheme, host, path, query, fragment = parse.urlsplit(url) query = parse.urlencode(params) if method in ('POST', 'PUT', 'PATCH'): if not body: # Put querystring to body body = query query = '' headers.update( {'Content-Type': 'application/x-www-form-urlencoded'}) request_path = parse.urlunsplit(('', '', path or '', query or '', '')) self._log(logging.DEBUG, u' \u251C\u2500 host: {0}'.format(host)) self._log( logging.DEBUG, u' \u251C\u2500 path: {0}'.format(request_path)) self._log(logging.DEBUG, u' \u251C\u2500 method: {0}'.format(method)) self._log(logging.DEBUG, u' \u251C\u2500 body: {0}'.format(body)) self._log(logging.DEBUG, u' \u251C\u2500 params: {0}'.format(params)) self._log(logging.DEBUG, u' \u2514\u2500 headers: {0}'.format(headers)) # Connect if scheme.lower() == 'https': connection = http_client.HTTPSConnection(host) else: connection = http_client.HTTPConnection(host) try: connection.request(method, request_path, body, headers) except Exception as e: raise FetchError('Fetching URL failed', original_message=str(e), url=request_path) response = connection.getresponse() location = response.getheader('Location') if response.status in (300, 301, 302, 303, 307) and location: if location == url: raise FetchError('Url redirects to itself!', url=location, status=response.status) elif max_redirects > 0: remaining_redirects = max_redirects - 1 self._log(logging.DEBUG, u'Redirecting to {0}'.format(url)) self._log(logging.DEBUG, u'Remaining redirects: {0}' .format(remaining_redirects)) # Call this method again. response = self._fetch(url=location, params=params, method=method, headers=headers, max_redirects=remaining_redirects) else: raise FetchError('Max redirects reached!', url=location, status=response.status) else: self._log(logging.DEBUG, u'Got response:') self._log(logging.DEBUG, u' \u251C\u2500 url: {0}'.format(url)) self._log( logging.DEBUG, u' \u251C\u2500 status: {0}'.format( response.status)) self._log( logging.DEBUG, u' \u2514\u2500 headers: {0}'.format( response.getheaders())) return authomatic.core.Response(response, content_parser)
[ "Fetches", "a", "URL", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L355-L464
[ "def", "_fetch", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "max_redirects", "=", "5", ",", "content_parser", "=", "None", ")", ":", "# 'magic' using _kwarg method", "# pylint:disable=no-member", "params", "=", "params", "or", "{", "}", "params", ".", "update", "(", "self", ".", "access_params", ")", "headers", "=", "headers", "or", "{", "}", "headers", ".", "update", "(", "self", ".", "access_headers", ")", "scheme", ",", "host", ",", "path", ",", "query", ",", "fragment", "=", "parse", ".", "urlsplit", "(", "url", ")", "query", "=", "parse", ".", "urlencode", "(", "params", ")", "if", "method", "in", "(", "'POST'", ",", "'PUT'", ",", "'PATCH'", ")", ":", "if", "not", "body", ":", "# Put querystring to body", "body", "=", "query", "query", "=", "''", "headers", ".", "update", "(", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", ")", "request_path", "=", "parse", ".", "urlunsplit", "(", "(", "''", ",", "''", ",", "path", "or", "''", ",", "query", "or", "''", ",", "''", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u251C\\u2500 host: {0}'", ".", "format", "(", "host", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u251C\\u2500 path: {0}'", ".", "format", "(", "request_path", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u251C\\u2500 method: {0}'", ".", "format", "(", "method", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u251C\\u2500 body: {0}'", ".", "format", "(", "body", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u251C\\u2500 params: {0}'", ".", "format", "(", "params", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u2514\\u2500 headers: {0}'", ".", "format", "(", "headers", ")", ")", "# Connect", "if", "scheme", ".", "lower", "(", ")", "==", "'https'", ":", "connection", "=", "http_client", ".", "HTTPSConnection", "(", "host", ")", "else", ":", "connection", "=", "http_client", ".", "HTTPConnection", "(", "host", ")", "try", ":", "connection", ".", "request", "(", "method", ",", "request_path", ",", "body", ",", "headers", ")", "except", "Exception", "as", "e", ":", "raise", "FetchError", "(", "'Fetching URL failed'", ",", "original_message", "=", "str", "(", "e", ")", ",", "url", "=", "request_path", ")", "response", "=", "connection", ".", "getresponse", "(", ")", "location", "=", "response", ".", "getheader", "(", "'Location'", ")", "if", "response", ".", "status", "in", "(", "300", ",", "301", ",", "302", ",", "303", ",", "307", ")", "and", "location", ":", "if", "location", "==", "url", ":", "raise", "FetchError", "(", "'Url redirects to itself!'", ",", "url", "=", "location", ",", "status", "=", "response", ".", "status", ")", "elif", "max_redirects", ">", "0", ":", "remaining_redirects", "=", "max_redirects", "-", "1", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u'Redirecting to {0}'", ".", "format", "(", "url", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u'Remaining redirects: {0}'", ".", "format", "(", "remaining_redirects", ")", ")", "# Call this method again.", "response", "=", "self", ".", "_fetch", "(", "url", "=", "location", ",", "params", "=", "params", ",", "method", "=", "method", ",", "headers", "=", "headers", ",", "max_redirects", "=", "remaining_redirects", ")", "else", ":", "raise", "FetchError", "(", "'Max redirects reached!'", ",", "url", "=", "location", ",", "status", "=", "response", ".", "status", ")", "else", ":", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u'Got response:'", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u251C\\u2500 url: {0}'", ".", "format", "(", "url", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u251C\\u2500 status: {0}'", ".", "format", "(", "response", ".", "status", ")", ")", "self", ".", "_log", "(", "logging", ".", "DEBUG", ",", "u' \\u2514\\u2500 headers: {0}'", ".", "format", "(", "response", ".", "getheaders", "(", ")", ")", ")", "return", "authomatic", ".", "core", ".", "Response", "(", "response", ",", "content_parser", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider._update_or_create_user
Updates or creates :attr:`.user`. :returns: :class:`.User`
authomatic/providers/__init__.py
def _update_or_create_user(self, data, credentials=None, content=None): """ Updates or creates :attr:`.user`. :returns: :class:`.User` """ if not self.user: self.user = authomatic.core.User(self, credentials=credentials) self.user.content = content self.user.data = data # Update. for key in self.user.__dict__: # Exclude data. if key not in ('data', 'content'): # Extract every data item whose key matches the user # property name, but only if it has a value. value = data.get(key) if value: setattr(self.user, key, value) # Handle different structure of data by different providers. self.user = self._x_user_parser(self.user, data) if self.user.id: self.user.id = str(self.user.id) # TODO: Move to User # If there is no user.name, if not self.user.name: if self.user.first_name and self.user.last_name: # Create it from first name and last name if available. self.user.name = ' '.join((self.user.first_name, self.user.last_name)) else: # Or use one of these. self.user.name = (self.user.username or self.user.nickname or self.user.first_name or self.user.last_name) if not self.user.location: if self.user.city and self.user.country: self.user.location = '{0}, {1}'.format(self.user.city, self.user.country) else: self.user.location = self.user.city or self.user.country return self.user
def _update_or_create_user(self, data, credentials=None, content=None): """ Updates or creates :attr:`.user`. :returns: :class:`.User` """ if not self.user: self.user = authomatic.core.User(self, credentials=credentials) self.user.content = content self.user.data = data # Update. for key in self.user.__dict__: # Exclude data. if key not in ('data', 'content'): # Extract every data item whose key matches the user # property name, but only if it has a value. value = data.get(key) if value: setattr(self.user, key, value) # Handle different structure of data by different providers. self.user = self._x_user_parser(self.user, data) if self.user.id: self.user.id = str(self.user.id) # TODO: Move to User # If there is no user.name, if not self.user.name: if self.user.first_name and self.user.last_name: # Create it from first name and last name if available. self.user.name = ' '.join((self.user.first_name, self.user.last_name)) else: # Or use one of these. self.user.name = (self.user.username or self.user.nickname or self.user.first_name or self.user.last_name) if not self.user.location: if self.user.city and self.user.country: self.user.location = '{0}, {1}'.format(self.user.city, self.user.country) else: self.user.location = self.user.city or self.user.country return self.user
[ "Updates", "or", "creates", ":", "attr", ":", ".", "user", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L466-L516
[ "def", "_update_or_create_user", "(", "self", ",", "data", ",", "credentials", "=", "None", ",", "content", "=", "None", ")", ":", "if", "not", "self", ".", "user", ":", "self", ".", "user", "=", "authomatic", ".", "core", ".", "User", "(", "self", ",", "credentials", "=", "credentials", ")", "self", ".", "user", ".", "content", "=", "content", "self", ".", "user", ".", "data", "=", "data", "# Update.", "for", "key", "in", "self", ".", "user", ".", "__dict__", ":", "# Exclude data.", "if", "key", "not", "in", "(", "'data'", ",", "'content'", ")", ":", "# Extract every data item whose key matches the user", "# property name, but only if it has a value.", "value", "=", "data", ".", "get", "(", "key", ")", "if", "value", ":", "setattr", "(", "self", ".", "user", ",", "key", ",", "value", ")", "# Handle different structure of data by different providers.", "self", ".", "user", "=", "self", ".", "_x_user_parser", "(", "self", ".", "user", ",", "data", ")", "if", "self", ".", "user", ".", "id", ":", "self", ".", "user", ".", "id", "=", "str", "(", "self", ".", "user", ".", "id", ")", "# TODO: Move to User", "# If there is no user.name,", "if", "not", "self", ".", "user", ".", "name", ":", "if", "self", ".", "user", ".", "first_name", "and", "self", ".", "user", ".", "last_name", ":", "# Create it from first name and last name if available.", "self", ".", "user", ".", "name", "=", "' '", ".", "join", "(", "(", "self", ".", "user", ".", "first_name", ",", "self", ".", "user", ".", "last_name", ")", ")", "else", ":", "# Or use one of these.", "self", ".", "user", ".", "name", "=", "(", "self", ".", "user", ".", "username", "or", "self", ".", "user", ".", "nickname", "or", "self", ".", "user", ".", "first_name", "or", "self", ".", "user", ".", "last_name", ")", "if", "not", "self", ".", "user", ".", "location", ":", "if", "self", ".", "user", ".", "city", "and", "self", ".", "user", ".", "country", ":", "self", ".", "user", ".", "location", "=", "'{0}, {1}'", ".", "format", "(", "self", ".", "user", ".", "city", ",", "self", ".", "user", ".", "country", ")", "else", ":", "self", ".", "user", ".", "location", "=", "self", ".", "user", ".", "city", "or", "self", ".", "user", ".", "country", "return", "self", ".", "user" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
BaseProvider._http_status_in_category
Checks whether a HTTP status code is in the category denoted by the hundreds digit.
authomatic/providers/__init__.py
def _http_status_in_category(status, category): """ Checks whether a HTTP status code is in the category denoted by the hundreds digit. """ assert category < 10, 'HTTP status category must be a one-digit int!' cat = category * 100 return status >= cat and status < cat + 100
def _http_status_in_category(status, category): """ Checks whether a HTTP status code is in the category denoted by the hundreds digit. """ assert category < 10, 'HTTP status category must be a one-digit int!' cat = category * 100 return status >= cat and status < cat + 100
[ "Checks", "whether", "a", "HTTP", "status", "code", "is", "in", "the", "category", "denoted", "by", "the", "hundreds", "digit", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L533-L541
[ "def", "_http_status_in_category", "(", "status", ",", "category", ")", ":", "assert", "category", "<", "10", ",", "'HTTP status category must be a one-digit int!'", "cat", "=", "category", "*", "100", "return", "status", ">=", "cat", "and", "status", "<", "cat", "+", "100" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider.type_id
A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part after hyphen denotes the class id e.g. ``oauth2.Facebook.type_id = '2-5'``, ``oauth1.Twitter.type_id = '1-5'``.
authomatic/providers/__init__.py
def type_id(self): """ A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part after hyphen denotes the class id e.g. ``oauth2.Facebook.type_id = '2-5'``, ``oauth1.Twitter.type_id = '1-5'``. """ cls = self.__class__ mod = sys.modules.get(cls.__module__) return str(self.PROVIDER_TYPE_ID) + '-' + \ str(mod.PROVIDER_ID_MAP.index(cls))
def type_id(self): """ A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part after hyphen denotes the class id e.g. ``oauth2.Facebook.type_id = '2-5'``, ``oauth1.Twitter.type_id = '1-5'``. """ cls = self.__class__ mod = sys.modules.get(cls.__module__) return str(self.PROVIDER_TYPE_ID) + '-' + \ str(mod.PROVIDER_ID_MAP.index(cls))
[ "A", "short", "string", "representing", "the", "provider", "implementation", "id", "used", "for", "serialization", "of", ":", "class", ":", ".", "Credentials", "and", "to", "identify", "the", "type", "of", "provider", "in", "JavaScript", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L754-L771
[ "def", "type_id", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "mod", "=", "sys", ".", "modules", ".", "get", "(", "cls", ".", "__module__", ")", "return", "str", "(", "self", ".", "PROVIDER_TYPE_ID", ")", "+", "'-'", "+", "str", "(", "mod", ".", "PROVIDER_ID_MAP", ".", "index", "(", "cls", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider.access
Fetches the **protected resource** of an authenticated **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). :param str url: The URL of the **protected resource**. :param str method: HTTP method of the request. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Maximum number of HTTP redirects to follow. :param function content_parser: A function to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. :returns: :class:`.Response`
authomatic/providers/__init__.py
def access(self, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None): """ Fetches the **protected resource** of an authenticated **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). :param str url: The URL of the **protected resource**. :param str method: HTTP method of the request. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Maximum number of HTTP redirects to follow. :param function content_parser: A function to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. :returns: :class:`.Response` """ if not self.user and not self.credentials: raise CredentialsError(u'There is no authenticated user!') headers = headers or {} self._log( logging.INFO, u'Accessing protected resource {0}.'.format(url)) request_elements = self.create_request_elements( request_type=self.PROTECTED_RESOURCE_REQUEST_TYPE, credentials=self.credentials, url=url, body=body, params=params, headers=headers, method=method ) response = self._fetch(*request_elements, max_redirects=max_redirects, content_parser=content_parser) self._log( logging.INFO, u'Got response. HTTP status = {0}.'.format( response.status)) return response
def access(self, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None): """ Fetches the **protected resource** of an authenticated **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). :param str url: The URL of the **protected resource**. :param str method: HTTP method of the request. :param dict headers: HTTP headers of the request. :param str body: Body of ``POST``, ``PUT`` and ``PATCH`` requests. :param int max_redirects: Maximum number of HTTP redirects to follow. :param function content_parser: A function to be used to parse the :attr:`.Response.data` from :attr:`.Response.content`. :returns: :class:`.Response` """ if not self.user and not self.credentials: raise CredentialsError(u'There is no authenticated user!') headers = headers or {} self._log( logging.INFO, u'Accessing protected resource {0}.'.format(url)) request_elements = self.create_request_elements( request_type=self.PROTECTED_RESOURCE_REQUEST_TYPE, credentials=self.credentials, url=url, body=body, params=params, headers=headers, method=method ) response = self._fetch(*request_elements, max_redirects=max_redirects, content_parser=content_parser) self._log( logging.INFO, u'Got response. HTTP status = {0}.'.format( response.status)) return response
[ "Fetches", "the", "**", "protected", "resource", "**", "of", "an", "authenticated", "**", "user", "**", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L773-L832
[ "def", "access", "(", "self", ",", "url", ",", "params", "=", "None", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "max_redirects", "=", "5", ",", "content_parser", "=", "None", ")", ":", "if", "not", "self", ".", "user", "and", "not", "self", ".", "credentials", ":", "raise", "CredentialsError", "(", "u'There is no authenticated user!'", ")", "headers", "=", "headers", "or", "{", "}", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Accessing protected resource {0}.'", ".", "format", "(", "url", ")", ")", "request_elements", "=", "self", ".", "create_request_elements", "(", "request_type", "=", "self", ".", "PROTECTED_RESOURCE_REQUEST_TYPE", ",", "credentials", "=", "self", ".", "credentials", ",", "url", "=", "url", ",", "body", "=", "body", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "method", "=", "method", ")", "response", "=", "self", ".", "_fetch", "(", "*", "request_elements", ",", "max_redirects", "=", "max_redirects", ",", "content_parser", "=", "content_parser", ")", "self", ".", "_log", "(", "logging", ".", "INFO", ",", "u'Got response. HTTP status = {0}.'", ".", "format", "(", "response", ".", "status", ")", ")", "return", "response" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider.async_access
Same as :meth:`.access` but runs asynchronously in a separate thread. .. warning:: |async| :returns: :class:`.Future` instance representing the separate thread.
authomatic/providers/__init__.py
def async_access(self, *args, **kwargs): """ Same as :meth:`.access` but runs asynchronously in a separate thread. .. warning:: |async| :returns: :class:`.Future` instance representing the separate thread. """ return authomatic.core.Future(self.access, *args, **kwargs)
def async_access(self, *args, **kwargs): """ Same as :meth:`.access` but runs asynchronously in a separate thread. .. warning:: |async| :returns: :class:`.Future` instance representing the separate thread. """ return authomatic.core.Future(self.access, *args, **kwargs)
[ "Same", "as", ":", "meth", ":", ".", "access", "but", "runs", "asynchronously", "in", "a", "separate", "thread", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L834-L847
[ "def", "async_access", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "authomatic", ".", "core", ".", "Future", "(", "self", ".", "access", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider.update_user
Updates the :attr:`.BaseProvider.user`. .. warning:: Fetches the :attr:`.user_info_url`! :returns: :class:`.UserInfoResponse`
authomatic/providers/__init__.py
def update_user(self): """ Updates the :attr:`.BaseProvider.user`. .. warning:: Fetches the :attr:`.user_info_url`! :returns: :class:`.UserInfoResponse` """ if self.user_info_url: response = self._access_user_info() self.user = self._update_or_create_user(response.data, content=response.content) return authomatic.core.UserInfoResponse(self.user, response.httplib_response)
def update_user(self): """ Updates the :attr:`.BaseProvider.user`. .. warning:: Fetches the :attr:`.user_info_url`! :returns: :class:`.UserInfoResponse` """ if self.user_info_url: response = self._access_user_info() self.user = self._update_or_create_user(response.data, content=response.content) return authomatic.core.UserInfoResponse(self.user, response.httplib_response)
[ "Updates", "the", ":", "attr", ":", ".", "BaseProvider", ".", "user", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L849-L865
[ "def", "update_user", "(", "self", ")", ":", "if", "self", ".", "user_info_url", ":", "response", "=", "self", ".", "_access_user_info", "(", ")", "self", ".", "user", "=", "self", ".", "_update_or_create_user", "(", "response", ".", "data", ",", "content", "=", "response", ".", "content", ")", "return", "authomatic", ".", "core", ".", "UserInfoResponse", "(", "self", ".", "user", ",", "response", ".", "httplib_response", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider._authorization_header
Creates authorization headers if the provider supports it. See: http://en.wikipedia.org/wiki/Basic_access_authentication. :param credentials: :class:`.Credentials` :returns: Headers as :class:`dict`.
authomatic/providers/__init__.py
def _authorization_header(cls, credentials): """ Creates authorization headers if the provider supports it. See: http://en.wikipedia.org/wiki/Basic_access_authentication. :param credentials: :class:`.Credentials` :returns: Headers as :class:`dict`. """ if cls._x_use_authorization_header: res = ':'.join( (credentials.consumer_key, credentials.consumer_secret)) res = base64.b64encode(six.b(res)).decode() return {'Authorization': 'Basic {0}'.format(res)} else: return {}
def _authorization_header(cls, credentials): """ Creates authorization headers if the provider supports it. See: http://en.wikipedia.org/wiki/Basic_access_authentication. :param credentials: :class:`.Credentials` :returns: Headers as :class:`dict`. """ if cls._x_use_authorization_header: res = ':'.join( (credentials.consumer_key, credentials.consumer_secret)) res = base64.b64encode(six.b(res)).decode() return {'Authorization': 'Basic {0}'.format(res)} else: return {}
[ "Creates", "authorization", "headers", "if", "the", "provider", "supports", "it", ".", "See", ":", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Basic_access_authentication", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L872-L892
[ "def", "_authorization_header", "(", "cls", ",", "credentials", ")", ":", "if", "cls", ".", "_x_use_authorization_header", ":", "res", "=", "':'", ".", "join", "(", "(", "credentials", ".", "consumer_key", ",", "credentials", ".", "consumer_secret", ")", ")", "res", "=", "base64", ".", "b64encode", "(", "six", ".", "b", "(", "res", ")", ")", ".", "decode", "(", ")", "return", "{", "'Authorization'", ":", "'Basic {0}'", ".", "format", "(", "res", ")", "}", "else", ":", "return", "{", "}" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider._check_consumer
Validates the :attr:`.consumer`.
authomatic/providers/__init__.py
def _check_consumer(self): """ Validates the :attr:`.consumer`. """ # 'magic' using _kwarg method # pylint:disable=no-member if not self.consumer.key: raise ConfigError( 'Consumer key not specified for provider {0}!'.format( self.name)) if not self.consumer.secret: raise ConfigError( 'Consumer secret not specified for provider {0}!'.format( self.name))
def _check_consumer(self): """ Validates the :attr:`.consumer`. """ # 'magic' using _kwarg method # pylint:disable=no-member if not self.consumer.key: raise ConfigError( 'Consumer key not specified for provider {0}!'.format( self.name)) if not self.consumer.secret: raise ConfigError( 'Consumer secret not specified for provider {0}!'.format( self.name))
[ "Validates", "the", ":", "attr", ":", ".", "consumer", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L894-L909
[ "def", "_check_consumer", "(", "self", ")", ":", "# 'magic' using _kwarg method", "# pylint:disable=no-member", "if", "not", "self", ".", "consumer", ".", "key", ":", "raise", "ConfigError", "(", "'Consumer key not specified for provider {0}!'", ".", "format", "(", "self", ".", "name", ")", ")", "if", "not", "self", ".", "consumer", ".", "secret", ":", "raise", "ConfigError", "(", "'Consumer secret not specified for provider {0}!'", ".", "format", "(", "self", ".", "name", ")", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider._split_url
Splits given url to url base and params converted to list of tuples.
authomatic/providers/__init__.py
def _split_url(url): """ Splits given url to url base and params converted to list of tuples. """ split = parse.urlsplit(url) base = parse.urlunsplit((split.scheme, split.netloc, split.path, 0, 0)) params = parse.parse_qsl(split.query, True) return base, params
def _split_url(url): """ Splits given url to url base and params converted to list of tuples. """ split = parse.urlsplit(url) base = parse.urlunsplit((split.scheme, split.netloc, split.path, 0, 0)) params = parse.parse_qsl(split.query, True) return base, params
[ "Splits", "given", "url", "to", "url", "base", "and", "params", "converted", "to", "list", "of", "tuples", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L912-L921
[ "def", "_split_url", "(", "url", ")", ":", "split", "=", "parse", ".", "urlsplit", "(", "url", ")", "base", "=", "parse", ".", "urlunsplit", "(", "(", "split", ".", "scheme", ",", "split", ".", "netloc", ",", "split", ".", "path", ",", "0", ",", "0", ")", ")", "params", "=", "parse", ".", "parse_qsl", "(", "split", ".", "query", ",", "True", ")", "return", "base", ",", "params" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
AuthorizationProvider._access_user_info
Accesses the :attr:`.user_info_url`. :returns: :class:`.UserInfoResponse`
authomatic/providers/__init__.py
def _access_user_info(self): """ Accesses the :attr:`.user_info_url`. :returns: :class:`.UserInfoResponse` """ url = self.user_info_url.format(**self.user.__dict__) return self.access(url)
def _access_user_info(self): """ Accesses the :attr:`.user_info_url`. :returns: :class:`.UserInfoResponse` """ url = self.user_info_url.format(**self.user.__dict__) return self.access(url)
[ "Accesses", "the", ":", "attr", ":", ".", "user_info_url", "." ]
authomatic/authomatic
python
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/providers/__init__.py#L968-L977
[ "def", "_access_user_info", "(", "self", ")", ":", "url", "=", "self", ".", "user_info_url", ".", "format", "(", "*", "*", "self", ".", "user", ".", "__dict__", ")", "return", "self", ".", "access", "(", "url", ")" ]
90a9ce60cc405ae8a2bf5c3713acd5d78579a04e
test
cross_origin
This function is the decorator which is used to wrap a Sanic route with. In the simplest case, simply use the default parameters to allow all origins in what is the most permissive configuration. If this method modifies state or performs authentication which may be brute-forced, you should add some degree of protection, such as Cross Site Forgery Request protection. :param origins: The origin, or list of origins to allow requests from. The origin(s) may be regular expressions, case-sensitive strings, or else an asterisk Default : '*' :type origins: list, string or regex :param methods: The method or list of methods which the allowed origins are allowed to access for non-simple requests. Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE] :type methods: list or string :param expose_headers: The header or list which are safe to expose to the API of a CORS API specification. Default : None :type expose_headers: list or string :param allow_headers: The header or list of header field names which can be used when this resource is accessed by allowed origins. The header(s) may be regular expressions, case-sensitive strings, or else an asterisk. Default : '*', allow all headers :type allow_headers: list, string or regex :param supports_credentials: Allows users to make authenticated requests. If true, injects the `Access-Control-Allow-Credentials` header in responses. This allows cookies and credentials to be submitted across domains. :note: This option cannot be used in conjuction with a '*' origin Default : False :type supports_credentials: bool :param max_age: The maximum time for which this CORS request maybe cached. This value is set as the `Access-Control-Max-Age` header. Default : None :type max_age: timedelta, integer, string or None :param send_wildcard: If True, and the origins parameter is `*`, a wildcard `Access-Control-Allow-Origin` header is sent, rather than the request's `Origin` header. Default : False :type send_wildcard: bool :param vary_header: If True, the header Vary: Origin will be returned as per the W3 implementation guidelines. Setting this header when the `Access-Control-Allow-Origin` is dynamically generated (e.g. when there is more than one allowed origin, and an Origin than '*' is returned) informs CDNs and other caches that the CORS headers are dynamic, and cannot be cached. If False, the Vary header will never be injected or altered. Default : True :type vary_header: bool :param automatic_options: Only applies to the `cross_origin` decorator. If True, Sanic-CORS will override Sanic's default OPTIONS handling to return CORS headers for OPTIONS requests. Default : True :type automatic_options: bool
sanic_cors/decorator.py
def cross_origin(app, *args, **kwargs): """ This function is the decorator which is used to wrap a Sanic route with. In the simplest case, simply use the default parameters to allow all origins in what is the most permissive configuration. If this method modifies state or performs authentication which may be brute-forced, you should add some degree of protection, such as Cross Site Forgery Request protection. :param origins: The origin, or list of origins to allow requests from. The origin(s) may be regular expressions, case-sensitive strings, or else an asterisk Default : '*' :type origins: list, string or regex :param methods: The method or list of methods which the allowed origins are allowed to access for non-simple requests. Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE] :type methods: list or string :param expose_headers: The header or list which are safe to expose to the API of a CORS API specification. Default : None :type expose_headers: list or string :param allow_headers: The header or list of header field names which can be used when this resource is accessed by allowed origins. The header(s) may be regular expressions, case-sensitive strings, or else an asterisk. Default : '*', allow all headers :type allow_headers: list, string or regex :param supports_credentials: Allows users to make authenticated requests. If true, injects the `Access-Control-Allow-Credentials` header in responses. This allows cookies and credentials to be submitted across domains. :note: This option cannot be used in conjuction with a '*' origin Default : False :type supports_credentials: bool :param max_age: The maximum time for which this CORS request maybe cached. This value is set as the `Access-Control-Max-Age` header. Default : None :type max_age: timedelta, integer, string or None :param send_wildcard: If True, and the origins parameter is `*`, a wildcard `Access-Control-Allow-Origin` header is sent, rather than the request's `Origin` header. Default : False :type send_wildcard: bool :param vary_header: If True, the header Vary: Origin will be returned as per the W3 implementation guidelines. Setting this header when the `Access-Control-Allow-Origin` is dynamically generated (e.g. when there is more than one allowed origin, and an Origin than '*' is returned) informs CDNs and other caches that the CORS headers are dynamic, and cannot be cached. If False, the Vary header will never be injected or altered. Default : True :type vary_header: bool :param automatic_options: Only applies to the `cross_origin` decorator. If True, Sanic-CORS will override Sanic's default OPTIONS handling to return CORS headers for OPTIONS requests. Default : True :type automatic_options: bool """ _options = kwargs _real_decorator = cors.decorate(app, *args, run_middleware=False, with_context=False, **kwargs) def wrapped_decorator(f): spf = SanicPluginsFramework(app) # get the singleton from the app try: plugin = spf.register_plugin(cors, skip_reg=True) except ValueError as e: # this is normal, if this plugin has been registered previously assert e.args and len(e.args) > 1 plugin = e.args[1] context = cors.get_context_from_spf(spf) log = context.log log(logging.DEBUG, "Enabled {:s} for cross_origin using options: {}".format(str(f), str(_options))) return _real_decorator(f) return wrapped_decorator
def cross_origin(app, *args, **kwargs): """ This function is the decorator which is used to wrap a Sanic route with. In the simplest case, simply use the default parameters to allow all origins in what is the most permissive configuration. If this method modifies state or performs authentication which may be brute-forced, you should add some degree of protection, such as Cross Site Forgery Request protection. :param origins: The origin, or list of origins to allow requests from. The origin(s) may be regular expressions, case-sensitive strings, or else an asterisk Default : '*' :type origins: list, string or regex :param methods: The method or list of methods which the allowed origins are allowed to access for non-simple requests. Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE] :type methods: list or string :param expose_headers: The header or list which are safe to expose to the API of a CORS API specification. Default : None :type expose_headers: list or string :param allow_headers: The header or list of header field names which can be used when this resource is accessed by allowed origins. The header(s) may be regular expressions, case-sensitive strings, or else an asterisk. Default : '*', allow all headers :type allow_headers: list, string or regex :param supports_credentials: Allows users to make authenticated requests. If true, injects the `Access-Control-Allow-Credentials` header in responses. This allows cookies and credentials to be submitted across domains. :note: This option cannot be used in conjuction with a '*' origin Default : False :type supports_credentials: bool :param max_age: The maximum time for which this CORS request maybe cached. This value is set as the `Access-Control-Max-Age` header. Default : None :type max_age: timedelta, integer, string or None :param send_wildcard: If True, and the origins parameter is `*`, a wildcard `Access-Control-Allow-Origin` header is sent, rather than the request's `Origin` header. Default : False :type send_wildcard: bool :param vary_header: If True, the header Vary: Origin will be returned as per the W3 implementation guidelines. Setting this header when the `Access-Control-Allow-Origin` is dynamically generated (e.g. when there is more than one allowed origin, and an Origin than '*' is returned) informs CDNs and other caches that the CORS headers are dynamic, and cannot be cached. If False, the Vary header will never be injected or altered. Default : True :type vary_header: bool :param automatic_options: Only applies to the `cross_origin` decorator. If True, Sanic-CORS will override Sanic's default OPTIONS handling to return CORS headers for OPTIONS requests. Default : True :type automatic_options: bool """ _options = kwargs _real_decorator = cors.decorate(app, *args, run_middleware=False, with_context=False, **kwargs) def wrapped_decorator(f): spf = SanicPluginsFramework(app) # get the singleton from the app try: plugin = spf.register_plugin(cors, skip_reg=True) except ValueError as e: # this is normal, if this plugin has been registered previously assert e.args and len(e.args) > 1 plugin = e.args[1] context = cors.get_context_from_spf(spf) log = context.log log(logging.DEBUG, "Enabled {:s} for cross_origin using options: {}".format(str(f), str(_options))) return _real_decorator(f) return wrapped_decorator
[ "This", "function", "is", "the", "decorator", "which", "is", "used", "to", "wrap", "a", "Sanic", "route", "with", ".", "In", "the", "simplest", "case", "simply", "use", "the", "default", "parameters", "to", "allow", "all", "origins", "in", "what", "is", "the", "most", "permissive", "configuration", ".", "If", "this", "method", "modifies", "state", "or", "performs", "authentication", "which", "may", "be", "brute", "-", "forced", "you", "should", "add", "some", "degree", "of", "protection", "such", "as", "Cross", "Site", "Forgery", "Request", "protection", "." ]
ashleysommer/sanic-cors
python
https://github.com/ashleysommer/sanic-cors/blob/f3d68def8cf859398b3c83e4109d815f1f038ea2/sanic_cors/decorator.py#L18-L120
[ "def", "cross_origin", "(", "app", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_options", "=", "kwargs", "_real_decorator", "=", "cors", ".", "decorate", "(", "app", ",", "*", "args", ",", "run_middleware", "=", "False", ",", "with_context", "=", "False", ",", "*", "*", "kwargs", ")", "def", "wrapped_decorator", "(", "f", ")", ":", "spf", "=", "SanicPluginsFramework", "(", "app", ")", "# get the singleton from the app", "try", ":", "plugin", "=", "spf", ".", "register_plugin", "(", "cors", ",", "skip_reg", "=", "True", ")", "except", "ValueError", "as", "e", ":", "# this is normal, if this plugin has been registered previously", "assert", "e", ".", "args", "and", "len", "(", "e", ".", "args", ")", ">", "1", "plugin", "=", "e", ".", "args", "[", "1", "]", "context", "=", "cors", ".", "get_context_from_spf", "(", "spf", ")", "log", "=", "context", ".", "log", "log", "(", "logging", ".", "DEBUG", ",", "\"Enabled {:s} for cross_origin using options: {}\"", ".", "format", "(", "str", "(", "f", ")", ",", "str", "(", "_options", ")", ")", ")", "return", "_real_decorator", "(", "f", ")", "return", "wrapped_decorator" ]
f3d68def8cf859398b3c83e4109d815f1f038ea2
test
set_cors_headers
Performs the actual evaluation of Sanic-CORS options and actually modifies the response object. This function is used both in the decorator and the after_request callback :param sanic.request.Request req:
sanic_cors/core.py
def set_cors_headers(req, resp, context, options): """ Performs the actual evaluation of Sanic-CORS options and actually modifies the response object. This function is used both in the decorator and the after_request callback :param sanic.request.Request req: """ try: request_context = context.request[id(req)] except AttributeError: LOG.debug("Cannot find the request context. Is request already finished?") return resp # If CORS has already been evaluated via the decorator, skip evaluated = request_context.get(SANIC_CORS_EVALUATED, False) if evaluated: LOG.debug('CORS have been already evaluated, skipping') return resp # `resp` can be None in the case of using Websockets # however this case should have been handled in the `extension` and `decorator` methods # before getting here. This is a final failsafe check to prevent crashing if resp is None: return None if resp.headers is None: resp.headers = CIMultiDict() headers_to_set = get_cors_headers(options, req.headers, req.method) LOG.debug('Settings CORS headers: %s', str(headers_to_set)) # dict .extend() does not work on CIDict so # iterate over them and add them individually. try: resp.headers.extend(headers_to_set) except Exception as e1: for k, v in headers_to_set.items(): try: resp.headers.add(k, v) except Exception as e2: resp.headers[k] = v return resp
def set_cors_headers(req, resp, context, options): """ Performs the actual evaluation of Sanic-CORS options and actually modifies the response object. This function is used both in the decorator and the after_request callback :param sanic.request.Request req: """ try: request_context = context.request[id(req)] except AttributeError: LOG.debug("Cannot find the request context. Is request already finished?") return resp # If CORS has already been evaluated via the decorator, skip evaluated = request_context.get(SANIC_CORS_EVALUATED, False) if evaluated: LOG.debug('CORS have been already evaluated, skipping') return resp # `resp` can be None in the case of using Websockets # however this case should have been handled in the `extension` and `decorator` methods # before getting here. This is a final failsafe check to prevent crashing if resp is None: return None if resp.headers is None: resp.headers = CIMultiDict() headers_to_set = get_cors_headers(options, req.headers, req.method) LOG.debug('Settings CORS headers: %s', str(headers_to_set)) # dict .extend() does not work on CIDict so # iterate over them and add them individually. try: resp.headers.extend(headers_to_set) except Exception as e1: for k, v in headers_to_set.items(): try: resp.headers.add(k, v) except Exception as e2: resp.headers[k] = v return resp
[ "Performs", "the", "actual", "evaluation", "of", "Sanic", "-", "CORS", "options", "and", "actually", "modifies", "the", "response", "object", "." ]
ashleysommer/sanic-cors
python
https://github.com/ashleysommer/sanic-cors/blob/f3d68def8cf859398b3c83e4109d815f1f038ea2/sanic_cors/core.py#L221-L265
[ "def", "set_cors_headers", "(", "req", ",", "resp", ",", "context", ",", "options", ")", ":", "try", ":", "request_context", "=", "context", ".", "request", "[", "id", "(", "req", ")", "]", "except", "AttributeError", ":", "LOG", ".", "debug", "(", "\"Cannot find the request context. Is request already finished?\"", ")", "return", "resp", "# If CORS has already been evaluated via the decorator, skip", "evaluated", "=", "request_context", ".", "get", "(", "SANIC_CORS_EVALUATED", ",", "False", ")", "if", "evaluated", ":", "LOG", ".", "debug", "(", "'CORS have been already evaluated, skipping'", ")", "return", "resp", "# `resp` can be None in the case of using Websockets", "# however this case should have been handled in the `extension` and `decorator` methods", "# before getting here. This is a final failsafe check to prevent crashing", "if", "resp", "is", "None", ":", "return", "None", "if", "resp", ".", "headers", "is", "None", ":", "resp", ".", "headers", "=", "CIMultiDict", "(", ")", "headers_to_set", "=", "get_cors_headers", "(", "options", ",", "req", ".", "headers", ",", "req", ".", "method", ")", "LOG", ".", "debug", "(", "'Settings CORS headers: %s'", ",", "str", "(", "headers_to_set", ")", ")", "# dict .extend() does not work on CIDict so", "# iterate over them and add them individually.", "try", ":", "resp", ".", "headers", ".", "extend", "(", "headers_to_set", ")", "except", "Exception", "as", "e1", ":", "for", "k", ",", "v", "in", "headers_to_set", ".", "items", "(", ")", ":", "try", ":", "resp", ".", "headers", ".", "add", "(", "k", ",", "v", ")", "except", "Exception", "as", "e2", ":", "resp", ".", "headers", "[", "k", "]", "=", "v", "return", "resp" ]
f3d68def8cf859398b3c83e4109d815f1f038ea2
test
get_app_kwarg_dict
Returns the dictionary of CORS specific app configurations.
sanic_cors/core.py
def get_app_kwarg_dict(appInstance): """Returns the dictionary of CORS specific app configurations.""" # In order to support blueprints which do not have a config attribute app_config = getattr(appInstance, 'config', {}) return dict( (k.lower().replace('cors_', ''), app_config.get(k)) for k in CONFIG_OPTIONS if app_config.get(k) is not None )
def get_app_kwarg_dict(appInstance): """Returns the dictionary of CORS specific app configurations.""" # In order to support blueprints which do not have a config attribute app_config = getattr(appInstance, 'config', {}) return dict( (k.lower().replace('cors_', ''), app_config.get(k)) for k in CONFIG_OPTIONS if app_config.get(k) is not None )
[ "Returns", "the", "dictionary", "of", "CORS", "specific", "app", "configurations", "." ]
ashleysommer/sanic-cors
python
https://github.com/ashleysommer/sanic-cors/blob/f3d68def8cf859398b3c83e4109d815f1f038ea2/sanic_cors/core.py#L318-L326
[ "def", "get_app_kwarg_dict", "(", "appInstance", ")", ":", "# In order to support blueprints which do not have a config attribute", "app_config", "=", "getattr", "(", "appInstance", ",", "'config'", ",", "{", "}", ")", "return", "dict", "(", "(", "k", ".", "lower", "(", ")", ".", "replace", "(", "'cors_'", ",", "''", ")", ",", "app_config", ".", "get", "(", "k", ")", ")", "for", "k", "in", "CONFIG_OPTIONS", "if", "app_config", ".", "get", "(", "k", ")", "is", "not", "None", ")" ]
f3d68def8cf859398b3c83e4109d815f1f038ea2
test
flexible_str
A more flexible str function which intelligently handles stringifying strings, lists and other iterables. The results are lexographically sorted to ensure generated responses are consistent when iterables such as Set are used.
sanic_cors/core.py
def flexible_str(obj): """ A more flexible str function which intelligently handles stringifying strings, lists and other iterables. The results are lexographically sorted to ensure generated responses are consistent when iterables such as Set are used. """ if obj is None: return None elif(not isinstance(obj, str) and isinstance(obj, collections.abc.Iterable)): return ', '.join(str(item) for item in sorted(obj)) else: return str(obj)
def flexible_str(obj): """ A more flexible str function which intelligently handles stringifying strings, lists and other iterables. The results are lexographically sorted to ensure generated responses are consistent when iterables such as Set are used. """ if obj is None: return None elif(not isinstance(obj, str) and isinstance(obj, collections.abc.Iterable)): return ', '.join(str(item) for item in sorted(obj)) else: return str(obj)
[ "A", "more", "flexible", "str", "function", "which", "intelligently", "handles", "stringifying", "strings", "lists", "and", "other", "iterables", ".", "The", "results", "are", "lexographically", "sorted", "to", "ensure", "generated", "responses", "are", "consistent", "when", "iterables", "such", "as", "Set", "are", "used", "." ]
ashleysommer/sanic-cors
python
https://github.com/ashleysommer/sanic-cors/blob/f3d68def8cf859398b3c83e4109d815f1f038ea2/sanic_cors/core.py#L329-L342
[ "def", "flexible_str", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "None", "elif", "(", "not", "isinstance", "(", "obj", ",", "str", ")", "and", "isinstance", "(", "obj", ",", "collections", ".", "abc", ".", "Iterable", ")", ")", ":", "return", "', '", ".", "join", "(", "str", "(", "item", ")", "for", "item", "in", "sorted", "(", "obj", ")", ")", "else", ":", "return", "str", "(", "obj", ")" ]
f3d68def8cf859398b3c83e4109d815f1f038ea2
test
ensure_iterable
Wraps scalars or string types as a list, or returns the iterable instance.
sanic_cors/core.py
def ensure_iterable(inst): """ Wraps scalars or string types as a list, or returns the iterable instance. """ if isinstance(inst, str): return [inst] elif not isinstance(inst, collections.abc.Iterable): return [inst] else: return inst
def ensure_iterable(inst): """ Wraps scalars or string types as a list, or returns the iterable instance. """ if isinstance(inst, str): return [inst] elif not isinstance(inst, collections.abc.Iterable): return [inst] else: return inst
[ "Wraps", "scalars", "or", "string", "types", "as", "a", "list", "or", "returns", "the", "iterable", "instance", "." ]
ashleysommer/sanic-cors
python
https://github.com/ashleysommer/sanic-cors/blob/f3d68def8cf859398b3c83e4109d815f1f038ea2/sanic_cors/core.py#L351-L360
[ "def", "ensure_iterable", "(", "inst", ")", ":", "if", "isinstance", "(", "inst", ",", "str", ")", ":", "return", "[", "inst", "]", "elif", "not", "isinstance", "(", "inst", ",", "collections", ".", "abc", ".", "Iterable", ")", ":", "return", "[", "inst", "]", "else", ":", "return", "inst" ]
f3d68def8cf859398b3c83e4109d815f1f038ea2
test
isclose
Python 3.4 does not have math.isclose, so we need to steal it and add it here.
algorithms/util.py
def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0): """ Python 3.4 does not have math.isclose, so we need to steal it and add it here. """ try: return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol) except AttributeError: # Running on older version of python, fall back to hand-rolled implementation if (rel_tol < 0.0) or (abs_tol < 0.0): raise ValueError("Tolerances must be non-negative, but are rel_tol: {} and abs_tol: {}".format(rel_tol, abs_tol)) if math.isnan(a) or math.isnan(b): return False # NaNs are never close to anything, even other NaNs if (a == b): return True if math.isinf(a) or math.isinf(b): return False # Infinity is only close to itself, and we already handled that case diff = abs(a - b) return (diff <= rel_tol * abs(b)) or (diff <= rel_tol * abs(a)) or (diff <= abs_tol)
def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0): """ Python 3.4 does not have math.isclose, so we need to steal it and add it here. """ try: return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol) except AttributeError: # Running on older version of python, fall back to hand-rolled implementation if (rel_tol < 0.0) or (abs_tol < 0.0): raise ValueError("Tolerances must be non-negative, but are rel_tol: {} and abs_tol: {}".format(rel_tol, abs_tol)) if math.isnan(a) or math.isnan(b): return False # NaNs are never close to anything, even other NaNs if (a == b): return True if math.isinf(a) or math.isinf(b): return False # Infinity is only close to itself, and we already handled that case diff = abs(a - b) return (diff <= rel_tol * abs(b)) or (diff <= rel_tol * abs(a)) or (diff <= abs_tol)
[ "Python", "3", ".", "4", "does", "not", "have", "math", ".", "isclose", "so", "we", "need", "to", "steal", "it", "and", "add", "it", "here", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/algorithms/util.py#L6-L23
[ "def", "isclose", "(", "a", ",", "b", ",", "*", ",", "rel_tol", "=", "1e-09", ",", "abs_tol", "=", "0.0", ")", ":", "try", ":", "return", "math", ".", "isclose", "(", "a", ",", "b", ",", "rel_tol", "=", "rel_tol", ",", "abs_tol", "=", "abs_tol", ")", "except", "AttributeError", ":", "# Running on older version of python, fall back to hand-rolled implementation", "if", "(", "rel_tol", "<", "0.0", ")", "or", "(", "abs_tol", "<", "0.0", ")", ":", "raise", "ValueError", "(", "\"Tolerances must be non-negative, but are rel_tol: {} and abs_tol: {}\"", ".", "format", "(", "rel_tol", ",", "abs_tol", ")", ")", "if", "math", ".", "isnan", "(", "a", ")", "or", "math", ".", "isnan", "(", "b", ")", ":", "return", "False", "# NaNs are never close to anything, even other NaNs", "if", "(", "a", "==", "b", ")", ":", "return", "True", "if", "math", ".", "isinf", "(", "a", ")", "or", "math", ".", "isinf", "(", "b", ")", ":", "return", "False", "# Infinity is only close to itself, and we already handled that case", "diff", "=", "abs", "(", "a", "-", "b", ")", "return", "(", "diff", "<=", "rel_tol", "*", "abs", "(", "b", ")", ")", "or", "(", "diff", "<=", "rel_tol", "*", "abs", "(", "a", ")", ")", "or", "(", "diff", "<=", "abs_tol", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
deprecated
Deprecator decorator.
audiosegment.py
def deprecated(func): """ Deprecator decorator. """ @functools.wraps(func) def new_func(*args, **kwargs): warnings.warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, stacklevel=2) return func(*args, **kwargs) return new_func
def deprecated(func): """ Deprecator decorator. """ @functools.wraps(func) def new_func(*args, **kwargs): warnings.warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, stacklevel=2) return func(*args, **kwargs) return new_func
[ "Deprecator", "decorator", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L47-L56
[ "def", "deprecated", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"Call to deprecated function {}.\"", ".", "format", "(", "func", ".", "__name__", ")", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
deserialize
Attempts to deserialize a bytestring into an audiosegment. :param bstr: The bytestring serialized via an audiosegment's serialize() method. :returns: An AudioSegment object deserialized from `bstr`.
audiosegment.py
def deserialize(bstr): """ Attempts to deserialize a bytestring into an audiosegment. :param bstr: The bytestring serialized via an audiosegment's serialize() method. :returns: An AudioSegment object deserialized from `bstr`. """ d = pickle.loads(bstr) seg = pickle.loads(d['seg']) return AudioSegment(seg, d['name'])
def deserialize(bstr): """ Attempts to deserialize a bytestring into an audiosegment. :param bstr: The bytestring serialized via an audiosegment's serialize() method. :returns: An AudioSegment object deserialized from `bstr`. """ d = pickle.loads(bstr) seg = pickle.loads(d['seg']) return AudioSegment(seg, d['name'])
[ "Attempts", "to", "deserialize", "a", "bytestring", "into", "an", "audiosegment", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L1074-L1083
[ "def", "deserialize", "(", "bstr", ")", ":", "d", "=", "pickle", ".", "loads", "(", "bstr", ")", "seg", "=", "pickle", ".", "loads", "(", "d", "[", "'seg'", "]", ")", "return", "AudioSegment", "(", "seg", ",", "d", "[", "'name'", "]", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
from_file
Returns an AudioSegment object from the given file based on its file extension. If the extension is wrong, this will throw some sort of error. :param path: The path to the file, including the file extension. :returns: An AudioSegment instance from the file.
audiosegment.py
def from_file(path): """ Returns an AudioSegment object from the given file based on its file extension. If the extension is wrong, this will throw some sort of error. :param path: The path to the file, including the file extension. :returns: An AudioSegment instance from the file. """ _name, ext = os.path.splitext(path) ext = ext.lower()[1:] seg = pydub.AudioSegment.from_file(path, ext) return AudioSegment(seg, path)
def from_file(path): """ Returns an AudioSegment object from the given file based on its file extension. If the extension is wrong, this will throw some sort of error. :param path: The path to the file, including the file extension. :returns: An AudioSegment instance from the file. """ _name, ext = os.path.splitext(path) ext = ext.lower()[1:] seg = pydub.AudioSegment.from_file(path, ext) return AudioSegment(seg, path)
[ "Returns", "an", "AudioSegment", "object", "from", "the", "given", "file", "based", "on", "its", "file", "extension", ".", "If", "the", "extension", "is", "wrong", "this", "will", "throw", "some", "sort", "of", "error", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L1094-L1105
[ "def", "from_file", "(", "path", ")", ":", "_name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "ext", "=", "ext", ".", "lower", "(", ")", "[", "1", ":", "]", "seg", "=", "pydub", ".", "AudioSegment", ".", "from_file", "(", "path", ",", "ext", ")", "return", "AudioSegment", "(", "seg", ",", "path", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
from_numpy_array
Returns an AudioSegment created from the given numpy array. The numpy array must have shape = (num_samples, num_channels). :param nparr: The numpy array to create an AudioSegment from. :returns: An AudioSegment created from the given array.
audiosegment.py
def from_numpy_array(nparr, framerate): """ Returns an AudioSegment created from the given numpy array. The numpy array must have shape = (num_samples, num_channels). :param nparr: The numpy array to create an AudioSegment from. :returns: An AudioSegment created from the given array. """ # interleave the audio across all channels and collapse if nparr.dtype.itemsize not in (1, 2, 4): raise ValueError("Numpy Array must contain 8, 16, or 32 bit values.") if len(nparr.shape) == 1: arrays = [nparr] elif len(nparr.shape) == 2: arrays = [nparr[i,:] for i in range(nparr.shape[0])] else: raise ValueError("Numpy Array must be one or two dimensional. Shape must be: (num_samples, num_channels).") interleaved = np.vstack(arrays).reshape((-1,), order='F') dubseg = pydub.AudioSegment(interleaved.tobytes(), frame_rate=framerate, sample_width=interleaved.dtype.itemsize, channels=len(interleaved.shape) ) return AudioSegment(dubseg, "")
def from_numpy_array(nparr, framerate): """ Returns an AudioSegment created from the given numpy array. The numpy array must have shape = (num_samples, num_channels). :param nparr: The numpy array to create an AudioSegment from. :returns: An AudioSegment created from the given array. """ # interleave the audio across all channels and collapse if nparr.dtype.itemsize not in (1, 2, 4): raise ValueError("Numpy Array must contain 8, 16, or 32 bit values.") if len(nparr.shape) == 1: arrays = [nparr] elif len(nparr.shape) == 2: arrays = [nparr[i,:] for i in range(nparr.shape[0])] else: raise ValueError("Numpy Array must be one or two dimensional. Shape must be: (num_samples, num_channels).") interleaved = np.vstack(arrays).reshape((-1,), order='F') dubseg = pydub.AudioSegment(interleaved.tobytes(), frame_rate=framerate, sample_width=interleaved.dtype.itemsize, channels=len(interleaved.shape) ) return AudioSegment(dubseg, "")
[ "Returns", "an", "AudioSegment", "created", "from", "the", "given", "numpy", "array", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L1116-L1140
[ "def", "from_numpy_array", "(", "nparr", ",", "framerate", ")", ":", "# interleave the audio across all channels and collapse", "if", "nparr", ".", "dtype", ".", "itemsize", "not", "in", "(", "1", ",", "2", ",", "4", ")", ":", "raise", "ValueError", "(", "\"Numpy Array must contain 8, 16, or 32 bit values.\"", ")", "if", "len", "(", "nparr", ".", "shape", ")", "==", "1", ":", "arrays", "=", "[", "nparr", "]", "elif", "len", "(", "nparr", ".", "shape", ")", "==", "2", ":", "arrays", "=", "[", "nparr", "[", "i", ",", ":", "]", "for", "i", "in", "range", "(", "nparr", ".", "shape", "[", "0", "]", ")", "]", "else", ":", "raise", "ValueError", "(", "\"Numpy Array must be one or two dimensional. Shape must be: (num_samples, num_channels).\"", ")", "interleaved", "=", "np", ".", "vstack", "(", "arrays", ")", ".", "reshape", "(", "(", "-", "1", ",", ")", ",", "order", "=", "'F'", ")", "dubseg", "=", "pydub", ".", "AudioSegment", "(", "interleaved", ".", "tobytes", "(", ")", ",", "frame_rate", "=", "framerate", ",", "sample_width", "=", "interleaved", ".", "dtype", ".", "itemsize", ",", "channels", "=", "len", "(", "interleaved", ".", "shape", ")", ")", "return", "AudioSegment", "(", "dubseg", ",", "\"\"", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
silent
Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: AudioSegment object filled with pure digital silence.
audiosegment.py
def silent(duration=1000, frame_rate=11025): """ Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: AudioSegment object filled with pure digital silence. """ seg = pydub.AudioSegment.silent(duration=duration, frame_rate=frame_rate) return AudioSegment(seg, "")
def silent(duration=1000, frame_rate=11025): """ Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: AudioSegment object filled with pure digital silence. """ seg = pydub.AudioSegment.silent(duration=duration, frame_rate=frame_rate) return AudioSegment(seg, "")
[ "Creates", "an", "AudioSegment", "object", "of", "the", "specified", "duration", "/", "frame_rate", "filled", "with", "digital", "silence", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L1142-L1151
[ "def", "silent", "(", "duration", "=", "1000", ",", "frame_rate", "=", "11025", ")", ":", "seg", "=", "pydub", ".", "AudioSegment", ".", "silent", "(", "duration", "=", "duration", ",", "frame_rate", "=", "frame_rate", ")", "return", "AudioSegment", "(", "seg", ",", "\"\"", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.spl
Sound Pressure Level - defined as 20 * log10(p/p0), where p is the RMS of the sound wave in Pascals and p0 is 20 micro Pascals. Since we would need to know calibration information about the microphone used to record the sound in order to transform the PCM values of this audiosegment into Pascals, we can't really give an accurate SPL measurement. However, we can give a reasonable guess that can certainly be used to compare two sounds taken from the same microphone set up. Be wary about using this to compare sounds taken under different recording conditions however, except as a simple approximation. Returns a scalar float representing the dB SPL of this audiosegment.
audiosegment.py
def spl(self): """ Sound Pressure Level - defined as 20 * log10(p/p0), where p is the RMS of the sound wave in Pascals and p0 is 20 micro Pascals. Since we would need to know calibration information about the microphone used to record the sound in order to transform the PCM values of this audiosegment into Pascals, we can't really give an accurate SPL measurement. However, we can give a reasonable guess that can certainly be used to compare two sounds taken from the same microphone set up. Be wary about using this to compare sounds taken under different recording conditions however, except as a simple approximation. Returns a scalar float representing the dB SPL of this audiosegment. """ arr = self.to_numpy_array() if len(arr) == 0: return 0.0 else: rms = self.rms ratio = rms / P_REF_PCM return 20.0 * np.log10(ratio + 1E-9)
def spl(self): """ Sound Pressure Level - defined as 20 * log10(p/p0), where p is the RMS of the sound wave in Pascals and p0 is 20 micro Pascals. Since we would need to know calibration information about the microphone used to record the sound in order to transform the PCM values of this audiosegment into Pascals, we can't really give an accurate SPL measurement. However, we can give a reasonable guess that can certainly be used to compare two sounds taken from the same microphone set up. Be wary about using this to compare sounds taken under different recording conditions however, except as a simple approximation. Returns a scalar float representing the dB SPL of this audiosegment. """ arr = self.to_numpy_array() if len(arr) == 0: return 0.0 else: rms = self.rms ratio = rms / P_REF_PCM return 20.0 * np.log10(ratio + 1E-9)
[ "Sound", "Pressure", "Level", "-", "defined", "as", "20", "*", "log10", "(", "p", "/", "p0", ")", "where", "p", "is", "the", "RMS", "of", "the", "sound", "wave", "in", "Pascals", "and", "p0", "is", "20", "micro", "Pascals", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L130-L155
[ "def", "spl", "(", "self", ")", ":", "arr", "=", "self", ".", "to_numpy_array", "(", ")", "if", "len", "(", "arr", ")", "==", "0", ":", "return", "0.0", "else", ":", "rms", "=", "self", ".", "rms", "ratio", "=", "rms", "/", "P_REF_PCM", "return", "20.0", "*", "np", ".", "log10", "(", "ratio", "+", "1E-9", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.filter_bank
Returns a numpy array of shape (nfilters, nsamples), where each row of data is the result of bandpass filtering the audiosegment around a particular frequency. The frequencies are spaced from `lower_bound_hz` to `upper_bound_hz` and are returned with the np array. The particular spacing of the frequencies depends on `mode`, which can be either: 'linear', 'mel', or 'log'. .. note:: This method is an approximation of a gammatone filterbank until I get around to writing an actual gammatone filterbank function. .. code-block:: python # Example usage import audiosegment import matplotlib.pyplot as plt import numpy as np def visualize(spect, frequencies, title=""): # Visualize the result of calling seg.filter_bank() for any number of filters i = 0 for freq, (index, row) in zip(frequencies[::-1], enumerate(spect[::-1, :])): plt.subplot(spect.shape[0], 1, index + 1) if i == 0: plt.title(title) i += 1 plt.ylabel("{0:.0f}".format(freq)) plt.plot(row) plt.show() seg = audiosegment.from_file("some_audio.wav").resample(sample_rate_Hz=24000, sample_width=2, channels=1) spec, frequencies = seg.filter_bank(nfilters=5) visualize(spec, frequencies) .. image:: images/filter_bank.png :param lower_bound_hz: The lower bound of the frequencies to use in the bandpass filters. :param upper_bound_hz: The upper bound of the frequencies to use in the bandpass filters. :param nfilters: The number of filters to apply. This will determine which frequencies are used as well, as they are interpolated between `lower_bound_hz` and `upper_bound_hz` based on `mode`. :param mode: The way the frequencies are spaced. Options are: `linear`, in which case the frequencies are linearly interpolated between `lower_bound_hz` and `upper_bound_hz`, `mel`, in which case the mel frequencies are used, or `log`, in which case they are log-10 spaced. :returns: A numpy array of the form (nfilters, nsamples), where each row is the audiosegment, bandpass-filtered around a particular frequency, and the list of frequencies. I.e., returns (spec, freqs).
audiosegment.py
def filter_bank(self, lower_bound_hz=50, upper_bound_hz=8E3, nfilters=128, mode='mel'): """ Returns a numpy array of shape (nfilters, nsamples), where each row of data is the result of bandpass filtering the audiosegment around a particular frequency. The frequencies are spaced from `lower_bound_hz` to `upper_bound_hz` and are returned with the np array. The particular spacing of the frequencies depends on `mode`, which can be either: 'linear', 'mel', or 'log'. .. note:: This method is an approximation of a gammatone filterbank until I get around to writing an actual gammatone filterbank function. .. code-block:: python # Example usage import audiosegment import matplotlib.pyplot as plt import numpy as np def visualize(spect, frequencies, title=""): # Visualize the result of calling seg.filter_bank() for any number of filters i = 0 for freq, (index, row) in zip(frequencies[::-1], enumerate(spect[::-1, :])): plt.subplot(spect.shape[0], 1, index + 1) if i == 0: plt.title(title) i += 1 plt.ylabel("{0:.0f}".format(freq)) plt.plot(row) plt.show() seg = audiosegment.from_file("some_audio.wav").resample(sample_rate_Hz=24000, sample_width=2, channels=1) spec, frequencies = seg.filter_bank(nfilters=5) visualize(spec, frequencies) .. image:: images/filter_bank.png :param lower_bound_hz: The lower bound of the frequencies to use in the bandpass filters. :param upper_bound_hz: The upper bound of the frequencies to use in the bandpass filters. :param nfilters: The number of filters to apply. This will determine which frequencies are used as well, as they are interpolated between `lower_bound_hz` and `upper_bound_hz` based on `mode`. :param mode: The way the frequencies are spaced. Options are: `linear`, in which case the frequencies are linearly interpolated between `lower_bound_hz` and `upper_bound_hz`, `mel`, in which case the mel frequencies are used, or `log`, in which case they are log-10 spaced. :returns: A numpy array of the form (nfilters, nsamples), where each row is the audiosegment, bandpass-filtered around a particular frequency, and the list of frequencies. I.e., returns (spec, freqs). """ # Logspace to get all the frequency channels we are after data = self.to_numpy_array() if mode.lower() == 'mel': frequencies = librosa.core.mel_frequencies(n_mels=nfilters, fmin=lower_bound_hz, fmax=upper_bound_hz) elif mode.lower() == 'linear': frequencies = np.linspace(lower_bound_hz, upper_bound_hz, num=nfilters, endpoint=True) elif mode.lower() == 'log': start = np.log10(lower_bound_hz) stop = np.log10(upper_bound_hz) frequencies = np.logspace(start, stop, num=nfilters, endpoint=True, base=10.0) else: raise ValueError("'mode' must be one of: (mel, linear, or log), but was {}".format(mode)) # Do a band-pass filter in each frequency rows = [filters.bandpass_filter(data, freq*0.8, freq*1.2, self.frame_rate) for freq in frequencies] rows = np.array(rows) spect = np.vstack(rows) return spect, frequencies
def filter_bank(self, lower_bound_hz=50, upper_bound_hz=8E3, nfilters=128, mode='mel'): """ Returns a numpy array of shape (nfilters, nsamples), where each row of data is the result of bandpass filtering the audiosegment around a particular frequency. The frequencies are spaced from `lower_bound_hz` to `upper_bound_hz` and are returned with the np array. The particular spacing of the frequencies depends on `mode`, which can be either: 'linear', 'mel', or 'log'. .. note:: This method is an approximation of a gammatone filterbank until I get around to writing an actual gammatone filterbank function. .. code-block:: python # Example usage import audiosegment import matplotlib.pyplot as plt import numpy as np def visualize(spect, frequencies, title=""): # Visualize the result of calling seg.filter_bank() for any number of filters i = 0 for freq, (index, row) in zip(frequencies[::-1], enumerate(spect[::-1, :])): plt.subplot(spect.shape[0], 1, index + 1) if i == 0: plt.title(title) i += 1 plt.ylabel("{0:.0f}".format(freq)) plt.plot(row) plt.show() seg = audiosegment.from_file("some_audio.wav").resample(sample_rate_Hz=24000, sample_width=2, channels=1) spec, frequencies = seg.filter_bank(nfilters=5) visualize(spec, frequencies) .. image:: images/filter_bank.png :param lower_bound_hz: The lower bound of the frequencies to use in the bandpass filters. :param upper_bound_hz: The upper bound of the frequencies to use in the bandpass filters. :param nfilters: The number of filters to apply. This will determine which frequencies are used as well, as they are interpolated between `lower_bound_hz` and `upper_bound_hz` based on `mode`. :param mode: The way the frequencies are spaced. Options are: `linear`, in which case the frequencies are linearly interpolated between `lower_bound_hz` and `upper_bound_hz`, `mel`, in which case the mel frequencies are used, or `log`, in which case they are log-10 spaced. :returns: A numpy array of the form (nfilters, nsamples), where each row is the audiosegment, bandpass-filtered around a particular frequency, and the list of frequencies. I.e., returns (spec, freqs). """ # Logspace to get all the frequency channels we are after data = self.to_numpy_array() if mode.lower() == 'mel': frequencies = librosa.core.mel_frequencies(n_mels=nfilters, fmin=lower_bound_hz, fmax=upper_bound_hz) elif mode.lower() == 'linear': frequencies = np.linspace(lower_bound_hz, upper_bound_hz, num=nfilters, endpoint=True) elif mode.lower() == 'log': start = np.log10(lower_bound_hz) stop = np.log10(upper_bound_hz) frequencies = np.logspace(start, stop, num=nfilters, endpoint=True, base=10.0) else: raise ValueError("'mode' must be one of: (mel, linear, or log), but was {}".format(mode)) # Do a band-pass filter in each frequency rows = [filters.bandpass_filter(data, freq*0.8, freq*1.2, self.frame_rate) for freq in frequencies] rows = np.array(rows) spect = np.vstack(rows) return spect, frequencies
[ "Returns", "a", "numpy", "array", "of", "shape", "(", "nfilters", "nsamples", ")", "where", "each", "row", "of", "data", "is", "the", "result", "of", "bandpass", "filtering", "the", "audiosegment", "around", "a", "particular", "frequency", ".", "The", "frequencies", "are", "spaced", "from", "lower_bound_hz", "to", "upper_bound_hz", "and", "are", "returned", "with", "the", "np", "array", ".", "The", "particular", "spacing", "of", "the", "frequencies", "depends", "on", "mode", "which", "can", "be", "either", ":", "linear", "mel", "or", "log", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L157-L225
[ "def", "filter_bank", "(", "self", ",", "lower_bound_hz", "=", "50", ",", "upper_bound_hz", "=", "8E3", ",", "nfilters", "=", "128", ",", "mode", "=", "'mel'", ")", ":", "# Logspace to get all the frequency channels we are after", "data", "=", "self", ".", "to_numpy_array", "(", ")", "if", "mode", ".", "lower", "(", ")", "==", "'mel'", ":", "frequencies", "=", "librosa", ".", "core", ".", "mel_frequencies", "(", "n_mels", "=", "nfilters", ",", "fmin", "=", "lower_bound_hz", ",", "fmax", "=", "upper_bound_hz", ")", "elif", "mode", ".", "lower", "(", ")", "==", "'linear'", ":", "frequencies", "=", "np", ".", "linspace", "(", "lower_bound_hz", ",", "upper_bound_hz", ",", "num", "=", "nfilters", ",", "endpoint", "=", "True", ")", "elif", "mode", ".", "lower", "(", ")", "==", "'log'", ":", "start", "=", "np", ".", "log10", "(", "lower_bound_hz", ")", "stop", "=", "np", ".", "log10", "(", "upper_bound_hz", ")", "frequencies", "=", "np", ".", "logspace", "(", "start", ",", "stop", ",", "num", "=", "nfilters", ",", "endpoint", "=", "True", ",", "base", "=", "10.0", ")", "else", ":", "raise", "ValueError", "(", "\"'mode' must be one of: (mel, linear, or log), but was {}\"", ".", "format", "(", "mode", ")", ")", "# Do a band-pass filter in each frequency", "rows", "=", "[", "filters", ".", "bandpass_filter", "(", "data", ",", "freq", "*", "0.8", ",", "freq", "*", "1.2", ",", "self", ".", "frame_rate", ")", "for", "freq", "in", "frequencies", "]", "rows", "=", "np", ".", "array", "(", "rows", ")", "spect", "=", "np", ".", "vstack", "(", "rows", ")", "return", "spect", ",", "frequencies" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.auditory_scene_analysis
Algorithm based on paper: Auditory Segmentation Based on Onset and Offset Analysis, by Hu and Wang, 2007. Returns a list of AudioSegments, each of which is all the sound during this AudioSegment's duration from a particular source. That is, if there are several overlapping sounds in this AudioSegment, this method will return one AudioSegment object for each of those sounds. At least, that's the idea. Current version is very much in alpha, and while it shows promise, will require quite a bit more tuning before it can really claim to work. :param debug: If `True` will print out debug outputs along the way. Useful if you want to see why it is taking so long. :param debugplot: If `True` will use Matplotlib to plot the resulting spectrogram masks in Mel frequency scale. :returns: List of AudioSegment objects, each of which is from a particular sound source.
audiosegment.py
def auditory_scene_analysis(self, debug=False, debugplot=False): """ Algorithm based on paper: Auditory Segmentation Based on Onset and Offset Analysis, by Hu and Wang, 2007. Returns a list of AudioSegments, each of which is all the sound during this AudioSegment's duration from a particular source. That is, if there are several overlapping sounds in this AudioSegment, this method will return one AudioSegment object for each of those sounds. At least, that's the idea. Current version is very much in alpha, and while it shows promise, will require quite a bit more tuning before it can really claim to work. :param debug: If `True` will print out debug outputs along the way. Useful if you want to see why it is taking so long. :param debugplot: If `True` will use Matplotlib to plot the resulting spectrogram masks in Mel frequency scale. :returns: List of AudioSegment objects, each of which is from a particular sound source. """ normalized = self.normalize_spl_by_average(db=60) def printd(*args, **kwargs): if debug: print(*args, **kwargs) # Create a spectrogram from a filterbank: [nfreqs, nsamples] printd("Making filter bank. This takes a little bit.") spect, frequencies = normalized.filter_bank(nfilters=128) # TODO: replace with correct number from paper # Half-wave rectify each frequency channel so that each value is 0 or greater - we are looking to get a temporal # envelope in each frequency channel printd("Half-wave rectifying") with warnings.catch_warnings(): # Ignore the annoying Numpy runtime warning for less than warnings.simplefilter("ignore") spect[spect < 0] = 0 # Low-pass filter each frequency channel to remove a bunch of noise - we are only looking for large changes printd("Low pass filtering") low_boundary = 30 order = 6 spect = np.apply_along_axis(filters.lowpass_filter, 1, spect, low_boundary, self.frame_rate, order) # Downsample each frequency printd("Downsampling") downsample_freq_hz = 400 if self.frame_rate > downsample_freq_hz: step = int(round(self.frame_rate / downsample_freq_hz)) spect = spect[:, ::step] # Smoothing - we will smooth across time and frequency to further remove noise. # But we need to do it with several different combinations of kernels to get the best idea of what's going on # Scales are (sc, st), meaning (frequency scale, time scale) scales = [(6, 1/4), (6, 1/14), (1/2, 1/14)] # For each (sc, st) scale, smooth across time using st, then across frequency using sc gaussian = lambda x, mu, sig: np.exp(-np.power(x - mu, 2.0) / (2 * np.power(sig, 2.0))) gaussian_kernel = lambda sig: gaussian(np.linspace(-10, 10, len(frequencies) / 2), 0, sig) spectrograms = [] printd("For each scale...") for sc, st in scales: printd(" -> Scale:", sc, st) printd(" -> Time and frequency smoothing") time_smoothed = np.apply_along_axis(filters.lowpass_filter, 1, spect, 1/st, downsample_freq_hz, 6) freq_smoothed = np.apply_along_axis(np.convolve, 0, time_smoothed, gaussian_kernel(sc), 'same') # Remove especially egregious artifacts printd(" -> Removing egregious filtering artifacts") with warnings.catch_warnings(): warnings.simplefilter("ignore") freq_smoothed[freq_smoothed > 1E3] = 1E3 freq_smoothed[freq_smoothed < -1E3] = -1E3 spectrograms.append(freq_smoothed) # Onset/Offset Detection and Matching segmasks = [] printd("For each scale...") for spect, (sc, st) in zip(spectrograms, scales): printd(" -> Scale:", sc, st) printd(" -> Getting the onsets") # Compute sudden upward changes in spect, these are onsets of events onsets, gradients = asa._compute_peaks_or_valleys_of_first_derivative(spect) # Compute sudden downward changes in spect, these are offsets of events printd(" -> Getting the offsets") offsets, _ = asa._compute_peaks_or_valleys_of_first_derivative(spect, do_peaks=False) # Correlate offsets with onsets so that we have a 1:1 relationship printd(" -> Lining up the onsets and offsets") offsets = asa._correlate_onsets_and_offsets(onsets, offsets, gradients) # Create onset/offset fronts # Do this by connecting onsets across frequency channels if they occur within 20ms of each other printd(" -> Create vertical contours (fronts)") onset_fronts = asa._form_onset_offset_fronts(onsets, sample_rate_hz=downsample_freq_hz, threshold_ms=20) offset_fronts = asa._form_onset_offset_fronts(offsets, sample_rate_hz=downsample_freq_hz, threshold_ms=20) # Break poorly matched onset fronts printd(" -> Breaking onset fronts between poorly matched frequencies") asa._break_poorly_matched_fronts(onset_fronts) printd(" -> Getting segmentation mask") segmentation_mask = asa._match_fronts(onset_fronts, offset_fronts, onsets, offsets, debug=debug) segmasks.append(segmentation_mask) break # TODO: We currently don't bother using the multiscale integration, so we should only do one of the scales # Multiscale Integration, seems to conglomerate too well and take too long #finished_segmentation_mask = asa._integrate_segmentation_masks(segmasks) # TODO: doesn't work well and takes too long. finished_segmentation_mask = segmasks[0] if debugplot: asa.visualize_segmentation_mask(finished_segmentation_mask, spect, frequencies) # Change the segmentation mask's domain to that of the STFT, so we can invert it into a wave form ## Get the times times = np.arange(2 * downsample_freq_hz * len(self) / MS_PER_S) printd("Times vs segmentation_mask's times:", times.shape, finished_segmentation_mask.shape[1]) ## Determine the new times and frequencies nsamples_for_each_fft = 2 * finished_segmentation_mask.shape[0] printd("Converting self into STFT") stft_frequencies, stft_times, stft = signal.stft(self.to_numpy_array(), self.frame_rate, nperseg=nsamples_for_each_fft) printd("STFTs shape:", stft.shape) printd("Frequencies:", stft_frequencies.shape) printd("Times:", stft_times.shape) ## Due to rounding, the STFT frequency may be one more than we want if stft_frequencies.shape[0] > finished_segmentation_mask.shape[0]: stft_frequencies = stft_frequencies[:finished_segmentation_mask.shape[0]] stft = stft[:stft_frequencies.shape[0], :] ## Downsample one into the other's times (if needed) finished_segmentation_mask, times, stft, stft_times = asa._downsample_one_or_the_other(stft, stft_times, finished_segmentation_mask, times) printd("Adjusted STFTs shape:", stft.shape) printd("Adjusted STFTs frequencies:", stft_frequencies.shape) printd("Adjusted STFTs times:", stft_times.shape) printd("Segmentation mask:", finished_segmentation_mask.shape) ## Interpolate to map the data into the new domain printd("Attempting to map mask of shape", finished_segmentation_mask.shape, "into shape", (stft_frequencies.shape[0], stft_times.shape[0])) finished_segmentation_mask = asa._map_segmentation_mask_to_stft_domain(finished_segmentation_mask, times, frequencies, stft_times, stft_frequencies) # Separate the mask into a bunch of single segments printd("Separating masks and throwing out inconsequential ones...") masks = asa._separate_masks(finished_segmentation_mask) printd("N separate masks:", len(masks)) # If we couldn't segment into masks after thresholding, # there wasn't more than a single audio stream # Just return us as the only audio stream if len(masks) == 0: clone = from_numpy_array(self.to_numpy_array(), self.frame_rate) return [clone] # TODO: Group masks that belong together... somehow... # Now multiprocess the rest, since it takes forever and is easily parallelizable try: ncpus = multiprocessing.cpu_count() except NotImplementedError: ncpus = 2 ncpus = len(masks) if len(masks) < ncpus else ncpus chunks = np.array_split(masks, ncpus) assert len(chunks) == ncpus queue = multiprocessing.Queue() printd("Using {} processes to convert {} masks into linear STFT space and then time domain.".format(ncpus, len(masks))) for i in range(ncpus): p = multiprocessing.Process(target=asa._asa_task, args=(queue, chunks[i], stft, self.sample_width, self.frame_rate, nsamples_for_each_fft), daemon=True) p.start() results = [] dones = [] while len(dones) < ncpus: item = queue.get() if type(item) == str and item == "DONE": dones.append(item) else: wav = from_numpy_array(item, self.frame_rate) results.append(wav) return results
def auditory_scene_analysis(self, debug=False, debugplot=False): """ Algorithm based on paper: Auditory Segmentation Based on Onset and Offset Analysis, by Hu and Wang, 2007. Returns a list of AudioSegments, each of which is all the sound during this AudioSegment's duration from a particular source. That is, if there are several overlapping sounds in this AudioSegment, this method will return one AudioSegment object for each of those sounds. At least, that's the idea. Current version is very much in alpha, and while it shows promise, will require quite a bit more tuning before it can really claim to work. :param debug: If `True` will print out debug outputs along the way. Useful if you want to see why it is taking so long. :param debugplot: If `True` will use Matplotlib to plot the resulting spectrogram masks in Mel frequency scale. :returns: List of AudioSegment objects, each of which is from a particular sound source. """ normalized = self.normalize_spl_by_average(db=60) def printd(*args, **kwargs): if debug: print(*args, **kwargs) # Create a spectrogram from a filterbank: [nfreqs, nsamples] printd("Making filter bank. This takes a little bit.") spect, frequencies = normalized.filter_bank(nfilters=128) # TODO: replace with correct number from paper # Half-wave rectify each frequency channel so that each value is 0 or greater - we are looking to get a temporal # envelope in each frequency channel printd("Half-wave rectifying") with warnings.catch_warnings(): # Ignore the annoying Numpy runtime warning for less than warnings.simplefilter("ignore") spect[spect < 0] = 0 # Low-pass filter each frequency channel to remove a bunch of noise - we are only looking for large changes printd("Low pass filtering") low_boundary = 30 order = 6 spect = np.apply_along_axis(filters.lowpass_filter, 1, spect, low_boundary, self.frame_rate, order) # Downsample each frequency printd("Downsampling") downsample_freq_hz = 400 if self.frame_rate > downsample_freq_hz: step = int(round(self.frame_rate / downsample_freq_hz)) spect = spect[:, ::step] # Smoothing - we will smooth across time and frequency to further remove noise. # But we need to do it with several different combinations of kernels to get the best idea of what's going on # Scales are (sc, st), meaning (frequency scale, time scale) scales = [(6, 1/4), (6, 1/14), (1/2, 1/14)] # For each (sc, st) scale, smooth across time using st, then across frequency using sc gaussian = lambda x, mu, sig: np.exp(-np.power(x - mu, 2.0) / (2 * np.power(sig, 2.0))) gaussian_kernel = lambda sig: gaussian(np.linspace(-10, 10, len(frequencies) / 2), 0, sig) spectrograms = [] printd("For each scale...") for sc, st in scales: printd(" -> Scale:", sc, st) printd(" -> Time and frequency smoothing") time_smoothed = np.apply_along_axis(filters.lowpass_filter, 1, spect, 1/st, downsample_freq_hz, 6) freq_smoothed = np.apply_along_axis(np.convolve, 0, time_smoothed, gaussian_kernel(sc), 'same') # Remove especially egregious artifacts printd(" -> Removing egregious filtering artifacts") with warnings.catch_warnings(): warnings.simplefilter("ignore") freq_smoothed[freq_smoothed > 1E3] = 1E3 freq_smoothed[freq_smoothed < -1E3] = -1E3 spectrograms.append(freq_smoothed) # Onset/Offset Detection and Matching segmasks = [] printd("For each scale...") for spect, (sc, st) in zip(spectrograms, scales): printd(" -> Scale:", sc, st) printd(" -> Getting the onsets") # Compute sudden upward changes in spect, these are onsets of events onsets, gradients = asa._compute_peaks_or_valleys_of_first_derivative(spect) # Compute sudden downward changes in spect, these are offsets of events printd(" -> Getting the offsets") offsets, _ = asa._compute_peaks_or_valleys_of_first_derivative(spect, do_peaks=False) # Correlate offsets with onsets so that we have a 1:1 relationship printd(" -> Lining up the onsets and offsets") offsets = asa._correlate_onsets_and_offsets(onsets, offsets, gradients) # Create onset/offset fronts # Do this by connecting onsets across frequency channels if they occur within 20ms of each other printd(" -> Create vertical contours (fronts)") onset_fronts = asa._form_onset_offset_fronts(onsets, sample_rate_hz=downsample_freq_hz, threshold_ms=20) offset_fronts = asa._form_onset_offset_fronts(offsets, sample_rate_hz=downsample_freq_hz, threshold_ms=20) # Break poorly matched onset fronts printd(" -> Breaking onset fronts between poorly matched frequencies") asa._break_poorly_matched_fronts(onset_fronts) printd(" -> Getting segmentation mask") segmentation_mask = asa._match_fronts(onset_fronts, offset_fronts, onsets, offsets, debug=debug) segmasks.append(segmentation_mask) break # TODO: We currently don't bother using the multiscale integration, so we should only do one of the scales # Multiscale Integration, seems to conglomerate too well and take too long #finished_segmentation_mask = asa._integrate_segmentation_masks(segmasks) # TODO: doesn't work well and takes too long. finished_segmentation_mask = segmasks[0] if debugplot: asa.visualize_segmentation_mask(finished_segmentation_mask, spect, frequencies) # Change the segmentation mask's domain to that of the STFT, so we can invert it into a wave form ## Get the times times = np.arange(2 * downsample_freq_hz * len(self) / MS_PER_S) printd("Times vs segmentation_mask's times:", times.shape, finished_segmentation_mask.shape[1]) ## Determine the new times and frequencies nsamples_for_each_fft = 2 * finished_segmentation_mask.shape[0] printd("Converting self into STFT") stft_frequencies, stft_times, stft = signal.stft(self.to_numpy_array(), self.frame_rate, nperseg=nsamples_for_each_fft) printd("STFTs shape:", stft.shape) printd("Frequencies:", stft_frequencies.shape) printd("Times:", stft_times.shape) ## Due to rounding, the STFT frequency may be one more than we want if stft_frequencies.shape[0] > finished_segmentation_mask.shape[0]: stft_frequencies = stft_frequencies[:finished_segmentation_mask.shape[0]] stft = stft[:stft_frequencies.shape[0], :] ## Downsample one into the other's times (if needed) finished_segmentation_mask, times, stft, stft_times = asa._downsample_one_or_the_other(stft, stft_times, finished_segmentation_mask, times) printd("Adjusted STFTs shape:", stft.shape) printd("Adjusted STFTs frequencies:", stft_frequencies.shape) printd("Adjusted STFTs times:", stft_times.shape) printd("Segmentation mask:", finished_segmentation_mask.shape) ## Interpolate to map the data into the new domain printd("Attempting to map mask of shape", finished_segmentation_mask.shape, "into shape", (stft_frequencies.shape[0], stft_times.shape[0])) finished_segmentation_mask = asa._map_segmentation_mask_to_stft_domain(finished_segmentation_mask, times, frequencies, stft_times, stft_frequencies) # Separate the mask into a bunch of single segments printd("Separating masks and throwing out inconsequential ones...") masks = asa._separate_masks(finished_segmentation_mask) printd("N separate masks:", len(masks)) # If we couldn't segment into masks after thresholding, # there wasn't more than a single audio stream # Just return us as the only audio stream if len(masks) == 0: clone = from_numpy_array(self.to_numpy_array(), self.frame_rate) return [clone] # TODO: Group masks that belong together... somehow... # Now multiprocess the rest, since it takes forever and is easily parallelizable try: ncpus = multiprocessing.cpu_count() except NotImplementedError: ncpus = 2 ncpus = len(masks) if len(masks) < ncpus else ncpus chunks = np.array_split(masks, ncpus) assert len(chunks) == ncpus queue = multiprocessing.Queue() printd("Using {} processes to convert {} masks into linear STFT space and then time domain.".format(ncpus, len(masks))) for i in range(ncpus): p = multiprocessing.Process(target=asa._asa_task, args=(queue, chunks[i], stft, self.sample_width, self.frame_rate, nsamples_for_each_fft), daemon=True) p.start() results = [] dones = [] while len(dones) < ncpus: item = queue.get() if type(item) == str and item == "DONE": dones.append(item) else: wav = from_numpy_array(item, self.frame_rate) results.append(wav) return results
[ "Algorithm", "based", "on", "paper", ":", "Auditory", "Segmentation", "Based", "on", "Onset", "and", "Offset", "Analysis", "by", "Hu", "and", "Wang", "2007", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L227-L407
[ "def", "auditory_scene_analysis", "(", "self", ",", "debug", "=", "False", ",", "debugplot", "=", "False", ")", ":", "normalized", "=", "self", ".", "normalize_spl_by_average", "(", "db", "=", "60", ")", "def", "printd", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "debug", ":", "print", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Create a spectrogram from a filterbank: [nfreqs, nsamples]", "printd", "(", "\"Making filter bank. This takes a little bit.\"", ")", "spect", ",", "frequencies", "=", "normalized", ".", "filter_bank", "(", "nfilters", "=", "128", ")", "# TODO: replace with correct number from paper", "# Half-wave rectify each frequency channel so that each value is 0 or greater - we are looking to get a temporal", "# envelope in each frequency channel", "printd", "(", "\"Half-wave rectifying\"", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "# Ignore the annoying Numpy runtime warning for less than", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "spect", "[", "spect", "<", "0", "]", "=", "0", "# Low-pass filter each frequency channel to remove a bunch of noise - we are only looking for large changes", "printd", "(", "\"Low pass filtering\"", ")", "low_boundary", "=", "30", "order", "=", "6", "spect", "=", "np", ".", "apply_along_axis", "(", "filters", ".", "lowpass_filter", ",", "1", ",", "spect", ",", "low_boundary", ",", "self", ".", "frame_rate", ",", "order", ")", "# Downsample each frequency", "printd", "(", "\"Downsampling\"", ")", "downsample_freq_hz", "=", "400", "if", "self", ".", "frame_rate", ">", "downsample_freq_hz", ":", "step", "=", "int", "(", "round", "(", "self", ".", "frame_rate", "/", "downsample_freq_hz", ")", ")", "spect", "=", "spect", "[", ":", ",", ":", ":", "step", "]", "# Smoothing - we will smooth across time and frequency to further remove noise.", "# But we need to do it with several different combinations of kernels to get the best idea of what's going on", "# Scales are (sc, st), meaning (frequency scale, time scale)", "scales", "=", "[", "(", "6", ",", "1", "/", "4", ")", ",", "(", "6", ",", "1", "/", "14", ")", ",", "(", "1", "/", "2", ",", "1", "/", "14", ")", "]", "# For each (sc, st) scale, smooth across time using st, then across frequency using sc", "gaussian", "=", "lambda", "x", ",", "mu", ",", "sig", ":", "np", ".", "exp", "(", "-", "np", ".", "power", "(", "x", "-", "mu", ",", "2.0", ")", "/", "(", "2", "*", "np", ".", "power", "(", "sig", ",", "2.0", ")", ")", ")", "gaussian_kernel", "=", "lambda", "sig", ":", "gaussian", "(", "np", ".", "linspace", "(", "-", "10", ",", "10", ",", "len", "(", "frequencies", ")", "/", "2", ")", ",", "0", ",", "sig", ")", "spectrograms", "=", "[", "]", "printd", "(", "\"For each scale...\"", ")", "for", "sc", ",", "st", "in", "scales", ":", "printd", "(", "\" -> Scale:\"", ",", "sc", ",", "st", ")", "printd", "(", "\" -> Time and frequency smoothing\"", ")", "time_smoothed", "=", "np", ".", "apply_along_axis", "(", "filters", ".", "lowpass_filter", ",", "1", ",", "spect", ",", "1", "/", "st", ",", "downsample_freq_hz", ",", "6", ")", "freq_smoothed", "=", "np", ".", "apply_along_axis", "(", "np", ".", "convolve", ",", "0", ",", "time_smoothed", ",", "gaussian_kernel", "(", "sc", ")", ",", "'same'", ")", "# Remove especially egregious artifacts", "printd", "(", "\" -> Removing egregious filtering artifacts\"", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "freq_smoothed", "[", "freq_smoothed", ">", "1E3", "]", "=", "1E3", "freq_smoothed", "[", "freq_smoothed", "<", "-", "1E3", "]", "=", "-", "1E3", "spectrograms", ".", "append", "(", "freq_smoothed", ")", "# Onset/Offset Detection and Matching", "segmasks", "=", "[", "]", "printd", "(", "\"For each scale...\"", ")", "for", "spect", ",", "(", "sc", ",", "st", ")", "in", "zip", "(", "spectrograms", ",", "scales", ")", ":", "printd", "(", "\" -> Scale:\"", ",", "sc", ",", "st", ")", "printd", "(", "\" -> Getting the onsets\"", ")", "# Compute sudden upward changes in spect, these are onsets of events", "onsets", ",", "gradients", "=", "asa", ".", "_compute_peaks_or_valleys_of_first_derivative", "(", "spect", ")", "# Compute sudden downward changes in spect, these are offsets of events", "printd", "(", "\" -> Getting the offsets\"", ")", "offsets", ",", "_", "=", "asa", ".", "_compute_peaks_or_valleys_of_first_derivative", "(", "spect", ",", "do_peaks", "=", "False", ")", "# Correlate offsets with onsets so that we have a 1:1 relationship", "printd", "(", "\" -> Lining up the onsets and offsets\"", ")", "offsets", "=", "asa", ".", "_correlate_onsets_and_offsets", "(", "onsets", ",", "offsets", ",", "gradients", ")", "# Create onset/offset fronts", "# Do this by connecting onsets across frequency channels if they occur within 20ms of each other", "printd", "(", "\" -> Create vertical contours (fronts)\"", ")", "onset_fronts", "=", "asa", ".", "_form_onset_offset_fronts", "(", "onsets", ",", "sample_rate_hz", "=", "downsample_freq_hz", ",", "threshold_ms", "=", "20", ")", "offset_fronts", "=", "asa", ".", "_form_onset_offset_fronts", "(", "offsets", ",", "sample_rate_hz", "=", "downsample_freq_hz", ",", "threshold_ms", "=", "20", ")", "# Break poorly matched onset fronts", "printd", "(", "\" -> Breaking onset fronts between poorly matched frequencies\"", ")", "asa", ".", "_break_poorly_matched_fronts", "(", "onset_fronts", ")", "printd", "(", "\" -> Getting segmentation mask\"", ")", "segmentation_mask", "=", "asa", ".", "_match_fronts", "(", "onset_fronts", ",", "offset_fronts", ",", "onsets", ",", "offsets", ",", "debug", "=", "debug", ")", "segmasks", ".", "append", "(", "segmentation_mask", ")", "break", "# TODO: We currently don't bother using the multiscale integration, so we should only do one of the scales", "# Multiscale Integration, seems to conglomerate too well and take too long", "#finished_segmentation_mask = asa._integrate_segmentation_masks(segmasks) # TODO: doesn't work well and takes too long.", "finished_segmentation_mask", "=", "segmasks", "[", "0", "]", "if", "debugplot", ":", "asa", ".", "visualize_segmentation_mask", "(", "finished_segmentation_mask", ",", "spect", ",", "frequencies", ")", "# Change the segmentation mask's domain to that of the STFT, so we can invert it into a wave form", "## Get the times", "times", "=", "np", ".", "arange", "(", "2", "*", "downsample_freq_hz", "*", "len", "(", "self", ")", "/", "MS_PER_S", ")", "printd", "(", "\"Times vs segmentation_mask's times:\"", ",", "times", ".", "shape", ",", "finished_segmentation_mask", ".", "shape", "[", "1", "]", ")", "## Determine the new times and frequencies", "nsamples_for_each_fft", "=", "2", "*", "finished_segmentation_mask", ".", "shape", "[", "0", "]", "printd", "(", "\"Converting self into STFT\"", ")", "stft_frequencies", ",", "stft_times", ",", "stft", "=", "signal", ".", "stft", "(", "self", ".", "to_numpy_array", "(", ")", ",", "self", ".", "frame_rate", ",", "nperseg", "=", "nsamples_for_each_fft", ")", "printd", "(", "\"STFTs shape:\"", ",", "stft", ".", "shape", ")", "printd", "(", "\"Frequencies:\"", ",", "stft_frequencies", ".", "shape", ")", "printd", "(", "\"Times:\"", ",", "stft_times", ".", "shape", ")", "## Due to rounding, the STFT frequency may be one more than we want", "if", "stft_frequencies", ".", "shape", "[", "0", "]", ">", "finished_segmentation_mask", ".", "shape", "[", "0", "]", ":", "stft_frequencies", "=", "stft_frequencies", "[", ":", "finished_segmentation_mask", ".", "shape", "[", "0", "]", "]", "stft", "=", "stft", "[", ":", "stft_frequencies", ".", "shape", "[", "0", "]", ",", ":", "]", "## Downsample one into the other's times (if needed)", "finished_segmentation_mask", ",", "times", ",", "stft", ",", "stft_times", "=", "asa", ".", "_downsample_one_or_the_other", "(", "stft", ",", "stft_times", ",", "finished_segmentation_mask", ",", "times", ")", "printd", "(", "\"Adjusted STFTs shape:\"", ",", "stft", ".", "shape", ")", "printd", "(", "\"Adjusted STFTs frequencies:\"", ",", "stft_frequencies", ".", "shape", ")", "printd", "(", "\"Adjusted STFTs times:\"", ",", "stft_times", ".", "shape", ")", "printd", "(", "\"Segmentation mask:\"", ",", "finished_segmentation_mask", ".", "shape", ")", "## Interpolate to map the data into the new domain", "printd", "(", "\"Attempting to map mask of shape\"", ",", "finished_segmentation_mask", ".", "shape", ",", "\"into shape\"", ",", "(", "stft_frequencies", ".", "shape", "[", "0", "]", ",", "stft_times", ".", "shape", "[", "0", "]", ")", ")", "finished_segmentation_mask", "=", "asa", ".", "_map_segmentation_mask_to_stft_domain", "(", "finished_segmentation_mask", ",", "times", ",", "frequencies", ",", "stft_times", ",", "stft_frequencies", ")", "# Separate the mask into a bunch of single segments", "printd", "(", "\"Separating masks and throwing out inconsequential ones...\"", ")", "masks", "=", "asa", ".", "_separate_masks", "(", "finished_segmentation_mask", ")", "printd", "(", "\"N separate masks:\"", ",", "len", "(", "masks", ")", ")", "# If we couldn't segment into masks after thresholding,", "# there wasn't more than a single audio stream", "# Just return us as the only audio stream", "if", "len", "(", "masks", ")", "==", "0", ":", "clone", "=", "from_numpy_array", "(", "self", ".", "to_numpy_array", "(", ")", ",", "self", ".", "frame_rate", ")", "return", "[", "clone", "]", "# TODO: Group masks that belong together... somehow...", "# Now multiprocess the rest, since it takes forever and is easily parallelizable", "try", ":", "ncpus", "=", "multiprocessing", ".", "cpu_count", "(", ")", "except", "NotImplementedError", ":", "ncpus", "=", "2", "ncpus", "=", "len", "(", "masks", ")", "if", "len", "(", "masks", ")", "<", "ncpus", "else", "ncpus", "chunks", "=", "np", ".", "array_split", "(", "masks", ",", "ncpus", ")", "assert", "len", "(", "chunks", ")", "==", "ncpus", "queue", "=", "multiprocessing", ".", "Queue", "(", ")", "printd", "(", "\"Using {} processes to convert {} masks into linear STFT space and then time domain.\"", ".", "format", "(", "ncpus", ",", "len", "(", "masks", ")", ")", ")", "for", "i", "in", "range", "(", "ncpus", ")", ":", "p", "=", "multiprocessing", ".", "Process", "(", "target", "=", "asa", ".", "_asa_task", ",", "args", "=", "(", "queue", ",", "chunks", "[", "i", "]", ",", "stft", ",", "self", ".", "sample_width", ",", "self", ".", "frame_rate", ",", "nsamples_for_each_fft", ")", ",", "daemon", "=", "True", ")", "p", ".", "start", "(", ")", "results", "=", "[", "]", "dones", "=", "[", "]", "while", "len", "(", "dones", ")", "<", "ncpus", ":", "item", "=", "queue", ".", "get", "(", ")", "if", "type", "(", "item", ")", "==", "str", "and", "item", "==", "\"DONE\"", ":", "dones", ".", "append", "(", "item", ")", "else", ":", "wav", "=", "from_numpy_array", "(", "item", ",", "self", ".", "frame_rate", ")", "results", ".", "append", "(", "wav", ")", "return", "results" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.detect_voice
Returns self as a list of tuples: [('v', voiced segment), ('u', unvoiced segment), (etc.)] The overall order of the AudioSegment is preserved. :param prob_detect_voice: The raw probability that any random 20ms window of the audio file contains voice. :returns: The described list.
audiosegment.py
def detect_voice(self, prob_detect_voice=0.5): """ Returns self as a list of tuples: [('v', voiced segment), ('u', unvoiced segment), (etc.)] The overall order of the AudioSegment is preserved. :param prob_detect_voice: The raw probability that any random 20ms window of the audio file contains voice. :returns: The described list. """ assert self.frame_rate in (48000, 32000, 16000, 8000), "Try resampling to one of the allowed frame rates." assert self.sample_width == 2, "Try resampling to 16 bit." assert self.channels == 1, "Try resampling to one channel." class model_class: def __init__(self, aggressiveness): self.v = webrtcvad.Vad(int(aggressiveness)) def predict(self, vector): if self.v.is_speech(vector.raw_data, vector.frame_rate): return 1 else: return 0 model = model_class(aggressiveness=2) pyesno = 0.3 # Probability of the next 20 ms being unvoiced given that this 20 ms was voiced pnoyes = 0.2 # Probability of the next 20 ms being voiced given that this 20 ms was unvoiced p_realyes_outputyes = 0.4 # WebRTCVAD has a very high FP rate - just because it says yes, doesn't mean much p_realyes_outputno = 0.05 # If it says no, we can be very certain that it really is a no p_yes_raw = prob_detect_voice filtered = self.detect_event(model=model, ms_per_input=20, transition_matrix=(pyesno, pnoyes), model_stats=(p_realyes_outputyes, p_realyes_outputno), event_length_s=0.25, prob_raw_yes=p_yes_raw) ret = [] for tup in filtered: t = ('v', tup[1]) if tup[0] == 'y' else ('u', tup[1]) ret.append(t) return ret
def detect_voice(self, prob_detect_voice=0.5): """ Returns self as a list of tuples: [('v', voiced segment), ('u', unvoiced segment), (etc.)] The overall order of the AudioSegment is preserved. :param prob_detect_voice: The raw probability that any random 20ms window of the audio file contains voice. :returns: The described list. """ assert self.frame_rate in (48000, 32000, 16000, 8000), "Try resampling to one of the allowed frame rates." assert self.sample_width == 2, "Try resampling to 16 bit." assert self.channels == 1, "Try resampling to one channel." class model_class: def __init__(self, aggressiveness): self.v = webrtcvad.Vad(int(aggressiveness)) def predict(self, vector): if self.v.is_speech(vector.raw_data, vector.frame_rate): return 1 else: return 0 model = model_class(aggressiveness=2) pyesno = 0.3 # Probability of the next 20 ms being unvoiced given that this 20 ms was voiced pnoyes = 0.2 # Probability of the next 20 ms being voiced given that this 20 ms was unvoiced p_realyes_outputyes = 0.4 # WebRTCVAD has a very high FP rate - just because it says yes, doesn't mean much p_realyes_outputno = 0.05 # If it says no, we can be very certain that it really is a no p_yes_raw = prob_detect_voice filtered = self.detect_event(model=model, ms_per_input=20, transition_matrix=(pyesno, pnoyes), model_stats=(p_realyes_outputyes, p_realyes_outputno), event_length_s=0.25, prob_raw_yes=p_yes_raw) ret = [] for tup in filtered: t = ('v', tup[1]) if tup[0] == 'y' else ('u', tup[1]) ret.append(t) return ret
[ "Returns", "self", "as", "a", "list", "of", "tuples", ":", "[", "(", "v", "voiced", "segment", ")", "(", "u", "unvoiced", "segment", ")", "(", "etc", ".", ")", "]" ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L409-L450
[ "def", "detect_voice", "(", "self", ",", "prob_detect_voice", "=", "0.5", ")", ":", "assert", "self", ".", "frame_rate", "in", "(", "48000", ",", "32000", ",", "16000", ",", "8000", ")", ",", "\"Try resampling to one of the allowed frame rates.\"", "assert", "self", ".", "sample_width", "==", "2", ",", "\"Try resampling to 16 bit.\"", "assert", "self", ".", "channels", "==", "1", ",", "\"Try resampling to one channel.\"", "class", "model_class", ":", "def", "__init__", "(", "self", ",", "aggressiveness", ")", ":", "self", ".", "v", "=", "webrtcvad", ".", "Vad", "(", "int", "(", "aggressiveness", ")", ")", "def", "predict", "(", "self", ",", "vector", ")", ":", "if", "self", ".", "v", ".", "is_speech", "(", "vector", ".", "raw_data", ",", "vector", ".", "frame_rate", ")", ":", "return", "1", "else", ":", "return", "0", "model", "=", "model_class", "(", "aggressiveness", "=", "2", ")", "pyesno", "=", "0.3", "# Probability of the next 20 ms being unvoiced given that this 20 ms was voiced", "pnoyes", "=", "0.2", "# Probability of the next 20 ms being voiced given that this 20 ms was unvoiced", "p_realyes_outputyes", "=", "0.4", "# WebRTCVAD has a very high FP rate - just because it says yes, doesn't mean much", "p_realyes_outputno", "=", "0.05", "# If it says no, we can be very certain that it really is a no", "p_yes_raw", "=", "prob_detect_voice", "filtered", "=", "self", ".", "detect_event", "(", "model", "=", "model", ",", "ms_per_input", "=", "20", ",", "transition_matrix", "=", "(", "pyesno", ",", "pnoyes", ")", ",", "model_stats", "=", "(", "p_realyes_outputyes", ",", "p_realyes_outputno", ")", ",", "event_length_s", "=", "0.25", ",", "prob_raw_yes", "=", "p_yes_raw", ")", "ret", "=", "[", "]", "for", "tup", "in", "filtered", ":", "t", "=", "(", "'v'", ",", "tup", "[", "1", "]", ")", "if", "tup", "[", "0", "]", "==", "'y'", "else", "(", "'u'", ",", "tup", "[", "1", "]", ")", "ret", ".", "append", "(", "t", ")", "return", "ret" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.dice
Cuts the AudioSegment into `seconds` segments (at most). So for example, if seconds=10, this will return a list of AudioSegments, in order, where each one is at most 10 seconds long. If `zero_pad` is True, the last item AudioSegment object will be zero padded to result in `seconds` seconds. :param seconds: The length of each segment in seconds. Can be either a float/int, in which case `self.duration_seconds` / `seconds` are made, each of `seconds` length, or a list-like can be given, in which case the given list must sum to `self.duration_seconds` and each segment is specified by the list - e.g. the 9th AudioSegment in the returned list will be `seconds[8]` seconds long. :param zero_pad: Whether to zero_pad the final segment if necessary. Ignored if `seconds` is a list-like. :returns: A list of AudioSegments, each of which is the appropriate number of seconds long. :raises: ValueError if a list-like is given for `seconds` and the list's durations do not sum to `self.duration_seconds`.
audiosegment.py
def dice(self, seconds, zero_pad=False): """ Cuts the AudioSegment into `seconds` segments (at most). So for example, if seconds=10, this will return a list of AudioSegments, in order, where each one is at most 10 seconds long. If `zero_pad` is True, the last item AudioSegment object will be zero padded to result in `seconds` seconds. :param seconds: The length of each segment in seconds. Can be either a float/int, in which case `self.duration_seconds` / `seconds` are made, each of `seconds` length, or a list-like can be given, in which case the given list must sum to `self.duration_seconds` and each segment is specified by the list - e.g. the 9th AudioSegment in the returned list will be `seconds[8]` seconds long. :param zero_pad: Whether to zero_pad the final segment if necessary. Ignored if `seconds` is a list-like. :returns: A list of AudioSegments, each of which is the appropriate number of seconds long. :raises: ValueError if a list-like is given for `seconds` and the list's durations do not sum to `self.duration_seconds`. """ try: total_s = sum(seconds) if not (self.duration_seconds <= total_s + 1 and self.duration_seconds >= total_s - 1): raise ValueError("`seconds` does not sum to within one second of the duration of this AudioSegment.\ given total seconds: %s and self.duration_seconds: %s" % (total_s, self.duration_seconds)) starts = [] stops = [] time_ms = 0 for dur in seconds: starts.append(time_ms) time_ms += dur * MS_PER_S stops.append(time_ms) zero_pad = False except TypeError: # `seconds` is not a list starts = range(0, int(round(self.duration_seconds * MS_PER_S)), int(round(seconds * MS_PER_S))) stops = (min(self.duration_seconds * MS_PER_S, start + seconds * MS_PER_S) for start in starts) outs = [self[start:stop] for start, stop in zip(starts, stops)] out_lens = [out.duration_seconds for out in outs] # Check if our last slice is within one ms of expected - if so, we don't need to zero pad if zero_pad and not (out_lens[-1] <= seconds * MS_PER_S + 1 and out_lens[-1] >= seconds * MS_PER_S - 1): num_zeros = self.frame_rate * (seconds * MS_PER_S - out_lens[-1]) outs[-1] = outs[-1].zero_extend(num_samples=num_zeros) return outs
def dice(self, seconds, zero_pad=False): """ Cuts the AudioSegment into `seconds` segments (at most). So for example, if seconds=10, this will return a list of AudioSegments, in order, where each one is at most 10 seconds long. If `zero_pad` is True, the last item AudioSegment object will be zero padded to result in `seconds` seconds. :param seconds: The length of each segment in seconds. Can be either a float/int, in which case `self.duration_seconds` / `seconds` are made, each of `seconds` length, or a list-like can be given, in which case the given list must sum to `self.duration_seconds` and each segment is specified by the list - e.g. the 9th AudioSegment in the returned list will be `seconds[8]` seconds long. :param zero_pad: Whether to zero_pad the final segment if necessary. Ignored if `seconds` is a list-like. :returns: A list of AudioSegments, each of which is the appropriate number of seconds long. :raises: ValueError if a list-like is given for `seconds` and the list's durations do not sum to `self.duration_seconds`. """ try: total_s = sum(seconds) if not (self.duration_seconds <= total_s + 1 and self.duration_seconds >= total_s - 1): raise ValueError("`seconds` does not sum to within one second of the duration of this AudioSegment.\ given total seconds: %s and self.duration_seconds: %s" % (total_s, self.duration_seconds)) starts = [] stops = [] time_ms = 0 for dur in seconds: starts.append(time_ms) time_ms += dur * MS_PER_S stops.append(time_ms) zero_pad = False except TypeError: # `seconds` is not a list starts = range(0, int(round(self.duration_seconds * MS_PER_S)), int(round(seconds * MS_PER_S))) stops = (min(self.duration_seconds * MS_PER_S, start + seconds * MS_PER_S) for start in starts) outs = [self[start:stop] for start, stop in zip(starts, stops)] out_lens = [out.duration_seconds for out in outs] # Check if our last slice is within one ms of expected - if so, we don't need to zero pad if zero_pad and not (out_lens[-1] <= seconds * MS_PER_S + 1 and out_lens[-1] >= seconds * MS_PER_S - 1): num_zeros = self.frame_rate * (seconds * MS_PER_S - out_lens[-1]) outs[-1] = outs[-1].zero_extend(num_samples=num_zeros) return outs
[ "Cuts", "the", "AudioSegment", "into", "seconds", "segments", "(", "at", "most", ")", ".", "So", "for", "example", "if", "seconds", "=", "10", "this", "will", "return", "a", "list", "of", "AudioSegments", "in", "order", "where", "each", "one", "is", "at", "most", "10", "seconds", "long", ".", "If", "zero_pad", "is", "True", "the", "last", "item", "AudioSegment", "object", "will", "be", "zero", "padded", "to", "result", "in", "seconds", "seconds", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L452-L493
[ "def", "dice", "(", "self", ",", "seconds", ",", "zero_pad", "=", "False", ")", ":", "try", ":", "total_s", "=", "sum", "(", "seconds", ")", "if", "not", "(", "self", ".", "duration_seconds", "<=", "total_s", "+", "1", "and", "self", ".", "duration_seconds", ">=", "total_s", "-", "1", ")", ":", "raise", "ValueError", "(", "\"`seconds` does not sum to within one second of the duration of this AudioSegment.\\\n given total seconds: %s and self.duration_seconds: %s\"", "%", "(", "total_s", ",", "self", ".", "duration_seconds", ")", ")", "starts", "=", "[", "]", "stops", "=", "[", "]", "time_ms", "=", "0", "for", "dur", "in", "seconds", ":", "starts", ".", "append", "(", "time_ms", ")", "time_ms", "+=", "dur", "*", "MS_PER_S", "stops", ".", "append", "(", "time_ms", ")", "zero_pad", "=", "False", "except", "TypeError", ":", "# `seconds` is not a list", "starts", "=", "range", "(", "0", ",", "int", "(", "round", "(", "self", ".", "duration_seconds", "*", "MS_PER_S", ")", ")", ",", "int", "(", "round", "(", "seconds", "*", "MS_PER_S", ")", ")", ")", "stops", "=", "(", "min", "(", "self", ".", "duration_seconds", "*", "MS_PER_S", ",", "start", "+", "seconds", "*", "MS_PER_S", ")", "for", "start", "in", "starts", ")", "outs", "=", "[", "self", "[", "start", ":", "stop", "]", "for", "start", ",", "stop", "in", "zip", "(", "starts", ",", "stops", ")", "]", "out_lens", "=", "[", "out", ".", "duration_seconds", "for", "out", "in", "outs", "]", "# Check if our last slice is within one ms of expected - if so, we don't need to zero pad", "if", "zero_pad", "and", "not", "(", "out_lens", "[", "-", "1", "]", "<=", "seconds", "*", "MS_PER_S", "+", "1", "and", "out_lens", "[", "-", "1", "]", ">=", "seconds", "*", "MS_PER_S", "-", "1", ")", ":", "num_zeros", "=", "self", ".", "frame_rate", "*", "(", "seconds", "*", "MS_PER_S", "-", "out_lens", "[", "-", "1", "]", ")", "outs", "[", "-", "1", "]", "=", "outs", "[", "-", "1", "]", ".", "zero_extend", "(", "num_samples", "=", "num_zeros", ")", "return", "outs" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.detect_event
A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.] is returned, where tuples of the form ('n', AudioSegment) are the segments of sound where the event was not detected, while ('y', AudioSegment) tuples were the segments of sound where the event was detected. .. code-block:: python # Example usage import audiosegment import keras import keras.models import numpy as np import sys class Model: def __init__(self, modelpath): self.model = keras.models.load_model(modelpath) def predict(self, seg): _bins, fft_vals = seg.fft() fft_vals = np.abs(fft_vals) / len(fft_vals) predicted_np_form = self.model.predict(np.array([fft_vals]), batch_size=1) prediction_as_int = int(round(predicted_np_form[0][0])) return prediction_as_int modelpath = sys.argv[1] wavpath = sys.argv[2] model = Model(modelpath) seg = audiosegment.from_file(wavpath).resample(sample_rate_Hz=32000, sample_width=2, channels=1) pyes_to_no = 0.3 # The probability of one 30 ms sample being an event, and the next one not pno_to_yes = 0.2 # The probability of one 30 ms sample not being an event, and the next one yes ptrue_pos_rate = 0.8 # The true positive rate (probability of a predicted yes being right) pfalse_neg_rate = 0.3 # The false negative rate (probability of a predicted no being wrong) raw_prob = 0.7 # The raw probability of seeing the event in any random 30 ms slice of this file events = seg.detect_event(model, ms_per_input=30, transition_matrix=[pyes_to_no, pno_to_yes], model_stats=[ptrue_pos_rate, pfalse_neg_rate], event_length_s=0.25, prob_raw_yes=raw_prob) nos = [event[1] for event in events if event[0] == 'n'] yeses = [event[1] for event in events if event[0] == 'y'] if len(nos) > 1: notdetected = nos[0].reduce(nos[1:]) notdetected.export("notdetected.wav", format="WAV") if len(yeses) > 1: detected = yeses[0].reduce(yeses[1:]) detected.export("detected.wav", format="WAV") :param model: The model. The model must have a predict() function which takes an AudioSegment of `ms_per_input` number of ms and which outputs 1 if the audio event is detected in that input, and 0 if not. Make sure to resample the AudioSegment to the right values before calling this function on it. :param ms_per_input: The number of ms of AudioSegment to be fed into the model at a time. If this does not come out even, the last AudioSegment will be zero-padded. :param transition_matrix: An iterable of the form: [p(yes->no), p(no->yes)]. That is, the probability of moving from a 'yes' state to a 'no' state and the probability of vice versa. :param model_stats: An iterable of the form: [p(reality=1|output=1), p(reality=1|output=0)]. That is, the probability of the ground truth really being a 1, given that the model output a 1, and the probability of the ground truth being a 1, given that the model output a 0. :param event_length_s: The typical duration of the event you are looking for in seconds (can be a float). :param start_as_yes: If True, the first `ms_per_input` will be in the 'y' category. Otherwise it will be in the 'n' category. :param prob_raw_yes: The raw probability of finding the event in any given `ms_per_input` vector. :returns: A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.], where over the course of the list, the AudioSegment in tuple 3 picks up where the one in tuple 2 left off. :raises: ValueError if `ms_per_input` is negative or larger than the number of ms in this AudioSegment; if `transition_matrix` or `model_stats` do not have a __len__ attribute or are not length 2; if the values in `transition_matrix` or `model_stats` are not in the closed interval [0.0, 1.0].
audiosegment.py
def detect_event(self, model, ms_per_input, transition_matrix, model_stats, event_length_s, start_as_yes=False, prob_raw_yes=0.5): """ A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.] is returned, where tuples of the form ('n', AudioSegment) are the segments of sound where the event was not detected, while ('y', AudioSegment) tuples were the segments of sound where the event was detected. .. code-block:: python # Example usage import audiosegment import keras import keras.models import numpy as np import sys class Model: def __init__(self, modelpath): self.model = keras.models.load_model(modelpath) def predict(self, seg): _bins, fft_vals = seg.fft() fft_vals = np.abs(fft_vals) / len(fft_vals) predicted_np_form = self.model.predict(np.array([fft_vals]), batch_size=1) prediction_as_int = int(round(predicted_np_form[0][0])) return prediction_as_int modelpath = sys.argv[1] wavpath = sys.argv[2] model = Model(modelpath) seg = audiosegment.from_file(wavpath).resample(sample_rate_Hz=32000, sample_width=2, channels=1) pyes_to_no = 0.3 # The probability of one 30 ms sample being an event, and the next one not pno_to_yes = 0.2 # The probability of one 30 ms sample not being an event, and the next one yes ptrue_pos_rate = 0.8 # The true positive rate (probability of a predicted yes being right) pfalse_neg_rate = 0.3 # The false negative rate (probability of a predicted no being wrong) raw_prob = 0.7 # The raw probability of seeing the event in any random 30 ms slice of this file events = seg.detect_event(model, ms_per_input=30, transition_matrix=[pyes_to_no, pno_to_yes], model_stats=[ptrue_pos_rate, pfalse_neg_rate], event_length_s=0.25, prob_raw_yes=raw_prob) nos = [event[1] for event in events if event[0] == 'n'] yeses = [event[1] for event in events if event[0] == 'y'] if len(nos) > 1: notdetected = nos[0].reduce(nos[1:]) notdetected.export("notdetected.wav", format="WAV") if len(yeses) > 1: detected = yeses[0].reduce(yeses[1:]) detected.export("detected.wav", format="WAV") :param model: The model. The model must have a predict() function which takes an AudioSegment of `ms_per_input` number of ms and which outputs 1 if the audio event is detected in that input, and 0 if not. Make sure to resample the AudioSegment to the right values before calling this function on it. :param ms_per_input: The number of ms of AudioSegment to be fed into the model at a time. If this does not come out even, the last AudioSegment will be zero-padded. :param transition_matrix: An iterable of the form: [p(yes->no), p(no->yes)]. That is, the probability of moving from a 'yes' state to a 'no' state and the probability of vice versa. :param model_stats: An iterable of the form: [p(reality=1|output=1), p(reality=1|output=0)]. That is, the probability of the ground truth really being a 1, given that the model output a 1, and the probability of the ground truth being a 1, given that the model output a 0. :param event_length_s: The typical duration of the event you are looking for in seconds (can be a float). :param start_as_yes: If True, the first `ms_per_input` will be in the 'y' category. Otherwise it will be in the 'n' category. :param prob_raw_yes: The raw probability of finding the event in any given `ms_per_input` vector. :returns: A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.], where over the course of the list, the AudioSegment in tuple 3 picks up where the one in tuple 2 left off. :raises: ValueError if `ms_per_input` is negative or larger than the number of ms in this AudioSegment; if `transition_matrix` or `model_stats` do not have a __len__ attribute or are not length 2; if the values in `transition_matrix` or `model_stats` are not in the closed interval [0.0, 1.0]. """ if ms_per_input < 0 or ms_per_input / MS_PER_S > self.duration_seconds: raise ValueError("ms_per_input cannot be negative and cannot be longer than the duration of the AudioSegment."\ " The given value was " + str(ms_per_input)) elif not hasattr(transition_matrix, "__len__") or len(transition_matrix) != 2: raise ValueError("transition_matrix must be an iterable of length 2.") elif not hasattr(model_stats, "__len__") or len(model_stats) != 2: raise ValueError("model_stats must be an iterable of length 2.") elif any([True for prob in transition_matrix if prob > 1.0 or prob < 0.0]): raise ValueError("Values in transition_matrix are probabilities, and so must be in the range [0.0, 1.0].") elif any([True for prob in model_stats if prob > 1.0 or prob < 0.0]): raise ValueError("Values in model_stats are probabilities, and so must be in the range [0.0, 1.0].") elif prob_raw_yes > 1.0 or prob_raw_yes < 0.0: raise ValueError("`prob_raw_yes` is a probability, and so must be in the range [0.0, 1.0]") # Get the yeses or nos for when the filter is triggered (when the event is on/off) filter_indices = [yes_or_no for yes_or_no in detect._get_filter_indices(self, start_as_yes, prob_raw_yes, ms_per_input, model, transition_matrix, model_stats)] # Run a homogeneity filter over the values to make local regions more self-similar (reduce noise) ret = detect._homogeneity_filter(filter_indices, window_size=int(round(0.25 * MS_PER_S / ms_per_input))) # Group the consecutive ones together ret = detect._group_filter_values(self, ret, ms_per_input) # Take the groups and turn them into AudioSegment objects real_ret = [] for i, (this_yesno, next_timestamp) in enumerate(ret): if i > 0: _next_yesno, timestamp = ret[i - 1] else: timestamp = 0 ms_per_s = 1000 data = self[timestamp * ms_per_s:next_timestamp * ms_per_s].raw_data seg = AudioSegment(pydub.AudioSegment(data=data, sample_width=self.sample_width, frame_rate=self.frame_rate, channels=self.channels), self.name) real_ret.append((this_yesno, seg)) return real_ret
def detect_event(self, model, ms_per_input, transition_matrix, model_stats, event_length_s, start_as_yes=False, prob_raw_yes=0.5): """ A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.] is returned, where tuples of the form ('n', AudioSegment) are the segments of sound where the event was not detected, while ('y', AudioSegment) tuples were the segments of sound where the event was detected. .. code-block:: python # Example usage import audiosegment import keras import keras.models import numpy as np import sys class Model: def __init__(self, modelpath): self.model = keras.models.load_model(modelpath) def predict(self, seg): _bins, fft_vals = seg.fft() fft_vals = np.abs(fft_vals) / len(fft_vals) predicted_np_form = self.model.predict(np.array([fft_vals]), batch_size=1) prediction_as_int = int(round(predicted_np_form[0][0])) return prediction_as_int modelpath = sys.argv[1] wavpath = sys.argv[2] model = Model(modelpath) seg = audiosegment.from_file(wavpath).resample(sample_rate_Hz=32000, sample_width=2, channels=1) pyes_to_no = 0.3 # The probability of one 30 ms sample being an event, and the next one not pno_to_yes = 0.2 # The probability of one 30 ms sample not being an event, and the next one yes ptrue_pos_rate = 0.8 # The true positive rate (probability of a predicted yes being right) pfalse_neg_rate = 0.3 # The false negative rate (probability of a predicted no being wrong) raw_prob = 0.7 # The raw probability of seeing the event in any random 30 ms slice of this file events = seg.detect_event(model, ms_per_input=30, transition_matrix=[pyes_to_no, pno_to_yes], model_stats=[ptrue_pos_rate, pfalse_neg_rate], event_length_s=0.25, prob_raw_yes=raw_prob) nos = [event[1] for event in events if event[0] == 'n'] yeses = [event[1] for event in events if event[0] == 'y'] if len(nos) > 1: notdetected = nos[0].reduce(nos[1:]) notdetected.export("notdetected.wav", format="WAV") if len(yeses) > 1: detected = yeses[0].reduce(yeses[1:]) detected.export("detected.wav", format="WAV") :param model: The model. The model must have a predict() function which takes an AudioSegment of `ms_per_input` number of ms and which outputs 1 if the audio event is detected in that input, and 0 if not. Make sure to resample the AudioSegment to the right values before calling this function on it. :param ms_per_input: The number of ms of AudioSegment to be fed into the model at a time. If this does not come out even, the last AudioSegment will be zero-padded. :param transition_matrix: An iterable of the form: [p(yes->no), p(no->yes)]. That is, the probability of moving from a 'yes' state to a 'no' state and the probability of vice versa. :param model_stats: An iterable of the form: [p(reality=1|output=1), p(reality=1|output=0)]. That is, the probability of the ground truth really being a 1, given that the model output a 1, and the probability of the ground truth being a 1, given that the model output a 0. :param event_length_s: The typical duration of the event you are looking for in seconds (can be a float). :param start_as_yes: If True, the first `ms_per_input` will be in the 'y' category. Otherwise it will be in the 'n' category. :param prob_raw_yes: The raw probability of finding the event in any given `ms_per_input` vector. :returns: A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.], where over the course of the list, the AudioSegment in tuple 3 picks up where the one in tuple 2 left off. :raises: ValueError if `ms_per_input` is negative or larger than the number of ms in this AudioSegment; if `transition_matrix` or `model_stats` do not have a __len__ attribute or are not length 2; if the values in `transition_matrix` or `model_stats` are not in the closed interval [0.0, 1.0]. """ if ms_per_input < 0 or ms_per_input / MS_PER_S > self.duration_seconds: raise ValueError("ms_per_input cannot be negative and cannot be longer than the duration of the AudioSegment."\ " The given value was " + str(ms_per_input)) elif not hasattr(transition_matrix, "__len__") or len(transition_matrix) != 2: raise ValueError("transition_matrix must be an iterable of length 2.") elif not hasattr(model_stats, "__len__") or len(model_stats) != 2: raise ValueError("model_stats must be an iterable of length 2.") elif any([True for prob in transition_matrix if prob > 1.0 or prob < 0.0]): raise ValueError("Values in transition_matrix are probabilities, and so must be in the range [0.0, 1.0].") elif any([True for prob in model_stats if prob > 1.0 or prob < 0.0]): raise ValueError("Values in model_stats are probabilities, and so must be in the range [0.0, 1.0].") elif prob_raw_yes > 1.0 or prob_raw_yes < 0.0: raise ValueError("`prob_raw_yes` is a probability, and so must be in the range [0.0, 1.0]") # Get the yeses or nos for when the filter is triggered (when the event is on/off) filter_indices = [yes_or_no for yes_or_no in detect._get_filter_indices(self, start_as_yes, prob_raw_yes, ms_per_input, model, transition_matrix, model_stats)] # Run a homogeneity filter over the values to make local regions more self-similar (reduce noise) ret = detect._homogeneity_filter(filter_indices, window_size=int(round(0.25 * MS_PER_S / ms_per_input))) # Group the consecutive ones together ret = detect._group_filter_values(self, ret, ms_per_input) # Take the groups and turn them into AudioSegment objects real_ret = [] for i, (this_yesno, next_timestamp) in enumerate(ret): if i > 0: _next_yesno, timestamp = ret[i - 1] else: timestamp = 0 ms_per_s = 1000 data = self[timestamp * ms_per_s:next_timestamp * ms_per_s].raw_data seg = AudioSegment(pydub.AudioSegment(data=data, sample_width=self.sample_width, frame_rate=self.frame_rate, channels=self.channels), self.name) real_ret.append((this_yesno, seg)) return real_ret
[ "A", "list", "of", "tuples", "of", "the", "form", "[", "(", "n", "AudioSegment", ")", "(", "y", "AudioSegment", ")", "etc", ".", "]", "is", "returned", "where", "tuples", "of", "the", "form", "(", "n", "AudioSegment", ")", "are", "the", "segments", "of", "sound", "where", "the", "event", "was", "not", "detected", "while", "(", "y", "AudioSegment", ")", "tuples", "were", "the", "segments", "of", "sound", "where", "the", "event", "was", "detected", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L495-L617
[ "def", "detect_event", "(", "self", ",", "model", ",", "ms_per_input", ",", "transition_matrix", ",", "model_stats", ",", "event_length_s", ",", "start_as_yes", "=", "False", ",", "prob_raw_yes", "=", "0.5", ")", ":", "if", "ms_per_input", "<", "0", "or", "ms_per_input", "/", "MS_PER_S", ">", "self", ".", "duration_seconds", ":", "raise", "ValueError", "(", "\"ms_per_input cannot be negative and cannot be longer than the duration of the AudioSegment.\"", "\" The given value was \"", "+", "str", "(", "ms_per_input", ")", ")", "elif", "not", "hasattr", "(", "transition_matrix", ",", "\"__len__\"", ")", "or", "len", "(", "transition_matrix", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"transition_matrix must be an iterable of length 2.\"", ")", "elif", "not", "hasattr", "(", "model_stats", ",", "\"__len__\"", ")", "or", "len", "(", "model_stats", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"model_stats must be an iterable of length 2.\"", ")", "elif", "any", "(", "[", "True", "for", "prob", "in", "transition_matrix", "if", "prob", ">", "1.0", "or", "prob", "<", "0.0", "]", ")", ":", "raise", "ValueError", "(", "\"Values in transition_matrix are probabilities, and so must be in the range [0.0, 1.0].\"", ")", "elif", "any", "(", "[", "True", "for", "prob", "in", "model_stats", "if", "prob", ">", "1.0", "or", "prob", "<", "0.0", "]", ")", ":", "raise", "ValueError", "(", "\"Values in model_stats are probabilities, and so must be in the range [0.0, 1.0].\"", ")", "elif", "prob_raw_yes", ">", "1.0", "or", "prob_raw_yes", "<", "0.0", ":", "raise", "ValueError", "(", "\"`prob_raw_yes` is a probability, and so must be in the range [0.0, 1.0]\"", ")", "# Get the yeses or nos for when the filter is triggered (when the event is on/off)", "filter_indices", "=", "[", "yes_or_no", "for", "yes_or_no", "in", "detect", ".", "_get_filter_indices", "(", "self", ",", "start_as_yes", ",", "prob_raw_yes", ",", "ms_per_input", ",", "model", ",", "transition_matrix", ",", "model_stats", ")", "]", "# Run a homogeneity filter over the values to make local regions more self-similar (reduce noise)", "ret", "=", "detect", ".", "_homogeneity_filter", "(", "filter_indices", ",", "window_size", "=", "int", "(", "round", "(", "0.25", "*", "MS_PER_S", "/", "ms_per_input", ")", ")", ")", "# Group the consecutive ones together", "ret", "=", "detect", ".", "_group_filter_values", "(", "self", ",", "ret", ",", "ms_per_input", ")", "# Take the groups and turn them into AudioSegment objects", "real_ret", "=", "[", "]", "for", "i", ",", "(", "this_yesno", ",", "next_timestamp", ")", "in", "enumerate", "(", "ret", ")", ":", "if", "i", ">", "0", ":", "_next_yesno", ",", "timestamp", "=", "ret", "[", "i", "-", "1", "]", "else", ":", "timestamp", "=", "0", "ms_per_s", "=", "1000", "data", "=", "self", "[", "timestamp", "*", "ms_per_s", ":", "next_timestamp", "*", "ms_per_s", "]", ".", "raw_data", "seg", "=", "AudioSegment", "(", "pydub", ".", "AudioSegment", "(", "data", "=", "data", ",", "sample_width", "=", "self", ".", "sample_width", ",", "frame_rate", "=", "self", ".", "frame_rate", ",", "channels", "=", "self", ".", "channels", ")", ",", "self", ".", "name", ")", "real_ret", ".", "append", "(", "(", "this_yesno", ",", "seg", ")", ")", "return", "real_ret" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment._execute_sox_cmd
Executes a Sox command in a platform-independent manner. `cmd` must be a format string that includes {inputfile} and {outputfile}.
audiosegment.py
def _execute_sox_cmd(self, cmd, console_output=False): """ Executes a Sox command in a platform-independent manner. `cmd` must be a format string that includes {inputfile} and {outputfile}. """ on_windows = platform.system().lower() == "windows" # On Windows, a temporary file cannot be shared outside the process that creates it # so we need to create a "permanent" file that we will use and delete afterwards def _get_random_tmp_file(): if on_windows: rand_string = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) tmp = self.name + "_" + rand_string WinTempFile = collections.namedtuple("WinTempFile", "name") tmp = WinTempFile(tmp) else: tmp = tempfile.NamedTemporaryFile() return tmp # Get a temp file to put our data and a temp file to store the result tmp = _get_random_tmp_file() othertmp = _get_random_tmp_file() # Store our data in the temp file self.export(tmp.name, format="WAV") # Write the command to sox stdout = stderr = subprocess.PIPE if console_output else subprocess.DEVNULL command = cmd.format(inputfile=tmp.name, outputfile=othertmp.name) res = subprocess.call(command.split(' '), stdout=stdout, stderr=stderr) assert res == 0, "Sox did not work as intended, or perhaps you don't have Sox installed?" # Create a new AudioSegment from the other temp file (where Sox put the result) other = AudioSegment(pydub.AudioSegment.from_wav(othertmp.name), self.name) # Clean up the temp files if on_windows: os.remove(tmp.name) os.remove(othertmp.name) else: tmp.close() othertmp.close() return other
def _execute_sox_cmd(self, cmd, console_output=False): """ Executes a Sox command in a platform-independent manner. `cmd` must be a format string that includes {inputfile} and {outputfile}. """ on_windows = platform.system().lower() == "windows" # On Windows, a temporary file cannot be shared outside the process that creates it # so we need to create a "permanent" file that we will use and delete afterwards def _get_random_tmp_file(): if on_windows: rand_string = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) tmp = self.name + "_" + rand_string WinTempFile = collections.namedtuple("WinTempFile", "name") tmp = WinTempFile(tmp) else: tmp = tempfile.NamedTemporaryFile() return tmp # Get a temp file to put our data and a temp file to store the result tmp = _get_random_tmp_file() othertmp = _get_random_tmp_file() # Store our data in the temp file self.export(tmp.name, format="WAV") # Write the command to sox stdout = stderr = subprocess.PIPE if console_output else subprocess.DEVNULL command = cmd.format(inputfile=tmp.name, outputfile=othertmp.name) res = subprocess.call(command.split(' '), stdout=stdout, stderr=stderr) assert res == 0, "Sox did not work as intended, or perhaps you don't have Sox installed?" # Create a new AudioSegment from the other temp file (where Sox put the result) other = AudioSegment(pydub.AudioSegment.from_wav(othertmp.name), self.name) # Clean up the temp files if on_windows: os.remove(tmp.name) os.remove(othertmp.name) else: tmp.close() othertmp.close() return other
[ "Executes", "a", "Sox", "command", "in", "a", "platform", "-", "independent", "manner", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L619-L663
[ "def", "_execute_sox_cmd", "(", "self", ",", "cmd", ",", "console_output", "=", "False", ")", ":", "on_windows", "=", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "==", "\"windows\"", "# On Windows, a temporary file cannot be shared outside the process that creates it", "# so we need to create a \"permanent\" file that we will use and delete afterwards", "def", "_get_random_tmp_file", "(", ")", ":", "if", "on_windows", ":", "rand_string", "=", "\"\"", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "8", ")", ")", "tmp", "=", "self", ".", "name", "+", "\"_\"", "+", "rand_string", "WinTempFile", "=", "collections", ".", "namedtuple", "(", "\"WinTempFile\"", ",", "\"name\"", ")", "tmp", "=", "WinTempFile", "(", "tmp", ")", "else", ":", "tmp", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "return", "tmp", "# Get a temp file to put our data and a temp file to store the result", "tmp", "=", "_get_random_tmp_file", "(", ")", "othertmp", "=", "_get_random_tmp_file", "(", ")", "# Store our data in the temp file", "self", ".", "export", "(", "tmp", ".", "name", ",", "format", "=", "\"WAV\"", ")", "# Write the command to sox", "stdout", "=", "stderr", "=", "subprocess", ".", "PIPE", "if", "console_output", "else", "subprocess", ".", "DEVNULL", "command", "=", "cmd", ".", "format", "(", "inputfile", "=", "tmp", ".", "name", ",", "outputfile", "=", "othertmp", ".", "name", ")", "res", "=", "subprocess", ".", "call", "(", "command", ".", "split", "(", "' '", ")", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ")", "assert", "res", "==", "0", ",", "\"Sox did not work as intended, or perhaps you don't have Sox installed?\"", "# Create a new AudioSegment from the other temp file (where Sox put the result)", "other", "=", "AudioSegment", "(", "pydub", ".", "AudioSegment", ".", "from_wav", "(", "othertmp", ".", "name", ")", ",", "self", ".", "name", ")", "# Clean up the temp files", "if", "on_windows", ":", "os", ".", "remove", "(", "tmp", ".", "name", ")", "os", ".", "remove", "(", "othertmp", ".", "name", ")", "else", ":", "tmp", ".", "close", "(", ")", "othertmp", ".", "close", "(", ")", "return", "other" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.filter_silence
Returns a copy of this AudioSegment, but whose silence has been removed. .. note:: This method requires that you have the program 'sox' installed. .. warning:: This method uses the program 'sox' to perform the task. While this is very fast for a single function call, the IO may add up for large numbers of AudioSegment objects. :param duration_s: The number of seconds of "silence" that must be present in a row to be stripped. :param threshold_percentage: Silence is defined as any samples whose absolute value is below `threshold_percentage * max(abs(samples in this segment))`. :param console_output: If True, will pipe all sox output to the console. :returns: A copy of this AudioSegment, but whose silence has been removed.
audiosegment.py
def filter_silence(self, duration_s=1, threshold_percentage=1, console_output=False): """ Returns a copy of this AudioSegment, but whose silence has been removed. .. note:: This method requires that you have the program 'sox' installed. .. warning:: This method uses the program 'sox' to perform the task. While this is very fast for a single function call, the IO may add up for large numbers of AudioSegment objects. :param duration_s: The number of seconds of "silence" that must be present in a row to be stripped. :param threshold_percentage: Silence is defined as any samples whose absolute value is below `threshold_percentage * max(abs(samples in this segment))`. :param console_output: If True, will pipe all sox output to the console. :returns: A copy of this AudioSegment, but whose silence has been removed. """ command = "sox {inputfile} -t wav {outputfile} silence -l 1 0.1 "\ + str(threshold_percentage) + "% -1 " + str(float(duration_s)) + " " + str(threshold_percentage) + "%" try: result = self._execute_sox_cmd(command) except pydub.exceptions.CouldntDecodeError: warnings.warn("After silence filtering, the resultant WAV file is corrupted, and so its data cannot be retrieved. Perhaps try a smaller threshold value.", stacklevel=2) # Return a copy of us result = AudioSegment(self.seg, self.name) return result
def filter_silence(self, duration_s=1, threshold_percentage=1, console_output=False): """ Returns a copy of this AudioSegment, but whose silence has been removed. .. note:: This method requires that you have the program 'sox' installed. .. warning:: This method uses the program 'sox' to perform the task. While this is very fast for a single function call, the IO may add up for large numbers of AudioSegment objects. :param duration_s: The number of seconds of "silence" that must be present in a row to be stripped. :param threshold_percentage: Silence is defined as any samples whose absolute value is below `threshold_percentage * max(abs(samples in this segment))`. :param console_output: If True, will pipe all sox output to the console. :returns: A copy of this AudioSegment, but whose silence has been removed. """ command = "sox {inputfile} -t wav {outputfile} silence -l 1 0.1 "\ + str(threshold_percentage) + "% -1 " + str(float(duration_s)) + " " + str(threshold_percentage) + "%" try: result = self._execute_sox_cmd(command) except pydub.exceptions.CouldntDecodeError: warnings.warn("After silence filtering, the resultant WAV file is corrupted, and so its data cannot be retrieved. Perhaps try a smaller threshold value.", stacklevel=2) # Return a copy of us result = AudioSegment(self.seg, self.name) return result
[ "Returns", "a", "copy", "of", "this", "AudioSegment", "but", "whose", "silence", "has", "been", "removed", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L665-L689
[ "def", "filter_silence", "(", "self", ",", "duration_s", "=", "1", ",", "threshold_percentage", "=", "1", ",", "console_output", "=", "False", ")", ":", "command", "=", "\"sox {inputfile} -t wav {outputfile} silence -l 1 0.1 \"", "+", "str", "(", "threshold_percentage", ")", "+", "\"% -1 \"", "+", "str", "(", "float", "(", "duration_s", ")", ")", "+", "\" \"", "+", "str", "(", "threshold_percentage", ")", "+", "\"%\"", "try", ":", "result", "=", "self", ".", "_execute_sox_cmd", "(", "command", ")", "except", "pydub", ".", "exceptions", ".", "CouldntDecodeError", ":", "warnings", ".", "warn", "(", "\"After silence filtering, the resultant WAV file is corrupted, and so its data cannot be retrieved. Perhaps try a smaller threshold value.\"", ",", "stacklevel", "=", "2", ")", "# Return a copy of us", "result", "=", "AudioSegment", "(", "self", ".", "seg", ",", "self", ".", "name", ")", "return", "result" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.fft
Transforms the indicated slice of the AudioSegment into the frequency domain and returns the bins and the values. If neither `start_s` or `start_sample` is specified, the first sample of the slice will be the first sample of the AudioSegment. If neither `duration_s` or `num_samples` is specified, the slice will be from the specified start to the end of the segment. .. code-block:: python # Example for plotting the FFT using this function import matplotlib.pyplot as plt import numpy as np seg = audiosegment.from_file("furelise.wav") # Just take the first 3 seconds hist_bins, hist_vals = seg[1:3000].fft() hist_vals_real_normed = np.abs(hist_vals) / len(hist_vals) plt.plot(hist_bins / 1000, hist_vals_real_normed) plt.xlabel("kHz") plt.ylabel("dB") plt.show() .. image:: images/fft.png :param start_s: The start time in seconds. If this is specified, you cannot specify `start_sample`. :param duration_s: The duration of the slice in seconds. If this is specified, you cannot specify `num_samples`. :param start_sample: The zero-based index of the first sample to include in the slice. If this is specified, you cannot specify `start_s`. :param num_samples: The number of samples to include in the slice. If this is specified, you cannot specify `duration_s`. :param zero_pad: If True and the combination of start and duration result in running off the end of the AudioSegment, the end is zero padded to prevent this. :returns: np.ndarray of frequencies in Hz, np.ndarray of amount of each frequency :raises: ValueError If `start_s` and `start_sample` are both specified and/or if both `duration_s` and `num_samples` are specified.
audiosegment.py
def fft(self, start_s=None, duration_s=None, start_sample=None, num_samples=None, zero_pad=False): """ Transforms the indicated slice of the AudioSegment into the frequency domain and returns the bins and the values. If neither `start_s` or `start_sample` is specified, the first sample of the slice will be the first sample of the AudioSegment. If neither `duration_s` or `num_samples` is specified, the slice will be from the specified start to the end of the segment. .. code-block:: python # Example for plotting the FFT using this function import matplotlib.pyplot as plt import numpy as np seg = audiosegment.from_file("furelise.wav") # Just take the first 3 seconds hist_bins, hist_vals = seg[1:3000].fft() hist_vals_real_normed = np.abs(hist_vals) / len(hist_vals) plt.plot(hist_bins / 1000, hist_vals_real_normed) plt.xlabel("kHz") plt.ylabel("dB") plt.show() .. image:: images/fft.png :param start_s: The start time in seconds. If this is specified, you cannot specify `start_sample`. :param duration_s: The duration of the slice in seconds. If this is specified, you cannot specify `num_samples`. :param start_sample: The zero-based index of the first sample to include in the slice. If this is specified, you cannot specify `start_s`. :param num_samples: The number of samples to include in the slice. If this is specified, you cannot specify `duration_s`. :param zero_pad: If True and the combination of start and duration result in running off the end of the AudioSegment, the end is zero padded to prevent this. :returns: np.ndarray of frequencies in Hz, np.ndarray of amount of each frequency :raises: ValueError If `start_s` and `start_sample` are both specified and/or if both `duration_s` and `num_samples` are specified. """ if start_s is not None and start_sample is not None: raise ValueError("Only one of start_s and start_sample can be specified.") if duration_s is not None and num_samples is not None: raise ValueError("Only one of duration_s and num_samples can be specified.") if start_s is None and start_sample is None: start_sample = 0 if duration_s is None and num_samples is None: num_samples = len(self.get_array_of_samples()) - int(start_sample) if duration_s is not None: num_samples = int(round(duration_s * self.frame_rate)) if start_s is not None: start_sample = int(round(start_s * self.frame_rate)) end_sample = start_sample + num_samples # end_sample is excluded if end_sample > len(self.get_array_of_samples()) and not zero_pad: raise ValueError("The combination of start and duration will run off the end of the AudioSegment object.") elif end_sample > len(self.get_array_of_samples()) and zero_pad: arr = np.array(self.get_array_of_samples()) zeros = np.zeros(end_sample - len(arr)) arr = np.append(arr, zeros) else: arr = np.array(self.get_array_of_samples()) audioslice = np.array(arr[start_sample:end_sample]) fft_result = np.fft.fft(audioslice)[range(int(round(num_samples/2)) + 1)] step_size = self.frame_rate / num_samples bins = np.arange(0, int(round(num_samples/2)) + 1, 1.0) * step_size return bins, fft_result
def fft(self, start_s=None, duration_s=None, start_sample=None, num_samples=None, zero_pad=False): """ Transforms the indicated slice of the AudioSegment into the frequency domain and returns the bins and the values. If neither `start_s` or `start_sample` is specified, the first sample of the slice will be the first sample of the AudioSegment. If neither `duration_s` or `num_samples` is specified, the slice will be from the specified start to the end of the segment. .. code-block:: python # Example for plotting the FFT using this function import matplotlib.pyplot as plt import numpy as np seg = audiosegment.from_file("furelise.wav") # Just take the first 3 seconds hist_bins, hist_vals = seg[1:3000].fft() hist_vals_real_normed = np.abs(hist_vals) / len(hist_vals) plt.plot(hist_bins / 1000, hist_vals_real_normed) plt.xlabel("kHz") plt.ylabel("dB") plt.show() .. image:: images/fft.png :param start_s: The start time in seconds. If this is specified, you cannot specify `start_sample`. :param duration_s: The duration of the slice in seconds. If this is specified, you cannot specify `num_samples`. :param start_sample: The zero-based index of the first sample to include in the slice. If this is specified, you cannot specify `start_s`. :param num_samples: The number of samples to include in the slice. If this is specified, you cannot specify `duration_s`. :param zero_pad: If True and the combination of start and duration result in running off the end of the AudioSegment, the end is zero padded to prevent this. :returns: np.ndarray of frequencies in Hz, np.ndarray of amount of each frequency :raises: ValueError If `start_s` and `start_sample` are both specified and/or if both `duration_s` and `num_samples` are specified. """ if start_s is not None and start_sample is not None: raise ValueError("Only one of start_s and start_sample can be specified.") if duration_s is not None and num_samples is not None: raise ValueError("Only one of duration_s and num_samples can be specified.") if start_s is None and start_sample is None: start_sample = 0 if duration_s is None and num_samples is None: num_samples = len(self.get_array_of_samples()) - int(start_sample) if duration_s is not None: num_samples = int(round(duration_s * self.frame_rate)) if start_s is not None: start_sample = int(round(start_s * self.frame_rate)) end_sample = start_sample + num_samples # end_sample is excluded if end_sample > len(self.get_array_of_samples()) and not zero_pad: raise ValueError("The combination of start and duration will run off the end of the AudioSegment object.") elif end_sample > len(self.get_array_of_samples()) and zero_pad: arr = np.array(self.get_array_of_samples()) zeros = np.zeros(end_sample - len(arr)) arr = np.append(arr, zeros) else: arr = np.array(self.get_array_of_samples()) audioslice = np.array(arr[start_sample:end_sample]) fft_result = np.fft.fft(audioslice)[range(int(round(num_samples/2)) + 1)] step_size = self.frame_rate / num_samples bins = np.arange(0, int(round(num_samples/2)) + 1, 1.0) * step_size return bins, fft_result
[ "Transforms", "the", "indicated", "slice", "of", "the", "AudioSegment", "into", "the", "frequency", "domain", "and", "returns", "the", "bins", "and", "the", "values", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L691-L759
[ "def", "fft", "(", "self", ",", "start_s", "=", "None", ",", "duration_s", "=", "None", ",", "start_sample", "=", "None", ",", "num_samples", "=", "None", ",", "zero_pad", "=", "False", ")", ":", "if", "start_s", "is", "not", "None", "and", "start_sample", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Only one of start_s and start_sample can be specified.\"", ")", "if", "duration_s", "is", "not", "None", "and", "num_samples", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Only one of duration_s and num_samples can be specified.\"", ")", "if", "start_s", "is", "None", "and", "start_sample", "is", "None", ":", "start_sample", "=", "0", "if", "duration_s", "is", "None", "and", "num_samples", "is", "None", ":", "num_samples", "=", "len", "(", "self", ".", "get_array_of_samples", "(", ")", ")", "-", "int", "(", "start_sample", ")", "if", "duration_s", "is", "not", "None", ":", "num_samples", "=", "int", "(", "round", "(", "duration_s", "*", "self", ".", "frame_rate", ")", ")", "if", "start_s", "is", "not", "None", ":", "start_sample", "=", "int", "(", "round", "(", "start_s", "*", "self", ".", "frame_rate", ")", ")", "end_sample", "=", "start_sample", "+", "num_samples", "# end_sample is excluded", "if", "end_sample", ">", "len", "(", "self", ".", "get_array_of_samples", "(", ")", ")", "and", "not", "zero_pad", ":", "raise", "ValueError", "(", "\"The combination of start and duration will run off the end of the AudioSegment object.\"", ")", "elif", "end_sample", ">", "len", "(", "self", ".", "get_array_of_samples", "(", ")", ")", "and", "zero_pad", ":", "arr", "=", "np", ".", "array", "(", "self", ".", "get_array_of_samples", "(", ")", ")", "zeros", "=", "np", ".", "zeros", "(", "end_sample", "-", "len", "(", "arr", ")", ")", "arr", "=", "np", ".", "append", "(", "arr", ",", "zeros", ")", "else", ":", "arr", "=", "np", ".", "array", "(", "self", ".", "get_array_of_samples", "(", ")", ")", "audioslice", "=", "np", ".", "array", "(", "arr", "[", "start_sample", ":", "end_sample", "]", ")", "fft_result", "=", "np", ".", "fft", ".", "fft", "(", "audioslice", ")", "[", "range", "(", "int", "(", "round", "(", "num_samples", "/", "2", ")", ")", "+", "1", ")", "]", "step_size", "=", "self", ".", "frame_rate", "/", "num_samples", "bins", "=", "np", ".", "arange", "(", "0", ",", "int", "(", "round", "(", "num_samples", "/", "2", ")", ")", "+", "1", ",", "1.0", ")", "*", "step_size", "return", "bins", ",", "fft_result" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.generate_frames
Yields self's data in chunks of frame_duration_ms. This function adapted from pywebrtc's example [https://github.com/wiseman/py-webrtcvad/blob/master/example.py]. :param frame_duration_ms: The length of each frame in ms. :param zero_pad: Whether or not to zero pad the end of the AudioSegment object to get all the audio data out as frames. If not, there may be a part at the end of the Segment that is cut off (the part will be <= `frame_duration_ms` in length). :returns: A Frame object with properties 'bytes (the data)', 'timestamp (start time)', and 'duration'.
audiosegment.py
def generate_frames(self, frame_duration_ms, zero_pad=True): """ Yields self's data in chunks of frame_duration_ms. This function adapted from pywebrtc's example [https://github.com/wiseman/py-webrtcvad/blob/master/example.py]. :param frame_duration_ms: The length of each frame in ms. :param zero_pad: Whether or not to zero pad the end of the AudioSegment object to get all the audio data out as frames. If not, there may be a part at the end of the Segment that is cut off (the part will be <= `frame_duration_ms` in length). :returns: A Frame object with properties 'bytes (the data)', 'timestamp (start time)', and 'duration'. """ Frame = collections.namedtuple("Frame", "bytes timestamp duration") # (samples/sec) * (seconds in a frame) * (bytes/sample) bytes_per_frame = int(self.frame_rate * (frame_duration_ms / 1000) * self.sample_width) offset = 0 # where we are so far in self's data (in bytes) timestamp = 0.0 # where we are so far in self (in seconds) # (bytes/frame) * (sample/bytes) * (sec/samples) frame_duration_s = (bytes_per_frame / self.frame_rate) / self.sample_width while offset + bytes_per_frame < len(self.raw_data): yield Frame(self.raw_data[offset:offset + bytes_per_frame], timestamp, frame_duration_s) timestamp += frame_duration_s offset += bytes_per_frame if zero_pad: rest = self.raw_data[offset:] zeros = bytes(bytes_per_frame - len(rest)) yield Frame(rest + zeros, timestamp, frame_duration_s)
def generate_frames(self, frame_duration_ms, zero_pad=True): """ Yields self's data in chunks of frame_duration_ms. This function adapted from pywebrtc's example [https://github.com/wiseman/py-webrtcvad/blob/master/example.py]. :param frame_duration_ms: The length of each frame in ms. :param zero_pad: Whether or not to zero pad the end of the AudioSegment object to get all the audio data out as frames. If not, there may be a part at the end of the Segment that is cut off (the part will be <= `frame_duration_ms` in length). :returns: A Frame object with properties 'bytes (the data)', 'timestamp (start time)', and 'duration'. """ Frame = collections.namedtuple("Frame", "bytes timestamp duration") # (samples/sec) * (seconds in a frame) * (bytes/sample) bytes_per_frame = int(self.frame_rate * (frame_duration_ms / 1000) * self.sample_width) offset = 0 # where we are so far in self's data (in bytes) timestamp = 0.0 # where we are so far in self (in seconds) # (bytes/frame) * (sample/bytes) * (sec/samples) frame_duration_s = (bytes_per_frame / self.frame_rate) / self.sample_width while offset + bytes_per_frame < len(self.raw_data): yield Frame(self.raw_data[offset:offset + bytes_per_frame], timestamp, frame_duration_s) timestamp += frame_duration_s offset += bytes_per_frame if zero_pad: rest = self.raw_data[offset:] zeros = bytes(bytes_per_frame - len(rest)) yield Frame(rest + zeros, timestamp, frame_duration_s)
[ "Yields", "self", "s", "data", "in", "chunks", "of", "frame_duration_ms", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L761-L789
[ "def", "generate_frames", "(", "self", ",", "frame_duration_ms", ",", "zero_pad", "=", "True", ")", ":", "Frame", "=", "collections", ".", "namedtuple", "(", "\"Frame\"", ",", "\"bytes timestamp duration\"", ")", "# (samples/sec) * (seconds in a frame) * (bytes/sample)", "bytes_per_frame", "=", "int", "(", "self", ".", "frame_rate", "*", "(", "frame_duration_ms", "/", "1000", ")", "*", "self", ".", "sample_width", ")", "offset", "=", "0", "# where we are so far in self's data (in bytes)", "timestamp", "=", "0.0", "# where we are so far in self (in seconds)", "# (bytes/frame) * (sample/bytes) * (sec/samples)", "frame_duration_s", "=", "(", "bytes_per_frame", "/", "self", ".", "frame_rate", ")", "/", "self", ".", "sample_width", "while", "offset", "+", "bytes_per_frame", "<", "len", "(", "self", ".", "raw_data", ")", ":", "yield", "Frame", "(", "self", ".", "raw_data", "[", "offset", ":", "offset", "+", "bytes_per_frame", "]", ",", "timestamp", ",", "frame_duration_s", ")", "timestamp", "+=", "frame_duration_s", "offset", "+=", "bytes_per_frame", "if", "zero_pad", ":", "rest", "=", "self", ".", "raw_data", "[", "offset", ":", "]", "zeros", "=", "bytes", "(", "bytes_per_frame", "-", "len", "(", "rest", ")", ")", "yield", "Frame", "(", "rest", "+", "zeros", ",", "timestamp", ",", "frame_duration_s", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.generate_frames_as_segments
Does the same thing as `generate_frames`, but yields tuples of (AudioSegment, timestamp) instead of Frames.
audiosegment.py
def generate_frames_as_segments(self, frame_duration_ms, zero_pad=True): """ Does the same thing as `generate_frames`, but yields tuples of (AudioSegment, timestamp) instead of Frames. """ for frame in self.generate_frames(frame_duration_ms, zero_pad=zero_pad): seg = AudioSegment(pydub.AudioSegment(data=frame.bytes, sample_width=self.sample_width, frame_rate=self.frame_rate, channels=self.channels), self.name) yield seg, frame.timestamp
def generate_frames_as_segments(self, frame_duration_ms, zero_pad=True): """ Does the same thing as `generate_frames`, but yields tuples of (AudioSegment, timestamp) instead of Frames. """ for frame in self.generate_frames(frame_duration_ms, zero_pad=zero_pad): seg = AudioSegment(pydub.AudioSegment(data=frame.bytes, sample_width=self.sample_width, frame_rate=self.frame_rate, channels=self.channels), self.name) yield seg, frame.timestamp
[ "Does", "the", "same", "thing", "as", "generate_frames", "but", "yields", "tuples", "of", "(", "AudioSegment", "timestamp", ")", "instead", "of", "Frames", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L791-L798
[ "def", "generate_frames_as_segments", "(", "self", ",", "frame_duration_ms", ",", "zero_pad", "=", "True", ")", ":", "for", "frame", "in", "self", ".", "generate_frames", "(", "frame_duration_ms", ",", "zero_pad", "=", "zero_pad", ")", ":", "seg", "=", "AudioSegment", "(", "pydub", ".", "AudioSegment", "(", "data", "=", "frame", ".", "bytes", ",", "sample_width", "=", "self", ".", "sample_width", ",", "frame_rate", "=", "self", ".", "frame_rate", ",", "channels", "=", "self", ".", "channels", ")", ",", "self", ".", "name", ")", "yield", "seg", ",", "frame", ".", "timestamp" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.human_audible
Returns an estimate of whether this AudioSegment is mostly human audible or not. This is done by taking an FFT of the segment and checking if the SPL of the segment falls below the function `f(x) = 40.11453 - 0.01683697x + 1.406211e-6x^2 - 2.371512e-11x^3`, where x is the most characteristic frequency in the FFT. Note that this method is essentially trying to determine if the estimated SPL of the segment falls below the threshold of human hearing, which changes over frequency. If you graph the threshold over different frequencies, you get what is called an audiogram. The equation above is derived as a curve that tries to fit a typical audiogram, specifically as found in Hearing Thresholds by Yost and Killion, 1997 (see https://www.etymotic.com/media/publications/erl-0096-1997.pdf). Sources of error are: 1) The SPL of an AudioSegment is merely an approximation; 2) this curve is not a perfect fit, and besides, it is only an approximation of a typical audiogram; 3) the algorithm uses a characteristic frequency, which is only really going to be a thing for short segments or for segments which are dominated by a single frequency. :returns: `True` if we estimate that this sound is mostly human audible. `False` if we think it is not.
audiosegment.py
def human_audible(self): """ Returns an estimate of whether this AudioSegment is mostly human audible or not. This is done by taking an FFT of the segment and checking if the SPL of the segment falls below the function `f(x) = 40.11453 - 0.01683697x + 1.406211e-6x^2 - 2.371512e-11x^3`, where x is the most characteristic frequency in the FFT. Note that this method is essentially trying to determine if the estimated SPL of the segment falls below the threshold of human hearing, which changes over frequency. If you graph the threshold over different frequencies, you get what is called an audiogram. The equation above is derived as a curve that tries to fit a typical audiogram, specifically as found in Hearing Thresholds by Yost and Killion, 1997 (see https://www.etymotic.com/media/publications/erl-0096-1997.pdf). Sources of error are: 1) The SPL of an AudioSegment is merely an approximation; 2) this curve is not a perfect fit, and besides, it is only an approximation of a typical audiogram; 3) the algorithm uses a characteristic frequency, which is only really going to be a thing for short segments or for segments which are dominated by a single frequency. :returns: `True` if we estimate that this sound is mostly human audible. `False` if we think it is not. """ hist_bins, hist_vals = self.fft() hist_vals_real_normed = np.abs(hist_vals) / len(hist_vals) f_characteristic = hist_bins[np.argmax(hist_vals_real_normed)] threshold_fc = 40.11453 - (0.01683697 * f_characteristic) + (1.406211e-6 * f_characteristic ** 2) - (2.371512e-11 * f_characteristic ** 3) return self.spl >= threshold_fc
def human_audible(self): """ Returns an estimate of whether this AudioSegment is mostly human audible or not. This is done by taking an FFT of the segment and checking if the SPL of the segment falls below the function `f(x) = 40.11453 - 0.01683697x + 1.406211e-6x^2 - 2.371512e-11x^3`, where x is the most characteristic frequency in the FFT. Note that this method is essentially trying to determine if the estimated SPL of the segment falls below the threshold of human hearing, which changes over frequency. If you graph the threshold over different frequencies, you get what is called an audiogram. The equation above is derived as a curve that tries to fit a typical audiogram, specifically as found in Hearing Thresholds by Yost and Killion, 1997 (see https://www.etymotic.com/media/publications/erl-0096-1997.pdf). Sources of error are: 1) The SPL of an AudioSegment is merely an approximation; 2) this curve is not a perfect fit, and besides, it is only an approximation of a typical audiogram; 3) the algorithm uses a characteristic frequency, which is only really going to be a thing for short segments or for segments which are dominated by a single frequency. :returns: `True` if we estimate that this sound is mostly human audible. `False` if we think it is not. """ hist_bins, hist_vals = self.fft() hist_vals_real_normed = np.abs(hist_vals) / len(hist_vals) f_characteristic = hist_bins[np.argmax(hist_vals_real_normed)] threshold_fc = 40.11453 - (0.01683697 * f_characteristic) + (1.406211e-6 * f_characteristic ** 2) - (2.371512e-11 * f_characteristic ** 3) return self.spl >= threshold_fc
[ "Returns", "an", "estimate", "of", "whether", "this", "AudioSegment", "is", "mostly", "human", "audible", "or", "not", ".", "This", "is", "done", "by", "taking", "an", "FFT", "of", "the", "segment", "and", "checking", "if", "the", "SPL", "of", "the", "segment", "falls", "below", "the", "function", "f", "(", "x", ")", "=", "40", ".", "11453", "-", "0", ".", "01683697x", "+", "1", ".", "406211e", "-", "6x^2", "-", "2", ".", "371512e", "-", "11x^3", "where", "x", "is", "the", "most", "characteristic", "frequency", "in", "the", "FFT", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L800-L827
[ "def", "human_audible", "(", "self", ")", ":", "hist_bins", ",", "hist_vals", "=", "self", ".", "fft", "(", ")", "hist_vals_real_normed", "=", "np", ".", "abs", "(", "hist_vals", ")", "/", "len", "(", "hist_vals", ")", "f_characteristic", "=", "hist_bins", "[", "np", ".", "argmax", "(", "hist_vals_real_normed", ")", "]", "threshold_fc", "=", "40.11453", "-", "(", "0.01683697", "*", "f_characteristic", ")", "+", "(", "1.406211e-6", "*", "f_characteristic", "**", "2", ")", "-", "(", "2.371512e-11", "*", "f_characteristic", "**", "3", ")", "return", "self", ".", "spl", ">=", "threshold_fc" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.normalize_spl_by_average
Normalize the values in the AudioSegment so that its `spl` property gives `db`. .. note:: This method is currently broken - it returns an AudioSegment whose values are much smaller than reasonable, yet which yield an SPL value that equals the given `db`. Such an AudioSegment will not be serializable as a WAV file, which will also break any method that relies on SOX. I may remove this method in the future, since the SPL of an AudioSegment is pretty questionable to begin with. :param db: The decibels to normalize average to. :returns: A new AudioSegment object whose values are changed so that their average is `db`. :raises: ValueError if there are no samples in this AudioSegment.
audiosegment.py
def normalize_spl_by_average(self, db): """ Normalize the values in the AudioSegment so that its `spl` property gives `db`. .. note:: This method is currently broken - it returns an AudioSegment whose values are much smaller than reasonable, yet which yield an SPL value that equals the given `db`. Such an AudioSegment will not be serializable as a WAV file, which will also break any method that relies on SOX. I may remove this method in the future, since the SPL of an AudioSegment is pretty questionable to begin with. :param db: The decibels to normalize average to. :returns: A new AudioSegment object whose values are changed so that their average is `db`. :raises: ValueError if there are no samples in this AudioSegment. """ arr = self.to_numpy_array().copy() if len(arr) == 0: raise ValueError("Cannot normalize the SPL of an empty AudioSegment") def rms(x): return np.sqrt(np.mean(np.square(x))) # Figure out what RMS we would like desired_rms = P_REF_PCM * ((10 ** (db/20.0)) - 1E-9) # Use successive approximation to solve ## Keep trying different multiplication factors until we get close enough or run out of time max_ntries = 50 res_rms = 0.0 ntries = 0 factor = 0.1 left = 0.0 right = desired_rms while (ntries < max_ntries) and not util.isclose(res_rms, desired_rms, abs_tol=0.1): res_rms = rms(arr * factor) if res_rms < desired_rms: left = factor else: right = factor factor = 0.5 * (left + right) ntries += 1 dtype_dict = {1: np.int8, 2: np.int16, 4: np.int32} dtype = dtype_dict[self.sample_width] new_seg = from_numpy_array(np.array(arr * factor, dtype=dtype), self.frame_rate) return new_seg
def normalize_spl_by_average(self, db): """ Normalize the values in the AudioSegment so that its `spl` property gives `db`. .. note:: This method is currently broken - it returns an AudioSegment whose values are much smaller than reasonable, yet which yield an SPL value that equals the given `db`. Such an AudioSegment will not be serializable as a WAV file, which will also break any method that relies on SOX. I may remove this method in the future, since the SPL of an AudioSegment is pretty questionable to begin with. :param db: The decibels to normalize average to. :returns: A new AudioSegment object whose values are changed so that their average is `db`. :raises: ValueError if there are no samples in this AudioSegment. """ arr = self.to_numpy_array().copy() if len(arr) == 0: raise ValueError("Cannot normalize the SPL of an empty AudioSegment") def rms(x): return np.sqrt(np.mean(np.square(x))) # Figure out what RMS we would like desired_rms = P_REF_PCM * ((10 ** (db/20.0)) - 1E-9) # Use successive approximation to solve ## Keep trying different multiplication factors until we get close enough or run out of time max_ntries = 50 res_rms = 0.0 ntries = 0 factor = 0.1 left = 0.0 right = desired_rms while (ntries < max_ntries) and not util.isclose(res_rms, desired_rms, abs_tol=0.1): res_rms = rms(arr * factor) if res_rms < desired_rms: left = factor else: right = factor factor = 0.5 * (left + right) ntries += 1 dtype_dict = {1: np.int8, 2: np.int16, 4: np.int32} dtype = dtype_dict[self.sample_width] new_seg = from_numpy_array(np.array(arr * factor, dtype=dtype), self.frame_rate) return new_seg
[ "Normalize", "the", "values", "in", "the", "AudioSegment", "so", "that", "its", "spl", "property", "gives", "db", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L829-L876
[ "def", "normalize_spl_by_average", "(", "self", ",", "db", ")", ":", "arr", "=", "self", ".", "to_numpy_array", "(", ")", ".", "copy", "(", ")", "if", "len", "(", "arr", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Cannot normalize the SPL of an empty AudioSegment\"", ")", "def", "rms", "(", "x", ")", ":", "return", "np", ".", "sqrt", "(", "np", ".", "mean", "(", "np", ".", "square", "(", "x", ")", ")", ")", "# Figure out what RMS we would like", "desired_rms", "=", "P_REF_PCM", "*", "(", "(", "10", "**", "(", "db", "/", "20.0", ")", ")", "-", "1E-9", ")", "# Use successive approximation to solve", "## Keep trying different multiplication factors until we get close enough or run out of time", "max_ntries", "=", "50", "res_rms", "=", "0.0", "ntries", "=", "0", "factor", "=", "0.1", "left", "=", "0.0", "right", "=", "desired_rms", "while", "(", "ntries", "<", "max_ntries", ")", "and", "not", "util", ".", "isclose", "(", "res_rms", ",", "desired_rms", ",", "abs_tol", "=", "0.1", ")", ":", "res_rms", "=", "rms", "(", "arr", "*", "factor", ")", "if", "res_rms", "<", "desired_rms", ":", "left", "=", "factor", "else", ":", "right", "=", "factor", "factor", "=", "0.5", "*", "(", "left", "+", "right", ")", "ntries", "+=", "1", "dtype_dict", "=", "{", "1", ":", "np", ".", "int8", ",", "2", ":", "np", ".", "int16", ",", "4", ":", "np", ".", "int32", "}", "dtype", "=", "dtype_dict", "[", "self", ".", "sample_width", "]", "new_seg", "=", "from_numpy_array", "(", "np", ".", "array", "(", "arr", "*", "factor", ",", "dtype", "=", "dtype", ")", ",", "self", ".", "frame_rate", ")", "return", "new_seg" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.reduce
Reduces others into this one by concatenating all the others onto this one and returning the result. Does not modify self, instead, makes a copy and returns that. :param others: The other AudioSegment objects to append to this one. :returns: The concatenated result.
audiosegment.py
def reduce(self, others): """ Reduces others into this one by concatenating all the others onto this one and returning the result. Does not modify self, instead, makes a copy and returns that. :param others: The other AudioSegment objects to append to this one. :returns: The concatenated result. """ ret = AudioSegment(self.seg, self.name) selfdata = [self.seg._data] otherdata = [o.seg._data for o in others] ret.seg._data = b''.join(selfdata + otherdata) return ret
def reduce(self, others): """ Reduces others into this one by concatenating all the others onto this one and returning the result. Does not modify self, instead, makes a copy and returns that. :param others: The other AudioSegment objects to append to this one. :returns: The concatenated result. """ ret = AudioSegment(self.seg, self.name) selfdata = [self.seg._data] otherdata = [o.seg._data for o in others] ret.seg._data = b''.join(selfdata + otherdata) return ret
[ "Reduces", "others", "into", "this", "one", "by", "concatenating", "all", "the", "others", "onto", "this", "one", "and", "returning", "the", "result", ".", "Does", "not", "modify", "self", "instead", "makes", "a", "copy", "and", "returns", "that", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L878-L891
[ "def", "reduce", "(", "self", ",", "others", ")", ":", "ret", "=", "AudioSegment", "(", "self", ".", "seg", ",", "self", ".", "name", ")", "selfdata", "=", "[", "self", ".", "seg", ".", "_data", "]", "otherdata", "=", "[", "o", ".", "seg", ".", "_data", "for", "o", "in", "others", "]", "ret", ".", "seg", ".", "_data", "=", "b''", ".", "join", "(", "selfdata", "+", "otherdata", ")", "return", "ret" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.resample
Returns a new AudioSegment whose data is the same as this one, but which has been resampled to the specified characteristics. Any parameter left None will be unchanged. .. note:: This method requires that you have the program 'sox' installed. .. warning:: This method uses the program 'sox' to perform the task. While this is very fast for a single function call, the IO may add up for large numbers of AudioSegment objects. :param sample_rate_Hz: The new sample rate in Hz. :param sample_width: The new sample width in bytes, so sample_width=2 would correspond to 16 bit (2 byte) width. :param channels: The new number of channels. :param console_output: Will print the output of sox to the console if True. :returns: The newly sampled AudioSegment.
audiosegment.py
def resample(self, sample_rate_Hz=None, sample_width=None, channels=None, console_output=False): """ Returns a new AudioSegment whose data is the same as this one, but which has been resampled to the specified characteristics. Any parameter left None will be unchanged. .. note:: This method requires that you have the program 'sox' installed. .. warning:: This method uses the program 'sox' to perform the task. While this is very fast for a single function call, the IO may add up for large numbers of AudioSegment objects. :param sample_rate_Hz: The new sample rate in Hz. :param sample_width: The new sample width in bytes, so sample_width=2 would correspond to 16 bit (2 byte) width. :param channels: The new number of channels. :param console_output: Will print the output of sox to the console if True. :returns: The newly sampled AudioSegment. """ if sample_rate_Hz is None: sample_rate_Hz = self.frame_rate if sample_width is None: sample_width = self.sample_width if channels is None: channels = self.channels # TODO: Replace this with librosa's implementation to remove SOX dependency here command = "sox {inputfile} -b " + str(sample_width * 8) + " -r " + str(sample_rate_Hz) \ + " -t wav {outputfile} channels " + str(channels) return self._execute_sox_cmd(command, console_output=console_output)
def resample(self, sample_rate_Hz=None, sample_width=None, channels=None, console_output=False): """ Returns a new AudioSegment whose data is the same as this one, but which has been resampled to the specified characteristics. Any parameter left None will be unchanged. .. note:: This method requires that you have the program 'sox' installed. .. warning:: This method uses the program 'sox' to perform the task. While this is very fast for a single function call, the IO may add up for large numbers of AudioSegment objects. :param sample_rate_Hz: The new sample rate in Hz. :param sample_width: The new sample width in bytes, so sample_width=2 would correspond to 16 bit (2 byte) width. :param channels: The new number of channels. :param console_output: Will print the output of sox to the console if True. :returns: The newly sampled AudioSegment. """ if sample_rate_Hz is None: sample_rate_Hz = self.frame_rate if sample_width is None: sample_width = self.sample_width if channels is None: channels = self.channels # TODO: Replace this with librosa's implementation to remove SOX dependency here command = "sox {inputfile} -b " + str(sample_width * 8) + " -r " + str(sample_rate_Hz) \ + " -t wav {outputfile} channels " + str(channels) return self._execute_sox_cmd(command, console_output=console_output)
[ "Returns", "a", "new", "AudioSegment", "whose", "data", "is", "the", "same", "as", "this", "one", "but", "which", "has", "been", "resampled", "to", "the", "specified", "characteristics", ".", "Any", "parameter", "left", "None", "will", "be", "unchanged", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L893-L920
[ "def", "resample", "(", "self", ",", "sample_rate_Hz", "=", "None", ",", "sample_width", "=", "None", ",", "channels", "=", "None", ",", "console_output", "=", "False", ")", ":", "if", "sample_rate_Hz", "is", "None", ":", "sample_rate_Hz", "=", "self", ".", "frame_rate", "if", "sample_width", "is", "None", ":", "sample_width", "=", "self", ".", "sample_width", "if", "channels", "is", "None", ":", "channels", "=", "self", ".", "channels", "# TODO: Replace this with librosa's implementation to remove SOX dependency here", "command", "=", "\"sox {inputfile} -b \"", "+", "str", "(", "sample_width", "*", "8", ")", "+", "\" -r \"", "+", "str", "(", "sample_rate_Hz", ")", "+", "\" -t wav {outputfile} channels \"", "+", "str", "(", "channels", ")", "return", "self", ".", "_execute_sox_cmd", "(", "command", ",", "console_output", "=", "console_output", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.serialize
Serializes into a bytestring. :returns: An object of type Bytes.
audiosegment.py
def serialize(self): """ Serializes into a bytestring. :returns: An object of type Bytes. """ d = self.__getstate__() return pickle.dumps({ 'name': d['name'], 'seg': pickle.dumps(d['seg'], protocol=-1), }, protocol=-1)
def serialize(self): """ Serializes into a bytestring. :returns: An object of type Bytes. """ d = self.__getstate__() return pickle.dumps({ 'name': d['name'], 'seg': pickle.dumps(d['seg'], protocol=-1), }, protocol=-1)
[ "Serializes", "into", "a", "bytestring", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L938-L948
[ "def", "serialize", "(", "self", ")", ":", "d", "=", "self", ".", "__getstate__", "(", ")", "return", "pickle", ".", "dumps", "(", "{", "'name'", ":", "d", "[", "'name'", "]", ",", "'seg'", ":", "pickle", ".", "dumps", "(", "d", "[", "'seg'", "]", ",", "protocol", "=", "-", "1", ")", ",", "}", ",", "protocol", "=", "-", "1", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.spectrogram
Does a series of FFTs from `start_s` or `start_sample` for `duration_s` or `num_samples`. Effectively, transforms a slice of the AudioSegment into the frequency domain across different time bins. .. code-block:: python # Example for plotting a spectrogram using this function import audiosegment import matplotlib.pyplot as plt #... seg = audiosegment.from_file("somebodytalking.wav") freqs, times, amplitudes = seg.spectrogram(window_length_s=0.03, overlap=0.5) amplitudes = 10 * np.log10(amplitudes + 1e-9) # Plot plt.pcolormesh(times, freqs, amplitudes) plt.xlabel("Time in Seconds") plt.ylabel("Frequency in Hz") plt.show() .. image:: images/spectrogram.png :param start_s: The start time. Starts at the beginning if neither this nor `start_sample` is specified. :param duration_s: The duration of the spectrogram in seconds. Goes to the end if neither this nor `num_samples` is specified. :param start_sample: The index of the first sample to use. Starts at the beginning if neither this nor `start_s` is specified. :param num_samples: The number of samples in the spectrogram. Goes to the end if neither this nor `duration_s` is specified. :param window_length_s: The length of each FFT in seconds. If the total number of samples in the spectrogram is not a multiple of the window length in samples, the last window will be zero-padded. :param window_length_samples: The length of each FFT in number of samples. If the total number of samples in the spectrogram is not a multiple of the window length in samples, the last window will be zero-padded. :param overlap: The fraction of each window to overlap. :param window: See Scipy's spectrogram-function_. This parameter is passed as-is directly into the Scipy spectrogram function. It's documentation is reproduced here: Desired window to use. If window is a string or tuple, it is passed to get_window to generate the window values, which are DFT-even by default. See get_window for a list of windows and required parameters. If window is array_like it will be used directly as the window and its length must be `window_length_samples`. Defaults to a Tukey window with shape parameter of 0.25. :returns: Three np.ndarrays: The frequency values in Hz (the y-axis in a spectrogram), the time values starting at start time and then increasing by `duration_s` each step (the x-axis in a spectrogram), and the dB of each time/frequency bin as a 2D array of shape [len(frequency values), len(duration)]. :raises ValueError: If `start_s` and `start_sample` are both specified, if `duration_s` and `num_samples` are both specified, if the first window's duration plus start time lead to running off the end of the AudioSegment, or if `window_length_s` and `window_length_samples` are either both specified or if they are both not specified. .. _spectrogram-function: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html
audiosegment.py
def spectrogram(self, start_s=None, duration_s=None, start_sample=None, num_samples=None, window_length_s=None, window_length_samples=None, overlap=0.5, window=('tukey', 0.25)): """ Does a series of FFTs from `start_s` or `start_sample` for `duration_s` or `num_samples`. Effectively, transforms a slice of the AudioSegment into the frequency domain across different time bins. .. code-block:: python # Example for plotting a spectrogram using this function import audiosegment import matplotlib.pyplot as plt #... seg = audiosegment.from_file("somebodytalking.wav") freqs, times, amplitudes = seg.spectrogram(window_length_s=0.03, overlap=0.5) amplitudes = 10 * np.log10(amplitudes + 1e-9) # Plot plt.pcolormesh(times, freqs, amplitudes) plt.xlabel("Time in Seconds") plt.ylabel("Frequency in Hz") plt.show() .. image:: images/spectrogram.png :param start_s: The start time. Starts at the beginning if neither this nor `start_sample` is specified. :param duration_s: The duration of the spectrogram in seconds. Goes to the end if neither this nor `num_samples` is specified. :param start_sample: The index of the first sample to use. Starts at the beginning if neither this nor `start_s` is specified. :param num_samples: The number of samples in the spectrogram. Goes to the end if neither this nor `duration_s` is specified. :param window_length_s: The length of each FFT in seconds. If the total number of samples in the spectrogram is not a multiple of the window length in samples, the last window will be zero-padded. :param window_length_samples: The length of each FFT in number of samples. If the total number of samples in the spectrogram is not a multiple of the window length in samples, the last window will be zero-padded. :param overlap: The fraction of each window to overlap. :param window: See Scipy's spectrogram-function_. This parameter is passed as-is directly into the Scipy spectrogram function. It's documentation is reproduced here: Desired window to use. If window is a string or tuple, it is passed to get_window to generate the window values, which are DFT-even by default. See get_window for a list of windows and required parameters. If window is array_like it will be used directly as the window and its length must be `window_length_samples`. Defaults to a Tukey window with shape parameter of 0.25. :returns: Three np.ndarrays: The frequency values in Hz (the y-axis in a spectrogram), the time values starting at start time and then increasing by `duration_s` each step (the x-axis in a spectrogram), and the dB of each time/frequency bin as a 2D array of shape [len(frequency values), len(duration)]. :raises ValueError: If `start_s` and `start_sample` are both specified, if `duration_s` and `num_samples` are both specified, if the first window's duration plus start time lead to running off the end of the AudioSegment, or if `window_length_s` and `window_length_samples` are either both specified or if they are both not specified. .. _spectrogram-function: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html """ if start_s is not None and start_sample is not None: raise ValueError("Only one of start_s and start_sample may be specified.") if duration_s is not None and num_samples is not None: raise ValueError("Only one of duration_s and num_samples may be specified.") if window_length_s is not None and window_length_samples is not None: raise ValueError("Only one of window_length_s and window_length_samples may be specified.") if window_length_s is None and window_length_samples is None: raise ValueError("You must specify a window length, either in window_length_s or in window_length_samples.") # Determine the start sample if start_s is None and start_sample is None: start_sample = 0 elif start_s is not None: start_sample = int(round(start_s * self.frame_rate)) # Determine the number of samples if duration_s is None and num_samples is None: num_samples = len(self.get_array_of_samples()) - int(start_sample) elif duration_s is not None: num_samples = int(round(duration_s * self.frame_rate)) # Determine the number of samples per window if window_length_s is not None: window_length_samples = int(round(window_length_s * self.frame_rate)) # Check validity of number of samples if start_sample + num_samples > len(self.get_array_of_samples()): raise ValueError("The combination of start and duration will run off the end of the AudioSegment object.") # Create a Numpy Array out of the correct samples arr = self.to_numpy_array()[start_sample:start_sample+num_samples] # Use Scipy spectrogram and return fs, ts, sxx = signal.spectrogram(arr, self.frame_rate, scaling='spectrum', nperseg=window_length_samples, noverlap=int(round(overlap * window_length_samples)), mode='magnitude', window=window) return fs, ts, sxx
def spectrogram(self, start_s=None, duration_s=None, start_sample=None, num_samples=None, window_length_s=None, window_length_samples=None, overlap=0.5, window=('tukey', 0.25)): """ Does a series of FFTs from `start_s` or `start_sample` for `duration_s` or `num_samples`. Effectively, transforms a slice of the AudioSegment into the frequency domain across different time bins. .. code-block:: python # Example for plotting a spectrogram using this function import audiosegment import matplotlib.pyplot as plt #... seg = audiosegment.from_file("somebodytalking.wav") freqs, times, amplitudes = seg.spectrogram(window_length_s=0.03, overlap=0.5) amplitudes = 10 * np.log10(amplitudes + 1e-9) # Plot plt.pcolormesh(times, freqs, amplitudes) plt.xlabel("Time in Seconds") plt.ylabel("Frequency in Hz") plt.show() .. image:: images/spectrogram.png :param start_s: The start time. Starts at the beginning if neither this nor `start_sample` is specified. :param duration_s: The duration of the spectrogram in seconds. Goes to the end if neither this nor `num_samples` is specified. :param start_sample: The index of the first sample to use. Starts at the beginning if neither this nor `start_s` is specified. :param num_samples: The number of samples in the spectrogram. Goes to the end if neither this nor `duration_s` is specified. :param window_length_s: The length of each FFT in seconds. If the total number of samples in the spectrogram is not a multiple of the window length in samples, the last window will be zero-padded. :param window_length_samples: The length of each FFT in number of samples. If the total number of samples in the spectrogram is not a multiple of the window length in samples, the last window will be zero-padded. :param overlap: The fraction of each window to overlap. :param window: See Scipy's spectrogram-function_. This parameter is passed as-is directly into the Scipy spectrogram function. It's documentation is reproduced here: Desired window to use. If window is a string or tuple, it is passed to get_window to generate the window values, which are DFT-even by default. See get_window for a list of windows and required parameters. If window is array_like it will be used directly as the window and its length must be `window_length_samples`. Defaults to a Tukey window with shape parameter of 0.25. :returns: Three np.ndarrays: The frequency values in Hz (the y-axis in a spectrogram), the time values starting at start time and then increasing by `duration_s` each step (the x-axis in a spectrogram), and the dB of each time/frequency bin as a 2D array of shape [len(frequency values), len(duration)]. :raises ValueError: If `start_s` and `start_sample` are both specified, if `duration_s` and `num_samples` are both specified, if the first window's duration plus start time lead to running off the end of the AudioSegment, or if `window_length_s` and `window_length_samples` are either both specified or if they are both not specified. .. _spectrogram-function: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html """ if start_s is not None and start_sample is not None: raise ValueError("Only one of start_s and start_sample may be specified.") if duration_s is not None and num_samples is not None: raise ValueError("Only one of duration_s and num_samples may be specified.") if window_length_s is not None and window_length_samples is not None: raise ValueError("Only one of window_length_s and window_length_samples may be specified.") if window_length_s is None and window_length_samples is None: raise ValueError("You must specify a window length, either in window_length_s or in window_length_samples.") # Determine the start sample if start_s is None and start_sample is None: start_sample = 0 elif start_s is not None: start_sample = int(round(start_s * self.frame_rate)) # Determine the number of samples if duration_s is None and num_samples is None: num_samples = len(self.get_array_of_samples()) - int(start_sample) elif duration_s is not None: num_samples = int(round(duration_s * self.frame_rate)) # Determine the number of samples per window if window_length_s is not None: window_length_samples = int(round(window_length_s * self.frame_rate)) # Check validity of number of samples if start_sample + num_samples > len(self.get_array_of_samples()): raise ValueError("The combination of start and duration will run off the end of the AudioSegment object.") # Create a Numpy Array out of the correct samples arr = self.to_numpy_array()[start_sample:start_sample+num_samples] # Use Scipy spectrogram and return fs, ts, sxx = signal.spectrogram(arr, self.frame_rate, scaling='spectrum', nperseg=window_length_samples, noverlap=int(round(overlap * window_length_samples)), mode='magnitude', window=window) return fs, ts, sxx
[ "Does", "a", "series", "of", "FFTs", "from", "start_s", "or", "start_sample", "for", "duration_s", "or", "num_samples", ".", "Effectively", "transforms", "a", "slice", "of", "the", "AudioSegment", "into", "the", "frequency", "domain", "across", "different", "time", "bins", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L950-L1042
[ "def", "spectrogram", "(", "self", ",", "start_s", "=", "None", ",", "duration_s", "=", "None", ",", "start_sample", "=", "None", ",", "num_samples", "=", "None", ",", "window_length_s", "=", "None", ",", "window_length_samples", "=", "None", ",", "overlap", "=", "0.5", ",", "window", "=", "(", "'tukey'", ",", "0.25", ")", ")", ":", "if", "start_s", "is", "not", "None", "and", "start_sample", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Only one of start_s and start_sample may be specified.\"", ")", "if", "duration_s", "is", "not", "None", "and", "num_samples", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Only one of duration_s and num_samples may be specified.\"", ")", "if", "window_length_s", "is", "not", "None", "and", "window_length_samples", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Only one of window_length_s and window_length_samples may be specified.\"", ")", "if", "window_length_s", "is", "None", "and", "window_length_samples", "is", "None", ":", "raise", "ValueError", "(", "\"You must specify a window length, either in window_length_s or in window_length_samples.\"", ")", "# Determine the start sample", "if", "start_s", "is", "None", "and", "start_sample", "is", "None", ":", "start_sample", "=", "0", "elif", "start_s", "is", "not", "None", ":", "start_sample", "=", "int", "(", "round", "(", "start_s", "*", "self", ".", "frame_rate", ")", ")", "# Determine the number of samples", "if", "duration_s", "is", "None", "and", "num_samples", "is", "None", ":", "num_samples", "=", "len", "(", "self", ".", "get_array_of_samples", "(", ")", ")", "-", "int", "(", "start_sample", ")", "elif", "duration_s", "is", "not", "None", ":", "num_samples", "=", "int", "(", "round", "(", "duration_s", "*", "self", ".", "frame_rate", ")", ")", "# Determine the number of samples per window", "if", "window_length_s", "is", "not", "None", ":", "window_length_samples", "=", "int", "(", "round", "(", "window_length_s", "*", "self", ".", "frame_rate", ")", ")", "# Check validity of number of samples", "if", "start_sample", "+", "num_samples", ">", "len", "(", "self", ".", "get_array_of_samples", "(", ")", ")", ":", "raise", "ValueError", "(", "\"The combination of start and duration will run off the end of the AudioSegment object.\"", ")", "# Create a Numpy Array out of the correct samples", "arr", "=", "self", ".", "to_numpy_array", "(", ")", "[", "start_sample", ":", "start_sample", "+", "num_samples", "]", "# Use Scipy spectrogram and return", "fs", ",", "ts", ",", "sxx", "=", "signal", ".", "spectrogram", "(", "arr", ",", "self", ".", "frame_rate", ",", "scaling", "=", "'spectrum'", ",", "nperseg", "=", "window_length_samples", ",", "noverlap", "=", "int", "(", "round", "(", "overlap", "*", "window_length_samples", ")", ")", ",", "mode", "=", "'magnitude'", ",", "window", "=", "window", ")", "return", "fs", ",", "ts", ",", "sxx" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.to_numpy_array
Convenience function for `np.array(self.get_array_of_samples())` while keeping the appropriate dtype.
audiosegment.py
def to_numpy_array(self): """ Convenience function for `np.array(self.get_array_of_samples())` while keeping the appropriate dtype. """ dtype_dict = { 1: np.int8, 2: np.int16, 4: np.int32 } dtype = dtype_dict[self.sample_width] return np.array(self.get_array_of_samples(), dtype=dtype)
def to_numpy_array(self): """ Convenience function for `np.array(self.get_array_of_samples())` while keeping the appropriate dtype. """ dtype_dict = { 1: np.int8, 2: np.int16, 4: np.int32 } dtype = dtype_dict[self.sample_width] return np.array(self.get_array_of_samples(), dtype=dtype)
[ "Convenience", "function", "for", "np", ".", "array", "(", "self", ".", "get_array_of_samples", "()", ")", "while", "keeping", "the", "appropriate", "dtype", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L1044-L1055
[ "def", "to_numpy_array", "(", "self", ")", ":", "dtype_dict", "=", "{", "1", ":", "np", ".", "int8", ",", "2", ":", "np", ".", "int16", ",", "4", ":", "np", ".", "int32", "}", "dtype", "=", "dtype_dict", "[", "self", ".", "sample_width", "]", "return", "np", ".", "array", "(", "self", ".", "get_array_of_samples", "(", ")", ",", "dtype", "=", "dtype", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
AudioSegment.zero_extend
Adds a number of zeros (digital silence) to the AudioSegment (returning a new one). :param duration_s: The number of seconds of zeros to add. If this is specified, `num_samples` must be None. :param num_samples: The number of zeros to add. If this is specified, `duration_s` must be None. :returns: A new AudioSegment object that has been zero extended. :raises: ValueError if duration_s and num_samples are both specified.
audiosegment.py
def zero_extend(self, duration_s=None, num_samples=None): """ Adds a number of zeros (digital silence) to the AudioSegment (returning a new one). :param duration_s: The number of seconds of zeros to add. If this is specified, `num_samples` must be None. :param num_samples: The number of zeros to add. If this is specified, `duration_s` must be None. :returns: A new AudioSegment object that has been zero extended. :raises: ValueError if duration_s and num_samples are both specified. """ if duration_s is not None and num_samples is not None: raise ValueError("`duration_s` and `num_samples` cannot both be specified.") elif duration_s is not None: num_samples = self.frame_rate * duration_s seg = AudioSegment(self.seg, self.name) zeros = silent(duration=num_samples / self.frame_rate, frame_rate=self.frame_rate) return zeros.overlay(seg)
def zero_extend(self, duration_s=None, num_samples=None): """ Adds a number of zeros (digital silence) to the AudioSegment (returning a new one). :param duration_s: The number of seconds of zeros to add. If this is specified, `num_samples` must be None. :param num_samples: The number of zeros to add. If this is specified, `duration_s` must be None. :returns: A new AudioSegment object that has been zero extended. :raises: ValueError if duration_s and num_samples are both specified. """ if duration_s is not None and num_samples is not None: raise ValueError("`duration_s` and `num_samples` cannot both be specified.") elif duration_s is not None: num_samples = self.frame_rate * duration_s seg = AudioSegment(self.seg, self.name) zeros = silent(duration=num_samples / self.frame_rate, frame_rate=self.frame_rate) return zeros.overlay(seg)
[ "Adds", "a", "number", "of", "zeros", "(", "digital", "silence", ")", "to", "the", "AudioSegment", "(", "returning", "a", "new", "one", ")", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L1057-L1072
[ "def", "zero_extend", "(", "self", ",", "duration_s", "=", "None", ",", "num_samples", "=", "None", ")", ":", "if", "duration_s", "is", "not", "None", "and", "num_samples", "is", "not", "None", ":", "raise", "ValueError", "(", "\"`duration_s` and `num_samples` cannot both be specified.\"", ")", "elif", "duration_s", "is", "not", "None", ":", "num_samples", "=", "self", ".", "frame_rate", "*", "duration_s", "seg", "=", "AudioSegment", "(", "self", ".", "seg", ",", "self", ".", "name", ")", "zeros", "=", "silent", "(", "duration", "=", "num_samples", "/", "self", ".", "frame_rate", ",", "frame_rate", "=", "self", ".", "frame_rate", ")", "return", "zeros", ".", "overlay", "(", "seg", ")" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
_compute_peaks_or_valleys_of_first_derivative
Takes a spectrogram and returns a 2D array of the form: 0 0 0 1 0 0 1 0 0 0 1 <-- Frequency 0 0 0 1 0 0 0 0 0 0 1 0 <-- Frequency 1 0 0 0 0 0 0 1 0 1 0 0 <-- Frequency 2 *** Time axis ******* Where a 1 means that the value in that time bin in the spectrogram corresponds to a peak/valley in the first derivative. This function is used as part of the ASA algorithm and is not meant to be used publicly.
algorithms/asa.py
def _compute_peaks_or_valleys_of_first_derivative(s, do_peaks=True): """ Takes a spectrogram and returns a 2D array of the form: 0 0 0 1 0 0 1 0 0 0 1 <-- Frequency 0 0 0 1 0 0 0 0 0 0 1 0 <-- Frequency 1 0 0 0 0 0 0 1 0 1 0 0 <-- Frequency 2 *** Time axis ******* Where a 1 means that the value in that time bin in the spectrogram corresponds to a peak/valley in the first derivative. This function is used as part of the ASA algorithm and is not meant to be used publicly. """ # Get the first derivative of each frequency in the time domain gradient = np.nan_to_num(np.apply_along_axis(np.gradient, 1, s), copy=False) # Calculate the value we will use for determinig whether something is an event or not threshold = np.squeeze(np.nanmean(gradient, axis=1) + np.nanstd(gradient, axis=1)) # Look for relative extrema along the time dimension half_window = 4 if do_peaks: indexes = [signal.argrelextrema(gradient[i, :], np.greater, order=half_window)[0] for i in range(gradient.shape[0])] else: indexes = [signal.argrelextrema(gradient[i, :], np.less, order=half_window)[0] for i in range(gradient.shape[0])] # indexes should now contain the indexes of possible extrema # But we need to filter out values that are not large enough, and we want the end result # to be a 1 or 0 mask corresponding to locations of extrema extrema = np.zeros(s.shape) for row_index, index_array in enumerate(indexes): # Each index_array is a list of indexes corresponding to all the extrema in a given row for col_index in index_array: if do_peaks and (gradient[row_index, col_index] > threshold[row_index]): extrema[row_index, col_index] = 1 elif not do_peaks: # Note that we do not remove under-threshold values from the offsets - these will be taken care of later in the algo extrema[row_index, col_index] = 1 return extrema, gradient
def _compute_peaks_or_valleys_of_first_derivative(s, do_peaks=True): """ Takes a spectrogram and returns a 2D array of the form: 0 0 0 1 0 0 1 0 0 0 1 <-- Frequency 0 0 0 1 0 0 0 0 0 0 1 0 <-- Frequency 1 0 0 0 0 0 0 1 0 1 0 0 <-- Frequency 2 *** Time axis ******* Where a 1 means that the value in that time bin in the spectrogram corresponds to a peak/valley in the first derivative. This function is used as part of the ASA algorithm and is not meant to be used publicly. """ # Get the first derivative of each frequency in the time domain gradient = np.nan_to_num(np.apply_along_axis(np.gradient, 1, s), copy=False) # Calculate the value we will use for determinig whether something is an event or not threshold = np.squeeze(np.nanmean(gradient, axis=1) + np.nanstd(gradient, axis=1)) # Look for relative extrema along the time dimension half_window = 4 if do_peaks: indexes = [signal.argrelextrema(gradient[i, :], np.greater, order=half_window)[0] for i in range(gradient.shape[0])] else: indexes = [signal.argrelextrema(gradient[i, :], np.less, order=half_window)[0] for i in range(gradient.shape[0])] # indexes should now contain the indexes of possible extrema # But we need to filter out values that are not large enough, and we want the end result # to be a 1 or 0 mask corresponding to locations of extrema extrema = np.zeros(s.shape) for row_index, index_array in enumerate(indexes): # Each index_array is a list of indexes corresponding to all the extrema in a given row for col_index in index_array: if do_peaks and (gradient[row_index, col_index] > threshold[row_index]): extrema[row_index, col_index] = 1 elif not do_peaks: # Note that we do not remove under-threshold values from the offsets - these will be taken care of later in the algo extrema[row_index, col_index] = 1 return extrema, gradient
[ "Takes", "a", "spectrogram", "and", "returns", "a", "2D", "array", "of", "the", "form", ":" ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/algorithms/asa.py#L104-L143
[ "def", "_compute_peaks_or_valleys_of_first_derivative", "(", "s", ",", "do_peaks", "=", "True", ")", ":", "# Get the first derivative of each frequency in the time domain", "gradient", "=", "np", ".", "nan_to_num", "(", "np", ".", "apply_along_axis", "(", "np", ".", "gradient", ",", "1", ",", "s", ")", ",", "copy", "=", "False", ")", "# Calculate the value we will use for determinig whether something is an event or not", "threshold", "=", "np", ".", "squeeze", "(", "np", ".", "nanmean", "(", "gradient", ",", "axis", "=", "1", ")", "+", "np", ".", "nanstd", "(", "gradient", ",", "axis", "=", "1", ")", ")", "# Look for relative extrema along the time dimension", "half_window", "=", "4", "if", "do_peaks", ":", "indexes", "=", "[", "signal", ".", "argrelextrema", "(", "gradient", "[", "i", ",", ":", "]", ",", "np", ".", "greater", ",", "order", "=", "half_window", ")", "[", "0", "]", "for", "i", "in", "range", "(", "gradient", ".", "shape", "[", "0", "]", ")", "]", "else", ":", "indexes", "=", "[", "signal", ".", "argrelextrema", "(", "gradient", "[", "i", ",", ":", "]", ",", "np", ".", "less", ",", "order", "=", "half_window", ")", "[", "0", "]", "for", "i", "in", "range", "(", "gradient", ".", "shape", "[", "0", "]", ")", "]", "# indexes should now contain the indexes of possible extrema", "# But we need to filter out values that are not large enough, and we want the end result", "# to be a 1 or 0 mask corresponding to locations of extrema", "extrema", "=", "np", ".", "zeros", "(", "s", ".", "shape", ")", "for", "row_index", ",", "index_array", "in", "enumerate", "(", "indexes", ")", ":", "# Each index_array is a list of indexes corresponding to all the extrema in a given row", "for", "col_index", "in", "index_array", ":", "if", "do_peaks", "and", "(", "gradient", "[", "row_index", ",", "col_index", "]", ">", "threshold", "[", "row_index", "]", ")", ":", "extrema", "[", "row_index", ",", "col_index", "]", "=", "1", "elif", "not", "do_peaks", ":", "# Note that we do not remove under-threshold values from the offsets - these will be taken care of later in the algo", "extrema", "[", "row_index", ",", "col_index", "]", "=", "1", "return", "extrema", ",", "gradient" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6
test
_correlate_onsets_and_offsets
Takes an array of onsets and an array of offsets, of the shape [nfrequencies, nsamples], where each item in these arrays is either a 0 (not an on/offset) or a 1 (a possible on/offset). This function returns a new offsets array, where there is a one-to-one correlation between onsets and offsets, such that each onset has exactly one offset that occurs after it in the time domain (the second dimension of the array). The gradients array is used to decide which offset to use in the case of multiple possibilities.
algorithms/asa.py
def _correlate_onsets_and_offsets(onsets, offsets, gradients): """ Takes an array of onsets and an array of offsets, of the shape [nfrequencies, nsamples], where each item in these arrays is either a 0 (not an on/offset) or a 1 (a possible on/offset). This function returns a new offsets array, where there is a one-to-one correlation between onsets and offsets, such that each onset has exactly one offset that occurs after it in the time domain (the second dimension of the array). The gradients array is used to decide which offset to use in the case of multiple possibilities. """ # For each freq channel: for freq_index, (ons, offs) in enumerate(zip(onsets[:, :], offsets[:, :])): # Scan along onsets[f, :] until we find the first 1 indexes_of_all_ones = np.reshape(np.where(ons == 1), (-1,)) # Zero out anything in the offsets up to (and including) this point # since we can't have an offset before the first onset last_idx = indexes_of_all_ones[0] offs[0:last_idx + 1] = 0 if len(indexes_of_all_ones > 1): # Do the rest of this only if we have more than one onset in this frequency band for next_idx in indexes_of_all_ones[1:]: # Get all the indexes of possible offsets from onset index to next onset index offset_choices = offs[last_idx:next_idx] offset_choice_indexes = np.where(offset_choices == 1) # Assert that there is at least one offset choice if not np.any(offset_choices): continue assert np.any(offset_choices), "Offsets from {} to {} only include zeros".format(last_idx, next_idx) # If we have more than one choice, the offset index is the one that corresponds to the most negative gradient value # Convert the offset_choice_indexes to indexes in the whole offset array, rather than just the offset_choices array offset_choice_indexes = np.reshape(last_idx + offset_choice_indexes, (-1,)) assert np.all(offsets[freq_index, offset_choice_indexes]) gradient_values = gradients[freq_index, offset_choice_indexes] index_of_largest_from_gradient_values = np.where(gradient_values == np.min(gradient_values))[0] index_of_largest_offset_choice = offset_choice_indexes[index_of_largest_from_gradient_values] assert offsets[freq_index, index_of_largest_offset_choice] == 1 # Zero the others offsets[freq_index, offset_choice_indexes] = 0 offsets[freq_index, index_of_largest_offset_choice] = 1 last_idx = next_idx else: # We only have one onset in this frequency band, so the offset will be the very last sample offsets[freq_index, :] = 0 offsets[freq_index, -1] = 1 return offsets
def _correlate_onsets_and_offsets(onsets, offsets, gradients): """ Takes an array of onsets and an array of offsets, of the shape [nfrequencies, nsamples], where each item in these arrays is either a 0 (not an on/offset) or a 1 (a possible on/offset). This function returns a new offsets array, where there is a one-to-one correlation between onsets and offsets, such that each onset has exactly one offset that occurs after it in the time domain (the second dimension of the array). The gradients array is used to decide which offset to use in the case of multiple possibilities. """ # For each freq channel: for freq_index, (ons, offs) in enumerate(zip(onsets[:, :], offsets[:, :])): # Scan along onsets[f, :] until we find the first 1 indexes_of_all_ones = np.reshape(np.where(ons == 1), (-1,)) # Zero out anything in the offsets up to (and including) this point # since we can't have an offset before the first onset last_idx = indexes_of_all_ones[0] offs[0:last_idx + 1] = 0 if len(indexes_of_all_ones > 1): # Do the rest of this only if we have more than one onset in this frequency band for next_idx in indexes_of_all_ones[1:]: # Get all the indexes of possible offsets from onset index to next onset index offset_choices = offs[last_idx:next_idx] offset_choice_indexes = np.where(offset_choices == 1) # Assert that there is at least one offset choice if not np.any(offset_choices): continue assert np.any(offset_choices), "Offsets from {} to {} only include zeros".format(last_idx, next_idx) # If we have more than one choice, the offset index is the one that corresponds to the most negative gradient value # Convert the offset_choice_indexes to indexes in the whole offset array, rather than just the offset_choices array offset_choice_indexes = np.reshape(last_idx + offset_choice_indexes, (-1,)) assert np.all(offsets[freq_index, offset_choice_indexes]) gradient_values = gradients[freq_index, offset_choice_indexes] index_of_largest_from_gradient_values = np.where(gradient_values == np.min(gradient_values))[0] index_of_largest_offset_choice = offset_choice_indexes[index_of_largest_from_gradient_values] assert offsets[freq_index, index_of_largest_offset_choice] == 1 # Zero the others offsets[freq_index, offset_choice_indexes] = 0 offsets[freq_index, index_of_largest_offset_choice] = 1 last_idx = next_idx else: # We only have one onset in this frequency band, so the offset will be the very last sample offsets[freq_index, :] = 0 offsets[freq_index, -1] = 1 return offsets
[ "Takes", "an", "array", "of", "onsets", "and", "an", "array", "of", "offsets", "of", "the", "shape", "[", "nfrequencies", "nsamples", "]", "where", "each", "item", "in", "these", "arrays", "is", "either", "a", "0", "(", "not", "an", "on", "/", "offset", ")", "or", "a", "1", "(", "a", "possible", "on", "/", "offset", ")", "." ]
MaxStrange/AudioSegment
python
https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/algorithms/asa.py#L145-L195
[ "def", "_correlate_onsets_and_offsets", "(", "onsets", ",", "offsets", ",", "gradients", ")", ":", "# For each freq channel:", "for", "freq_index", ",", "(", "ons", ",", "offs", ")", "in", "enumerate", "(", "zip", "(", "onsets", "[", ":", ",", ":", "]", ",", "offsets", "[", ":", ",", ":", "]", ")", ")", ":", "# Scan along onsets[f, :] until we find the first 1", "indexes_of_all_ones", "=", "np", ".", "reshape", "(", "np", ".", "where", "(", "ons", "==", "1", ")", ",", "(", "-", "1", ",", ")", ")", "# Zero out anything in the offsets up to (and including) this point", "# since we can't have an offset before the first onset", "last_idx", "=", "indexes_of_all_ones", "[", "0", "]", "offs", "[", "0", ":", "last_idx", "+", "1", "]", "=", "0", "if", "len", "(", "indexes_of_all_ones", ">", "1", ")", ":", "# Do the rest of this only if we have more than one onset in this frequency band", "for", "next_idx", "in", "indexes_of_all_ones", "[", "1", ":", "]", ":", "# Get all the indexes of possible offsets from onset index to next onset index", "offset_choices", "=", "offs", "[", "last_idx", ":", "next_idx", "]", "offset_choice_indexes", "=", "np", ".", "where", "(", "offset_choices", "==", "1", ")", "# Assert that there is at least one offset choice", "if", "not", "np", ".", "any", "(", "offset_choices", ")", ":", "continue", "assert", "np", ".", "any", "(", "offset_choices", ")", ",", "\"Offsets from {} to {} only include zeros\"", ".", "format", "(", "last_idx", ",", "next_idx", ")", "# If we have more than one choice, the offset index is the one that corresponds to the most negative gradient value", "# Convert the offset_choice_indexes to indexes in the whole offset array, rather than just the offset_choices array", "offset_choice_indexes", "=", "np", ".", "reshape", "(", "last_idx", "+", "offset_choice_indexes", ",", "(", "-", "1", ",", ")", ")", "assert", "np", ".", "all", "(", "offsets", "[", "freq_index", ",", "offset_choice_indexes", "]", ")", "gradient_values", "=", "gradients", "[", "freq_index", ",", "offset_choice_indexes", "]", "index_of_largest_from_gradient_values", "=", "np", ".", "where", "(", "gradient_values", "==", "np", ".", "min", "(", "gradient_values", ")", ")", "[", "0", "]", "index_of_largest_offset_choice", "=", "offset_choice_indexes", "[", "index_of_largest_from_gradient_values", "]", "assert", "offsets", "[", "freq_index", ",", "index_of_largest_offset_choice", "]", "==", "1", "# Zero the others", "offsets", "[", "freq_index", ",", "offset_choice_indexes", "]", "=", "0", "offsets", "[", "freq_index", ",", "index_of_largest_offset_choice", "]", "=", "1", "last_idx", "=", "next_idx", "else", ":", "# We only have one onset in this frequency band, so the offset will be the very last sample", "offsets", "[", "freq_index", ",", ":", "]", "=", "0", "offsets", "[", "freq_index", ",", "-", "1", "]", "=", "1", "return", "offsets" ]
1daefb8de626ddff3ff7016697c3ad31d262ecd6