idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
244,000
def reset_logger ( name , level = None , handler = None ) : # Make the logger and set its level. if level is None : level = logging . INFO logger = logging . getLogger ( name ) logger . setLevel ( level ) # Make the handler and attach it. handler = handler or logging . StreamHandler ( ) handler . setFormatter ( logging . Formatter ( _DEFAULT_LOG_FORMAT ) ) # We don't use ``.addHandler``, since this logger may have already been # instantiated elsewhere with a different handler. It should only ever # have one, not many. logger . handlers = [ handler ] return logger
Make a standard python logger object with default formatter handler etc .
139
13
244,001
def adapt_logger ( logger ) : if isinstance ( logger , logging . Logger ) : return logger # Use the standard python logger created by these classes. if isinstance ( logger , ( SimpleLogger , NoOpLogger ) ) : return logger . logger # Otherwise, return whatever we were given because we can't adapt. return logger
Adapt our custom logger . BaseLogger object into a standard logging . Logger object .
72
18
244,002
def get_variation_for_experiment ( self , experiment_id ) : return self . experiment_bucket_map . get ( experiment_id , { self . VARIATION_ID_KEY : None } ) . get ( self . VARIATION_ID_KEY )
Helper method to retrieve variation ID for given experiment .
61
10
244,003
def get_numeric_value ( event_tags , logger = None ) : logger_message_debug = None numeric_metric_value = None if event_tags is None : logger_message_debug = 'Event tags is undefined.' elif not isinstance ( event_tags , dict ) : logger_message_debug = 'Event tags is not a dictionary.' elif NUMERIC_METRIC_TYPE not in event_tags : logger_message_debug = 'The numeric metric key is not in event tags.' else : numeric_metric_value = event_tags [ NUMERIC_METRIC_TYPE ] try : if isinstance ( numeric_metric_value , ( numbers . Integral , float , str ) ) : # Attempt to convert the numeric metric value to a float # (if it isn't already a float). cast_numeric_metric_value = float ( numeric_metric_value ) # If not a float after casting, then make everything else a None. # Other potential values are nan, inf, and -inf. if not isinstance ( cast_numeric_metric_value , float ) or math . isnan ( cast_numeric_metric_value ) or math . isinf ( cast_numeric_metric_value ) : logger_message_debug = 'Provided numeric value {} is in an invalid format.' . format ( numeric_metric_value ) numeric_metric_value = None else : # Handle booleans as a special case. # They are treated like an integer in the cast, but we do not want to cast this. if isinstance ( numeric_metric_value , bool ) : logger_message_debug = 'Provided numeric value is a boolean, which is an invalid format.' numeric_metric_value = None else : numeric_metric_value = cast_numeric_metric_value else : logger_message_debug = 'Numeric metric value is not in integer, float, or string form.' numeric_metric_value = None except ValueError : logger_message_debug = 'Value error while casting numeric metric value to a float.' numeric_metric_value = None # Log all potential debug messages while converting the numeric value to a float. if logger and logger_message_debug : logger . log ( enums . LogLevels . DEBUG , logger_message_debug ) # Log the final numeric metric value if numeric_metric_value is not None : if logger : logger . log ( enums . LogLevels . INFO , 'The numeric metric value {} will be sent to results.' . format ( numeric_metric_value ) ) else : if logger : logger . log ( enums . LogLevels . WARNING , 'The provided numeric metric value {} is in an invalid format and will not be sent to results.' . format ( numeric_metric_value ) ) return numeric_metric_value
A smart getter of the numeric value from the event tags .
623
13
244,004
def hash ( key , seed = 0x0 ) : key = bytearray ( xencode ( key ) ) def fmix ( h ) : h ^= h >> 16 h = ( h * 0x85ebca6b ) & 0xFFFFFFFF h ^= h >> 13 h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF h ^= h >> 16 return h length = len ( key ) nblocks = int ( length / 4 ) h1 = seed c1 = 0xcc9e2d51 c2 = 0x1b873593 # body for block_start in xrange ( 0 , nblocks * 4 , 4 ) : # ??? big endian? k1 = key [ block_start + 3 ] << 24 | key [ block_start + 2 ] << 16 | key [ block_start + 1 ] << 8 | key [ block_start + 0 ] k1 = ( c1 * k1 ) & 0xFFFFFFFF k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF # inlined ROTL32 k1 = ( c2 * k1 ) & 0xFFFFFFFF h1 ^= k1 h1 = ( h1 << 13 | h1 >> 19 ) & 0xFFFFFFFF # inlined ROTL32 h1 = ( h1 * 5 + 0xe6546b64 ) & 0xFFFFFFFF # tail tail_index = nblocks * 4 k1 = 0 tail_size = length & 3 if tail_size >= 3 : k1 ^= key [ tail_index + 2 ] << 16 if tail_size >= 2 : k1 ^= key [ tail_index + 1 ] << 8 if tail_size >= 1 : k1 ^= key [ tail_index + 0 ] if tail_size > 0 : k1 = ( k1 * c1 ) & 0xFFFFFFFF k1 = ( k1 << 15 | k1 >> 17 ) & 0xFFFFFFFF # inlined ROTL32 k1 = ( k1 * c2 ) & 0xFFFFFFFF h1 ^= k1 #finalization unsigned_val = fmix ( h1 ^ length ) if unsigned_val & 0x80000000 == 0 : return unsigned_val else : return - ( ( unsigned_val ^ 0xFFFFFFFF ) + 1 )
Implements 32bit murmur3 hash .
507
10
244,005
def hash64 ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF if unsigned_val1 & 0x8000000000000000 == 0 : signed_val1 = unsigned_val1 else : signed_val1 = - ( ( unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF ) + 1 ) unsigned_val2 = ( hash_128 >> 64 ) & 0xFFFFFFFFFFFFFFFF if unsigned_val2 & 0x8000000000000000 == 0 : signed_val2 = unsigned_val2 else : signed_val2 = - ( ( unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF ) + 1 ) return ( int ( signed_val1 ) , int ( signed_val2 ) )
Implements 64bit murmur3 hash . Returns a tuple .
182
14
244,006
def hash_bytes ( key , seed = 0x0 , x64arch = True ) : hash_128 = hash128 ( key , seed , x64arch ) bytestring = '' for i in xrange ( 0 , 16 , 1 ) : lsbyte = hash_128 & 0xFF bytestring = bytestring + str ( chr ( lsbyte ) ) hash_128 = hash_128 >> 8 return bytestring
Implements 128bit murmur3 hash . Returns a byte string .
93
15
244,007
def _generate_bucket_value ( self , bucketing_id ) : ratio = float ( self . _generate_unsigned_hash_code_32_bit ( bucketing_id ) ) / MAX_HASH_VALUE return math . floor ( ratio * MAX_TRAFFIC_VALUE )
Helper function to generate bucket value in half - closed interval [ 0 MAX_TRAFFIC_VALUE ) .
67
23
244,008
def find_bucket ( self , bucketing_id , parent_id , traffic_allocations ) : bucketing_key = BUCKETING_ID_TEMPLATE . format ( bucketing_id = bucketing_id , parent_id = parent_id ) bucketing_number = self . _generate_bucket_value ( bucketing_key ) self . config . logger . debug ( 'Assigned bucket %s to user with bucketing ID "%s".' % ( bucketing_number , bucketing_id ) ) for traffic_allocation in traffic_allocations : current_end_of_range = traffic_allocation . get ( 'endOfRange' ) if bucketing_number < current_end_of_range : return traffic_allocation . get ( 'entityId' ) return None
Determine entity based on bucket value and traffic allocations .
179
12
244,009
def bucket ( self , experiment , user_id , bucketing_id ) : if not experiment : return None # Determine if experiment is in a mutually exclusive group if experiment . groupPolicy in GROUP_POLICIES : group = self . config . get_group ( experiment . groupId ) if not group : return None user_experiment_id = self . find_bucket ( bucketing_id , experiment . groupId , group . trafficAllocation ) if not user_experiment_id : self . config . logger . info ( 'User "%s" is in no experiment.' % user_id ) return None if user_experiment_id != experiment . id : self . config . logger . info ( 'User "%s" is not in experiment "%s" of group %s.' % ( user_id , experiment . key , experiment . groupId ) ) return None self . config . logger . info ( 'User "%s" is in experiment %s of group %s.' % ( user_id , experiment . key , experiment . groupId ) ) # Bucket user if not in white-list and in group (if any) variation_id = self . find_bucket ( bucketing_id , experiment . id , experiment . trafficAllocation ) if variation_id : variation = self . config . get_variation_from_id ( experiment . key , variation_id ) self . config . logger . info ( 'User "%s" is in variation "%s" of experiment %s.' % ( user_id , variation . key , experiment . key ) ) return variation self . config . logger . info ( 'User "%s" is in no variation.' % user_id ) return None
For a given experiment and bucketing ID determines variation to be shown to user .
361
16
244,010
def _generate_key_map ( entity_list , key , entity_class ) : key_map = { } for obj in entity_list : key_map [ obj [ key ] ] = entity_class ( * * obj ) return key_map
Helper method to generate map from key to entity object for given list of dicts .
55
17
244,011
def _deserialize_audience ( audience_map ) : for audience in audience_map . values ( ) : condition_structure , condition_list = condition_helper . loads ( audience . conditions ) audience . __dict__ . update ( { 'conditionStructure' : condition_structure , 'conditionList' : condition_list } ) return audience_map
Helper method to de - serialize and populate audience map with the condition list and structure .
79
18
244,012
def get_typecast_value ( self , value , type ) : if type == entities . Variable . Type . BOOLEAN : return value == 'true' elif type == entities . Variable . Type . INTEGER : return int ( value ) elif type == entities . Variable . Type . DOUBLE : return float ( value ) else : return value
Helper method to determine actual value based on type of feature variable .
77
13
244,013
def get_experiment_from_key ( self , experiment_key ) : experiment = self . experiment_key_map . get ( experiment_key ) if experiment : return experiment self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get experiment for the provided experiment key .
100
8
244,014
def get_experiment_from_id ( self , experiment_id ) : experiment = self . experiment_id_map . get ( experiment_id ) if experiment : return experiment self . logger . error ( 'Experiment ID "%s" is not in datafile.' % experiment_id ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get experiment for the provided experiment ID .
100
8
244,015
def get_group ( self , group_id ) : group = self . group_id_map . get ( group_id ) if group : return group self . logger . error ( 'Group ID "%s" is not in datafile.' % group_id ) self . error_handler . handle_error ( exceptions . InvalidGroupException ( enums . Errors . INVALID_GROUP_ID_ERROR ) ) return None
Get group for the provided group ID .
90
8
244,016
def get_audience ( self , audience_id ) : audience = self . audience_id_map . get ( audience_id ) if audience : return audience self . logger . error ( 'Audience ID "%s" is not in datafile.' % audience_id ) self . error_handler . handle_error ( exceptions . InvalidAudienceException ( ( enums . Errors . INVALID_AUDIENCE_ERROR ) ) )
Get audience object for the provided audience ID .
92
9
244,017
def get_variation_from_key ( self , experiment_key , variation_key ) : variation_map = self . variation_key_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_key ) if variation : return variation else : self . logger . error ( 'Variation key "%s" is not in datafile.' % variation_key ) self . error_handler . handle_error ( exceptions . InvalidVariationException ( enums . Errors . INVALID_VARIATION_ERROR ) ) return None self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get variation given experiment and variation key .
184
8
244,018
def get_variation_from_id ( self , experiment_key , variation_id ) : variation_map = self . variation_id_map . get ( experiment_key ) if variation_map : variation = variation_map . get ( variation_id ) if variation : return variation else : self . logger . error ( 'Variation ID "%s" is not in datafile.' % variation_id ) self . error_handler . handle_error ( exceptions . InvalidVariationException ( enums . Errors . INVALID_VARIATION_ERROR ) ) return None self . logger . error ( 'Experiment key "%s" is not in datafile.' % experiment_key ) self . error_handler . handle_error ( exceptions . InvalidExperimentException ( enums . Errors . INVALID_EXPERIMENT_KEY_ERROR ) ) return None
Get variation given experiment and variation ID .
184
8
244,019
def get_event ( self , event_key ) : event = self . event_key_map . get ( event_key ) if event : return event self . logger . error ( 'Event "%s" is not in datafile.' % event_key ) self . error_handler . handle_error ( exceptions . InvalidEventException ( enums . Errors . INVALID_EVENT_KEY_ERROR ) ) return None
Get event for the provided event key .
90
8
244,020
def get_attribute_id ( self , attribute_key ) : attribute = self . attribute_key_map . get ( attribute_key ) has_reserved_prefix = attribute_key . startswith ( RESERVED_ATTRIBUTE_PREFIX ) if attribute : if has_reserved_prefix : self . logger . warning ( ( 'Attribute %s unexpectedly has reserved prefix %s; using attribute ID ' 'instead of reserved attribute name.' % ( attribute_key , RESERVED_ATTRIBUTE_PREFIX ) ) ) return attribute . id if has_reserved_prefix : return attribute_key self . logger . error ( 'Attribute "%s" is not in datafile.' % attribute_key ) self . error_handler . handle_error ( exceptions . InvalidAttributeException ( enums . Errors . INVALID_ATTRIBUTE_ERROR ) ) return None
Get attribute ID for the provided attribute key .
194
9
244,021
def get_feature_from_key ( self , feature_key ) : feature = self . feature_key_map . get ( feature_key ) if feature : return feature self . logger . error ( 'Feature "%s" is not in datafile.' % feature_key ) return None
Get feature for the provided feature key .
61
8
244,022
def get_rollout_from_id ( self , rollout_id ) : layer = self . rollout_id_map . get ( rollout_id ) if layer : return layer self . logger . error ( 'Rollout with ID "%s" is not in datafile.' % rollout_id ) return None
Get rollout for the provided ID .
65
7
244,023
def get_variable_value_for_variation ( self , variable , variation ) : if not variable or not variation : return None if variation . id not in self . variation_variable_usage_map : self . logger . error ( 'Variation with ID "%s" is not in the datafile.' % variation . id ) return None # Get all variable usages for the given variation variable_usages = self . variation_variable_usage_map [ variation . id ] # Find usage in given variation variable_usage = None if variable_usages : variable_usage = variable_usages . get ( variable . id ) if variable_usage : variable_value = variable_usage . value self . logger . info ( 'Value for variable "%s" for variation "%s" is "%s".' % ( variable . key , variation . key , variable_value ) ) else : variable_value = variable . defaultValue self . logger . info ( 'Variable "%s" is not used in variation "%s". Assigning default value "%s".' % ( variable . key , variation . key , variable_value ) ) return variable_value
Get the variable value for the given variation .
241
9
244,024
def get_variable_for_feature ( self , feature_key , variable_key ) : feature = self . feature_key_map . get ( feature_key ) if not feature : self . logger . error ( 'Feature with key "%s" not found in the datafile.' % feature_key ) return None if variable_key not in feature . variables : self . logger . error ( 'Variable with key "%s" not found in the datafile.' % variable_key ) return None return feature . variables . get ( variable_key )
Get the variable with the given variable key for the given feature .
115
13
244,025
def set_forced_variation ( self , experiment_key , user_id , variation_key ) : experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : # The invalid experiment key will be logged inside this call. return False experiment_id = experiment . id if variation_key is None : if user_id in self . forced_variation_map : experiment_to_variation_map = self . forced_variation_map . get ( user_id ) if experiment_id in experiment_to_variation_map : del ( self . forced_variation_map [ user_id ] [ experiment_id ] ) self . logger . debug ( 'Variation mapped to experiment "%s" has been removed for user "%s".' % ( experiment_key , user_id ) ) else : self . logger . debug ( 'Nothing to remove. Variation mapped to experiment "%s" for user "%s" does not exist.' % ( experiment_key , user_id ) ) else : self . logger . debug ( 'Nothing to remove. User "%s" does not exist in the forced variation map.' % user_id ) return True if not validator . is_non_empty_string ( variation_key ) : self . logger . debug ( 'Variation key is invalid.' ) return False forced_variation = self . get_variation_from_key ( experiment_key , variation_key ) if not forced_variation : # The invalid variation key will be logged inside this call. return False variation_id = forced_variation . id if user_id not in self . forced_variation_map : self . forced_variation_map [ user_id ] = { experiment_id : variation_id } else : self . forced_variation_map [ user_id ] [ experiment_id ] = variation_id self . logger . debug ( 'Set variation "%s" for experiment "%s" and user "%s" in the forced variation map.' % ( variation_id , experiment_id , user_id ) ) return True
Sets users to a map of experiments to forced variations .
450
12
244,026
def get_forced_variation ( self , experiment_key , user_id ) : if user_id not in self . forced_variation_map : self . logger . debug ( 'User "%s" is not in the forced variation map.' % user_id ) return None experiment = self . get_experiment_from_key ( experiment_key ) if not experiment : # The invalid experiment key will be logged inside this call. return None experiment_to_variation_map = self . forced_variation_map . get ( user_id ) if not experiment_to_variation_map : self . logger . debug ( 'No experiment "%s" mapped to user "%s" in the forced variation map.' % ( experiment_key , user_id ) ) return None variation_id = experiment_to_variation_map . get ( experiment . id ) if variation_id is None : self . logger . debug ( 'No variation mapped to experiment "%s" in the forced variation map.' % experiment_key ) return None variation = self . get_variation_from_id ( experiment_key , variation_id ) self . logger . debug ( 'Variation "%s" is mapped to experiment "%s" and user "%s" in the forced variation map' % ( variation . key , experiment_key , user_id ) ) return variation
Gets the forced variation key for the given user and experiment .
289
13
244,027
def dispatch_event ( event ) : try : if event . http_verb == enums . HTTPVerbs . GET : requests . get ( event . url , params = event . params , timeout = REQUEST_TIMEOUT ) . raise_for_status ( ) elif event . http_verb == enums . HTTPVerbs . POST : requests . post ( event . url , data = json . dumps ( event . params ) , headers = event . headers , timeout = REQUEST_TIMEOUT ) . raise_for_status ( ) except request_exception . RequestException as error : logging . error ( 'Dispatch event failed. Error: %s' % str ( error ) )
Dispatch the event being represented by the Event object .
145
10
244,028
def _validate_instantiation_options ( self , datafile , skip_json_validation ) : if not skip_json_validation and not validator . is_datafile_valid ( datafile ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'datafile' ) ) if not validator . is_event_dispatcher_valid ( self . event_dispatcher ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'event_dispatcher' ) ) if not validator . is_logger_valid ( self . logger ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'logger' ) ) if not validator . is_error_handler_valid ( self . error_handler ) : raise exceptions . InvalidInputException ( enums . Errors . INVALID_INPUT_ERROR . format ( 'error_handler' ) )
Helper method to validate all instantiation parameters .
229
9
244,029
def _validate_user_inputs ( self , attributes = None , event_tags = None ) : if attributes and not validator . are_attributes_valid ( attributes ) : self . logger . error ( 'Provided attributes are in an invalid format.' ) self . error_handler . handle_error ( exceptions . InvalidAttributeException ( enums . Errors . INVALID_ATTRIBUTE_FORMAT ) ) return False if event_tags and not validator . are_event_tags_valid ( event_tags ) : self . logger . error ( 'Provided event tags are in an invalid format.' ) self . error_handler . handle_error ( exceptions . InvalidEventTagException ( enums . Errors . INVALID_EVENT_TAG_FORMAT ) ) return False return True
Helper method to validate user inputs .
172
7
244,030
def _send_impression_event ( self , experiment , variation , user_id , attributes ) : impression_event = self . event_builder . create_impression_event ( experiment , variation . id , user_id , attributes ) self . logger . debug ( 'Dispatching impression event to URL %s with params %s.' % ( impression_event . url , impression_event . params ) ) try : self . event_dispatcher . dispatch_event ( impression_event ) except : self . logger . exception ( 'Unable to dispatch impression event!' ) self . notification_center . send_notifications ( enums . NotificationTypes . ACTIVATE , experiment , user_id , attributes , variation , impression_event )
Helper method to send impression event .
156
7
244,031
def _get_feature_variable_for_type ( self , feature_key , variable_key , variable_type , user_id , attributes ) : if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'feature_key' ) ) return None if not validator . is_non_empty_string ( variable_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'variable_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None if not self . _validate_user_inputs ( attributes ) : return None feature_flag = self . config . get_feature_from_key ( feature_key ) if not feature_flag : return None variable = self . config . get_variable_for_feature ( feature_key , variable_key ) if not variable : return None # Return None if type differs if variable . type != variable_type : self . logger . warning ( 'Requested variable type "%s", but variable is of type "%s". ' 'Use correct API to retrieve value. Returning None.' % ( variable_type , variable . type ) ) return None feature_enabled = False source_info = { } variable_value = variable . defaultValue decision = self . decision_service . get_variation_for_feature ( feature_flag , user_id , attributes ) if decision . variation : feature_enabled = decision . variation . featureEnabled if feature_enabled : variable_value = self . config . get_variable_value_for_variation ( variable , decision . variation ) self . logger . info ( 'Got variable value "%s" for variable "%s" of feature flag "%s".' % ( variable_value , variable_key , feature_key ) ) else : self . logger . info ( 'Feature "%s" for variation "%s" is not enabled. ' 'Returning the default variable value "%s".' % ( feature_key , decision . variation . key , variable_value ) ) else : self . logger . info ( 'User "%s" is not in any variation or rollout rule. ' 'Returning default value for variable "%s" of feature flag "%s".' % ( user_id , variable_key , feature_key ) ) if decision . source == enums . DecisionSources . FEATURE_TEST : source_info = { 'experiment_key' : decision . experiment . key , 'variation_key' : decision . variation . key } try : actual_value = self . config . get_typecast_value ( variable_value , variable_type ) except : self . logger . error ( 'Unable to cast value. Returning None.' ) actual_value = None self . notification_center . send_notifications ( enums . NotificationTypes . DECISION , enums . DecisionNotificationTypes . FEATURE_VARIABLE , user_id , attributes or { } , { 'feature_key' : feature_key , 'feature_enabled' : feature_enabled , 'source' : decision . source , 'variable_key' : variable_key , 'variable_value' : actual_value , 'variable_type' : variable_type , 'source_info' : source_info } ) return actual_value
Helper method to determine value for a certain variable attached to a feature flag based on type of variable .
765
20
244,032
def activate ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'activate' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None variation_key = self . get_variation ( experiment_key , user_id , attributes ) if not variation_key : self . logger . info ( 'Not activating user "%s".' % user_id ) return None experiment = self . config . get_experiment_from_key ( experiment_key ) variation = self . config . get_variation_from_key ( experiment_key , variation_key ) # Create and dispatch impression event self . logger . info ( 'Activating user "%s" in experiment "%s".' % ( user_id , experiment . key ) ) self . _send_impression_event ( experiment , variation , user_id , attributes ) return variation . key
Buckets visitor and sends impression event to Optimizely .
300
13
244,033
def track ( self , event_key , user_id , attributes = None , event_tags = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'track' ) ) return if not validator . is_non_empty_string ( event_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'event_key' ) ) return if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return if not self . _validate_user_inputs ( attributes , event_tags ) : return event = self . config . get_event ( event_key ) if not event : self . logger . info ( 'Not tracking user "%s" for event "%s".' % ( user_id , event_key ) ) return conversion_event = self . event_builder . create_conversion_event ( event_key , user_id , attributes , event_tags ) self . logger . info ( 'Tracking event "%s" for user "%s".' % ( event_key , user_id ) ) self . logger . debug ( 'Dispatching conversion event to URL %s with params %s.' % ( conversion_event . url , conversion_event . params ) ) try : self . event_dispatcher . dispatch_event ( conversion_event ) except : self . logger . exception ( 'Unable to dispatch conversion event!' ) self . notification_center . send_notifications ( enums . NotificationTypes . TRACK , event_key , user_id , attributes , event_tags , conversion_event )
Send conversion event to Optimizely .
391
8
244,034
def get_variation ( self , experiment_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None experiment = self . config . get_experiment_from_key ( experiment_key ) variation_key = None if not experiment : self . logger . info ( 'Experiment key "%s" is invalid. Not activating user "%s".' % ( experiment_key , user_id ) ) return None if not self . _validate_user_inputs ( attributes ) : return None variation = self . decision_service . get_variation ( experiment , user_id , attributes ) if variation : variation_key = variation . key if self . config . is_feature_experiment ( experiment . id ) : decision_notification_type = enums . DecisionNotificationTypes . FEATURE_TEST else : decision_notification_type = enums . DecisionNotificationTypes . AB_TEST self . notification_center . send_notifications ( enums . NotificationTypes . DECISION , decision_notification_type , user_id , attributes or { } , { 'experiment_key' : experiment_key , 'variation_key' : variation_key } ) return variation_key
Gets variation where user will be bucketed .
391
10
244,035
def is_feature_enabled ( self , feature_key , user_id , attributes = None ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'is_feature_enabled' ) ) return False if not validator . is_non_empty_string ( feature_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'feature_key' ) ) return False if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return False if not self . _validate_user_inputs ( attributes ) : return False feature = self . config . get_feature_from_key ( feature_key ) if not feature : return False feature_enabled = False source_info = { } decision = self . decision_service . get_variation_for_feature ( feature , user_id , attributes ) is_source_experiment = decision . source == enums . DecisionSources . FEATURE_TEST if decision . variation : if decision . variation . featureEnabled is True : feature_enabled = True # Send event if Decision came from an experiment. if is_source_experiment : source_info = { 'experiment_key' : decision . experiment . key , 'variation_key' : decision . variation . key } self . _send_impression_event ( decision . experiment , decision . variation , user_id , attributes ) if feature_enabled : self . logger . info ( 'Feature "%s" is enabled for user "%s".' % ( feature_key , user_id ) ) else : self . logger . info ( 'Feature "%s" is not enabled for user "%s".' % ( feature_key , user_id ) ) self . notification_center . send_notifications ( enums . NotificationTypes . DECISION , enums . DecisionNotificationTypes . FEATURE , user_id , attributes or { } , { 'feature_key' : feature_key , 'feature_enabled' : feature_enabled , 'source' : decision . source , 'source_info' : source_info } ) return feature_enabled
Returns true if the feature is enabled for the given user .
502
12
244,036
def get_enabled_features ( self , user_id , attributes = None ) : enabled_features = [ ] if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_enabled_features' ) ) return enabled_features if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return enabled_features if not self . _validate_user_inputs ( attributes ) : return enabled_features for feature in self . config . feature_key_map . values ( ) : if self . is_feature_enabled ( feature . key , user_id , attributes ) : enabled_features . append ( feature . key ) return enabled_features
Returns the list of features that are enabled for the user .
185
12
244,037
def get_feature_variable_boolean ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . BOOLEAN return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain boolean variable attached to a feature flag .
75
13
244,038
def get_feature_variable_double ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . DOUBLE return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain double variable attached to a feature flag .
73
13
244,039
def get_feature_variable_integer ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . INTEGER return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain integer variable attached to a feature flag .
73
13
244,040
def get_feature_variable_string ( self , feature_key , variable_key , user_id , attributes = None ) : variable_type = entities . Variable . Type . STRING return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes )
Returns value for a certain string variable attached to a feature .
72
12
244,041
def set_forced_variation ( self , experiment_key , user_id , variation_key ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'set_forced_variation' ) ) return False if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return False if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return False return self . config . set_forced_variation ( experiment_key , user_id , variation_key )
Force a user into a variation for a given experiment .
184
11
244,042
def get_forced_variation ( self , experiment_key , user_id ) : if not self . is_valid : self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'get_forced_variation' ) ) return None if not validator . is_non_empty_string ( experiment_key ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) ) return None if not isinstance ( user_id , string_types ) : self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'user_id' ) ) return None forced_variation = self . config . get_forced_variation ( experiment_key , user_id ) return forced_variation . key if forced_variation else None
Gets the forced variation for a given user and experiment .
194
12
244,043
def is_user_in_experiment ( config , experiment , attributes , logger ) : audience_conditions = experiment . getAudienceConditionsOrIds ( ) logger . debug ( audience_logs . EVALUATING_AUDIENCES_COMBINED . format ( experiment . key , json . dumps ( audience_conditions ) ) ) # Return True in case there are no audiences if audience_conditions is None or audience_conditions == [ ] : logger . info ( audience_logs . AUDIENCE_EVALUATION_RESULT_COMBINED . format ( experiment . key , 'TRUE' ) ) return True if attributes is None : attributes = { } def evaluate_custom_attr ( audienceId , index ) : audience = config . get_audience ( audienceId ) custom_attr_condition_evaluator = condition_helper . CustomAttributeConditionEvaluator ( audience . conditionList , attributes , logger ) return custom_attr_condition_evaluator . evaluate ( index ) def evaluate_audience ( audienceId ) : audience = config . get_audience ( audienceId ) if audience is None : return None logger . debug ( audience_logs . EVALUATING_AUDIENCE . format ( audienceId , audience . conditions ) ) result = condition_tree_evaluator . evaluate ( audience . conditionStructure , lambda index : evaluate_custom_attr ( audienceId , index ) ) result_str = str ( result ) . upper ( ) if result is not None else 'UNKNOWN' logger . info ( audience_logs . AUDIENCE_EVALUATION_RESULT . format ( audienceId , result_str ) ) return result eval_result = condition_tree_evaluator . evaluate ( audience_conditions , evaluate_audience ) eval_result = eval_result or False logger . info ( audience_logs . AUDIENCE_EVALUATION_RESULT_COMBINED . format ( experiment . key , str ( eval_result ) . upper ( ) ) ) return eval_result
Determine for given experiment if user satisfies the audiences for the experiment .
445
15
244,044
def _get_common_params ( self , user_id , attributes ) : commonParams = { } commonParams [ self . EventParams . PROJECT_ID ] = self . _get_project_id ( ) commonParams [ self . EventParams . ACCOUNT_ID ] = self . _get_account_id ( ) visitor = { } visitor [ self . EventParams . END_USER_ID ] = user_id visitor [ self . EventParams . SNAPSHOTS ] = [ ] commonParams [ self . EventParams . USERS ] = [ ] commonParams [ self . EventParams . USERS ] . append ( visitor ) commonParams [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . ATTRIBUTES ] = self . _get_attributes ( attributes ) commonParams [ self . EventParams . SOURCE_SDK_TYPE ] = 'python-sdk' commonParams [ self . EventParams . ENRICH_DECISIONS ] = True commonParams [ self . EventParams . SOURCE_SDK_VERSION ] = version . __version__ commonParams [ self . EventParams . ANONYMIZE_IP ] = self . _get_anonymize_ip ( ) commonParams [ self . EventParams . REVISION ] = self . _get_revision ( ) return commonParams
Get params which are used same in both conversion and impression events .
313
13
244,045
def _get_required_params_for_impression ( self , experiment , variation_id ) : snapshot = { } snapshot [ self . EventParams . DECISIONS ] = [ { self . EventParams . EXPERIMENT_ID : experiment . id , self . EventParams . VARIATION_ID : variation_id , self . EventParams . CAMPAIGN_ID : experiment . layerId } ] snapshot [ self . EventParams . EVENTS ] = [ { self . EventParams . EVENT_ID : experiment . layerId , self . EventParams . TIME : self . _get_time ( ) , self . EventParams . KEY : 'campaign_activated' , self . EventParams . UUID : str ( uuid . uuid4 ( ) ) } ] return snapshot
Get parameters that are required for the impression event to register .
175
12
244,046
def _get_required_params_for_conversion ( self , event_key , event_tags ) : snapshot = { } event_dict = { self . EventParams . EVENT_ID : self . config . get_event ( event_key ) . id , self . EventParams . TIME : self . _get_time ( ) , self . EventParams . KEY : event_key , self . EventParams . UUID : str ( uuid . uuid4 ( ) ) } if event_tags : revenue_value = event_tag_utils . get_revenue_value ( event_tags ) if revenue_value is not None : event_dict [ event_tag_utils . REVENUE_METRIC_TYPE ] = revenue_value numeric_value = event_tag_utils . get_numeric_value ( event_tags , self . config . logger ) if numeric_value is not None : event_dict [ event_tag_utils . NUMERIC_METRIC_TYPE ] = numeric_value if len ( event_tags ) > 0 : event_dict [ self . EventParams . TAGS ] = event_tags snapshot [ self . EventParams . EVENTS ] = [ event_dict ] return snapshot
Get parameters that are required for the conversion event to register .
268
12
244,047
def create_impression_event ( self , experiment , variation_id , user_id , attributes ) : params = self . _get_common_params ( user_id , attributes ) impression_params = self . _get_required_params_for_impression ( experiment , variation_id ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ] . append ( impression_params ) return Event ( self . EVENTS_URL , params , http_verb = self . HTTP_VERB , headers = self . HTTP_HEADERS )
Create impression Event to be sent to the logging endpoint .
127
11
244,048
def create_conversion_event ( self , event_key , user_id , attributes , event_tags ) : params = self . _get_common_params ( user_id , attributes ) conversion_params = self . _get_required_params_for_conversion ( event_key , event_tags ) params [ self . EventParams . USERS ] [ 0 ] [ self . EventParams . SNAPSHOTS ] . append ( conversion_params ) return Event ( self . EVENTS_URL , params , http_verb = self . HTTP_VERB , headers = self . HTTP_HEADERS )
Create conversion Event to be sent to the logging endpoint .
131
11
244,049
def _audience_condition_deserializer ( obj_dict ) : return [ obj_dict . get ( 'name' ) , obj_dict . get ( 'value' ) , obj_dict . get ( 'type' ) , obj_dict . get ( 'match' ) ]
Deserializer defining how dict objects need to be decoded for audience conditions .
62
16
244,050
def _get_condition_json ( self , index ) : condition = self . condition_data [ index ] condition_log = { 'name' : condition [ 0 ] , 'value' : condition [ 1 ] , 'type' : condition [ 2 ] , 'match' : condition [ 3 ] } return json . dumps ( condition_log )
Method to generate json for logging audience condition .
73
9
244,051
def is_value_type_valid_for_exact_conditions ( self , value ) : # No need to check for bool since bool is a subclass of int if isinstance ( value , string_types ) or isinstance ( value , ( numbers . Integral , float ) ) : return True return False
Method to validate if the value is valid for exact match type evaluation .
66
14
244,052
def exists_evaluator ( self , index ) : attr_name = self . condition_data [ index ] [ 0 ] return self . attributes . get ( attr_name ) is not None
Evaluate the given exists match condition for the user attributes .
43
13
244,053
def greater_than_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not validator . is_finite_number ( condition_value ) : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_VALUE . format ( self . _get_condition_json ( index ) ) ) return None if not self . is_value_a_number ( user_value ) : self . logger . warning ( audience_logs . UNEXPECTED_TYPE . format ( self . _get_condition_json ( index ) , type ( user_value ) , condition_name ) ) return None if not validator . is_finite_number ( user_value ) : self . logger . warning ( audience_logs . INFINITE_ATTRIBUTE_VALUE . format ( self . _get_condition_json ( index ) , condition_name ) ) return None return user_value > condition_value
Evaluate the given greater than match condition for the user attributes .
243
14
244,054
def substring_evaluator ( self , index ) : condition_name = self . condition_data [ index ] [ 0 ] condition_value = self . condition_data [ index ] [ 1 ] user_value = self . attributes . get ( condition_name ) if not isinstance ( condition_value , string_types ) : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_VALUE . format ( self . _get_condition_json ( index ) , ) ) return None if not isinstance ( user_value , string_types ) : self . logger . warning ( audience_logs . UNEXPECTED_TYPE . format ( self . _get_condition_json ( index ) , type ( user_value ) , condition_name ) ) return None return condition_value in user_value
Evaluate the given substring match condition for the given user attributes .
177
15
244,055
def evaluate ( self , index ) : if self . condition_data [ index ] [ 2 ] != self . CUSTOM_ATTRIBUTE_CONDITION_TYPE : self . logger . warning ( audience_logs . UNKNOWN_CONDITION_TYPE . format ( self . _get_condition_json ( index ) ) ) return None condition_match = self . condition_data [ index ] [ 3 ] if condition_match is None : condition_match = ConditionMatchTypes . EXACT if condition_match not in self . EVALUATORS_BY_MATCH_TYPE : self . logger . warning ( audience_logs . UNKNOWN_MATCH_TYPE . format ( self . _get_condition_json ( index ) ) ) return None if condition_match != ConditionMatchTypes . EXISTS : attribute_key = self . condition_data [ index ] [ 0 ] if attribute_key not in self . attributes : self . logger . debug ( audience_logs . MISSING_ATTRIBUTE_VALUE . format ( self . _get_condition_json ( index ) , attribute_key ) ) return None if self . attributes . get ( attribute_key ) is None : self . logger . debug ( audience_logs . NULL_ATTRIBUTE_VALUE . format ( self . _get_condition_json ( index ) , attribute_key ) ) return None return self . EVALUATORS_BY_MATCH_TYPE [ condition_match ] ( self , index )
Given a custom attribute audience condition and user attributes evaluate the condition against the attributes .
324
16
244,056
def object_hook ( self , object_dict ) : instance = self . decoder ( object_dict ) self . condition_list . append ( instance ) self . index += 1 return self . index
Hook which when passed into a json . JSONDecoder will replace each dict in a json string with its index and convert the dict to an object as defined by the passed in condition_decoder . The newly created condition object is appended to the conditions_list .
42
55
244,057
def _get_bucketing_id ( self , user_id , attributes ) : attributes = attributes or { } bucketing_id = attributes . get ( enums . ControlAttributes . BUCKETING_ID ) if bucketing_id is not None : if isinstance ( bucketing_id , string_types ) : return bucketing_id self . logger . warning ( 'Bucketing ID attribute is not a string. Defaulted to user_id.' ) return user_id
Helper method to determine bucketing ID for the user .
103
11
244,058
def get_forced_variation ( self , experiment , user_id ) : forced_variations = experiment . forcedVariations if forced_variations and user_id in forced_variations : variation_key = forced_variations . get ( user_id ) variation = self . config . get_variation_from_key ( experiment . key , variation_key ) if variation : self . logger . info ( 'User "%s" is forced in variation "%s".' % ( user_id , variation_key ) ) return variation return None
Determine if a user is forced into a variation for the given experiment and return that variation .
117
20
244,059
def get_stored_variation ( self , experiment , user_profile ) : user_id = user_profile . user_id variation_id = user_profile . get_variation_for_experiment ( experiment . id ) if variation_id : variation = self . config . get_variation_from_id ( experiment . key , variation_id ) if variation : self . logger . info ( 'Found a stored decision. User "%s" is in variation "%s" of experiment "%s".' % ( user_id , variation . key , experiment . key ) ) return variation return None
Determine if the user has a stored variation available for the given experiment and return that .
129
19
244,060
def get_variation ( self , experiment , user_id , attributes , ignore_user_profile = False ) : # Check if experiment is running if not experiment_helper . is_experiment_running ( experiment ) : self . logger . info ( 'Experiment "%s" is not running.' % experiment . key ) return None # Check if the user is forced into a variation variation = self . config . get_forced_variation ( experiment . key , user_id ) if variation : return variation # Check to see if user is white-listed for a certain variation variation = self . get_forced_variation ( experiment , user_id ) if variation : return variation # Check to see if user has a decision available for the given experiment user_profile = UserProfile ( user_id ) if not ignore_user_profile and self . user_profile_service : try : retrieved_profile = self . user_profile_service . lookup ( user_id ) except : self . logger . exception ( 'Unable to retrieve user profile for user "%s" as lookup failed.' % user_id ) retrieved_profile = None if validator . is_user_profile_valid ( retrieved_profile ) : user_profile = UserProfile ( * * retrieved_profile ) variation = self . get_stored_variation ( experiment , user_profile ) if variation : return variation else : self . logger . warning ( 'User profile has invalid format.' ) # Bucket user and store the new decision if not audience_helper . is_user_in_experiment ( self . config , experiment , attributes , self . logger ) : self . logger . info ( 'User "%s" does not meet conditions to be in experiment "%s".' % ( user_id , experiment . key ) ) return None # Determine bucketing ID to be used bucketing_id = self . _get_bucketing_id ( user_id , attributes ) variation = self . bucketer . bucket ( experiment , user_id , bucketing_id ) if variation : # Store this new decision and return the variation for the user if not ignore_user_profile and self . user_profile_service : try : user_profile . save_variation_for_experiment ( experiment . id , variation . id ) self . user_profile_service . save ( user_profile . __dict__ ) except : self . logger . exception ( 'Unable to save user profile for user "%s".' % user_id ) return variation return None
Top - level function to help determine variation user should be put in .
533
14
244,061
def get_experiment_in_group ( self , group , bucketing_id ) : experiment_id = self . bucketer . find_bucket ( bucketing_id , group . id , group . trafficAllocation ) if experiment_id : experiment = self . config . get_experiment_from_id ( experiment_id ) if experiment : self . logger . info ( 'User with bucketing ID "%s" is in experiment %s of group %s.' % ( bucketing_id , experiment . key , group . id ) ) return experiment self . logger . info ( 'User with bucketing ID "%s" is not in any experiments of group %s.' % ( bucketing_id , group . id ) ) return None
Determine which experiment in the group the user is bucketed into .
158
15
244,062
def add_notification_listener ( self , notification_type , notification_callback ) : if notification_type not in self . notifications : self . notifications [ notification_type ] = [ ( self . notification_id , notification_callback ) ] else : if reduce ( lambda a , b : a + 1 , filter ( lambda tup : tup [ 1 ] == notification_callback , self . notifications [ notification_type ] ) , 0 ) > 0 : return - 1 self . notifications [ notification_type ] . append ( ( self . notification_id , notification_callback ) ) ret_val = self . notification_id self . notification_id += 1 return ret_val
Add a notification callback to the notification center .
143
9
244,063
def remove_notification_listener ( self , notification_id ) : for v in self . notifications . values ( ) : toRemove = list ( filter ( lambda tup : tup [ 0 ] == notification_id , v ) ) if len ( toRemove ) > 0 : v . remove ( toRemove [ 0 ] ) return True return False
Remove a previously added notification callback .
74
7
244,064
def send_notifications ( self , notification_type , * args ) : if notification_type in self . notifications : for notification_id , callback in self . notifications [ notification_type ] : try : callback ( * args ) except : self . logger . exception ( 'Problem calling notify callback!' )
Fires off the notification for the specific event . Uses var args to pass in a arbitrary list of parameter according to which notification type was fired .
63
29
244,065
def and_evaluator ( conditions , leaf_evaluator ) : saw_null_result = False for condition in conditions : result = evaluate ( condition , leaf_evaluator ) if result is False : return False if result is None : saw_null_result = True return None if saw_null_result else True
Evaluates a list of conditions as if the evaluator had been applied to each entry and the results AND - ed together .
69
27
244,066
def not_evaluator ( conditions , leaf_evaluator ) : if not len ( conditions ) > 0 : return None result = evaluate ( conditions [ 0 ] , leaf_evaluator ) return None if result is None else not result
Evaluates a list of conditions as if the evaluator had been applied to a single entry and NOT was applied to the result .
51
28
244,067
def evaluate ( conditions , leaf_evaluator ) : if isinstance ( conditions , list ) : if conditions [ 0 ] in list ( EVALUATORS_BY_OPERATOR_TYPE . keys ( ) ) : return EVALUATORS_BY_OPERATOR_TYPE [ conditions [ 0 ] ] ( conditions [ 1 : ] , leaf_evaluator ) else : # assume OR when operator is not explicit. return EVALUATORS_BY_OPERATOR_TYPE [ ConditionOperatorTypes . OR ] ( conditions , leaf_evaluator ) leaf_condition = conditions return leaf_evaluator ( leaf_condition )
Top level method to evaluate conditions .
136
7
244,068
def data_objet_class ( data_mode = 'value' , time_mode = 'framewise' ) : classes_table = { ( 'value' , 'global' ) : GlobalValueObject , ( 'value' , 'event' ) : EventValueObject , ( 'value' , 'segment' ) : SegmentValueObject , ( 'value' , 'framewise' ) : FrameValueObject , ( 'label' , 'global' ) : GlobalLabelObject , ( 'label' , 'event' ) : EventLabelObject , ( 'label' , 'segment' ) : SegmentLabelObject , ( 'label' , 'framewise' ) : FrameLabelObject } try : return classes_table [ ( data_mode , time_mode ) ] except KeyError as e : raise ValueError ( 'Wrong arguments' )
Factory function for Analyzer result
185
6
244,069
def JSON_NumpyArrayEncoder ( obj ) : if isinstance ( obj , np . ndarray ) : return { 'numpyArray' : obj . tolist ( ) , 'dtype' : obj . dtype . __str__ ( ) } elif isinstance ( obj , np . generic ) : return np . asscalar ( obj ) else : print type ( obj ) raise TypeError ( repr ( obj ) + " is not JSON serializable" )
Define Specialize JSON encoder for numpy array
101
11
244,070
def render ( self ) : fig , ax = plt . subplots ( ) self . data_object . _render_plot ( ax ) return fig
Render a matplotlib figure from the analyzer result
33
11
244,071
def new_result ( self , data_mode = 'value' , time_mode = 'framewise' ) : from datetime import datetime result = AnalyzerResult ( data_mode = data_mode , time_mode = time_mode ) # Automatically write known metadata result . id_metadata . date = datetime . now ( ) . replace ( microsecond = 0 ) . isoformat ( ' ' ) result . id_metadata . version = timeside . core . __version__ result . id_metadata . author = 'TimeSide' result . id_metadata . id = self . id ( ) result . id_metadata . name = self . name ( ) result . id_metadata . description = self . description ( ) result . id_metadata . unit = self . unit ( ) result . id_metadata . proc_uuid = self . uuid ( ) result . audio_metadata . uri = self . mediainfo ( ) [ 'uri' ] result . audio_metadata . sha1 = self . mediainfo ( ) [ 'sha1' ] result . audio_metadata . start = self . mediainfo ( ) [ 'start' ] result . audio_metadata . duration = self . mediainfo ( ) [ 'duration' ] result . audio_metadata . is_segment = self . mediainfo ( ) [ 'is_segment' ] result . audio_metadata . channels = self . channels ( ) result . parameters = Parameters ( self . get_parameters ( ) ) if time_mode == 'framewise' : result . data_object . frame_metadata . samplerate = self . result_samplerate result . data_object . frame_metadata . blocksize = self . result_blocksize result . data_object . frame_metadata . stepsize = self . result_stepsize return result
Create a new result
396
4
244,072
def downmix_to_mono ( process_func ) : import functools @ functools . wraps ( process_func ) def wrapper ( analyzer , frames , eod ) : # Pre-processing if frames . ndim > 1 : downmix_frames = frames . mean ( axis = - 1 ) else : downmix_frames = frames # Processing process_func ( analyzer , downmix_frames , eod ) return frames , eod return wrapper
Pre - processing decorator that downmixes frames from multi - channel to mono
99
16
244,073
def frames_adapter ( process_func ) : import functools import numpy as np class framesBuffer ( object ) : def __init__ ( self , blocksize , stepsize ) : self . blocksize = blocksize self . stepsize = stepsize self . buffer = None def frames ( self , frames , eod ) : if self . buffer is not None : stack = np . concatenate ( [ self . buffer , frames ] ) else : stack = frames . copy ( ) stack_length = len ( stack ) nb_frames = ( stack_length - self . blocksize + self . stepsize ) // self . stepsize nb_frames = max ( nb_frames , 0 ) frames_length = nb_frames * self . stepsize + self . blocksize - self . stepsize last_block_size = stack_length - frames_length if eod : # Final zeropadding pad_shape = tuple ( self . blocksize - last_block_size if i == 0 else x for i , x in enumerate ( frames . shape ) ) stack = np . concatenate ( [ stack , np . zeros ( pad_shape , dtype = frames . dtype ) ] ) nb_frames += 1 self . buffer = stack [ nb_frames * self . stepsize : ] eod_list = np . repeat ( False , nb_frames ) if eod and len ( eod_list ) : eod_list [ - 1 ] = eod for index , eod in zip ( xrange ( 0 , nb_frames * self . stepsize , self . stepsize ) , eod_list ) : yield ( stack [ index : index + self . blocksize ] , eod ) aubio_analyzers = [ 'aubio_melenergy' , 'aubio_mfcc' , 'aubio_pitch' , 'aubio_specdesc' , 'aubio_temporal' ] @ functools . wraps ( process_func ) def wrapper ( analyzer , frames , eod ) : # Pre-processing if not hasattr ( analyzer , 'frames_buffer' ) : if analyzer . id ( ) in aubio_analyzers : # Aubio analyzers are waiting for stepsize length block # and reconstructs blocksize length frames itself # thus frames_adapter has to provide Aubio Pitch blocksize=stepsize length frames analyzer . frames_buffer = framesBuffer ( analyzer . input_stepsize , analyzer . input_stepsize ) else : analyzer . frames_buffer = framesBuffer ( analyzer . input_blocksize , analyzer . input_stepsize ) # Processing for adapted_frames , adapted_eod in analyzer . frames_buffer . frames ( frames , eod ) : process_func ( analyzer , adapted_frames , adapted_eod ) return frames , eod return wrapper
Pre - processing decorator that adapt frames to match input_blocksize and input_stepsize of the decorated analyzer
632
24
244,074
def get_uri ( self ) : if self . source_file and os . path . exists ( self . source_file . path ) : return self . source_file . path elif self . source_url : return self . source_url return None
Return the Item source
54
4
244,075
def get_audio_duration ( self ) : decoder = timeside . core . get_processor ( 'file_decoder' ) ( uri = self . get_uri ( ) ) return decoder . uri_total_duration
Return item audio duration
51
4
244,076
def get_results_path ( self ) : result_path = os . path . join ( RESULTS_ROOT , self . uuid ) if not os . path . exists ( result_path ) : os . makedirs ( result_path ) return result_path
Return Item result path
58
4
244,077
def get_uri ( source ) : import gst src_info = source_info ( source ) if src_info [ 'is_file' ] : # Is this a file? return get_uri ( src_info [ 'uri' ] ) elif gst . uri_is_valid ( source ) : # Is this a valid URI source for Gstreamer uri_protocol = gst . uri_get_protocol ( source ) if gst . uri_protocol_is_supported ( gst . URI_SRC , uri_protocol ) : return source else : raise IOError ( 'Invalid URI source for Gstreamer' ) else : raise IOError ( 'Failed getting uri for path %s: no such file' % source )
Check a media source as a valid file or uri and return the proper uri
169
17
244,078
def sha1sum_file ( filename ) : import hashlib import io sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * io . DEFAULT_BUFFER_SIZE with open ( filename , 'rb' ) as f : for chunk in iter ( lambda : f . read ( chunk_size ) , b'' ) : sha1 . update ( chunk ) return sha1 . hexdigest ( )
Return the secure hash digest with sha1 algorithm for a given file
99
14
244,079
def sha1sum_url ( url ) : import hashlib import urllib from contextlib import closing sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * 8192 max_file_size = 10 * 1024 * 1024 # 10Mo limit in case of very large file total_read = 0 with closing ( urllib . urlopen ( url ) ) as url_obj : for chunk in iter ( lambda : url_obj . read ( chunk_size ) , b'' ) : sha1 . update ( chunk ) total_read += chunk_size if total_read > max_file_size : break return sha1 . hexdigest ( )
Return the secure hash digest with sha1 algorithm for a given url
152
14
244,080
def sha1sum_numpy ( np_array ) : import hashlib return hashlib . sha1 ( np_array . view ( np . uint8 ) ) . hexdigest ( )
Return the secure hash digest with sha1 algorithm for a numpy array
43
15
244,081
def import_module_with_exceptions ( name , package = None ) : from timeside . core import _WITH_AUBIO , _WITH_YAAFE , _WITH_VAMP if name . count ( '.server.' ) : # TODO: # Temporary skip all timeside.server submodules before check dependencies return try : import_module ( name , package ) except VampImportError : # No Vamp Host if _WITH_VAMP : raise VampImportError else : # Ignore Vamp ImportError return except ImportError as e : if str ( e ) . count ( 'yaafelib' ) and not _WITH_YAAFE : # Ignore Yaafe ImportError return elif str ( e ) . count ( 'aubio' ) and not _WITH_AUBIO : # Ignore Aubio ImportError return elif str ( e ) . count ( 'DJANGO_SETTINGS_MODULE' ) : # Ignore module requiring DJANGO_SETTINGS_MODULE in environnement return else : print ( name , package ) raise e return name
Wrapper around importlib . import_module to import TimeSide subpackage and ignoring ImportError if Aubio Yaafe and Vamp Host are not available
241
31
244,082
def check_vamp ( ) : try : from timeside . plugins . analyzer . externals import vamp_plugin except VampImportError : warnings . warn ( 'Vamp host is not available' , ImportWarning , stacklevel = 2 ) _WITH_VAMP = False else : _WITH_VAMP = True del vamp_plugin return _WITH_VAMP
Check Vamp host availability
84
5
244,083
def im_watermark ( im , inputtext , font = None , color = None , opacity = .6 , margin = ( 30 , 30 ) ) : if im . mode != "RGBA" : im = im . convert ( "RGBA" ) textlayer = Image . new ( "RGBA" , im . size , ( 0 , 0 , 0 , 0 ) ) textdraw = ImageDraw . Draw ( textlayer ) textsize = textdraw . textsize ( inputtext , font = font ) textpos = [ im . size [ i ] - textsize [ i ] - margin [ i ] for i in [ 0 , 1 ] ] textdraw . text ( textpos , inputtext , font = font , fill = color ) if opacity != 1 : textlayer = reduce_opacity ( textlayer , opacity ) return Image . composite ( textlayer , im , textlayer )
imprints a PIL image with the indicated text in lower - right corner
187
15
244,084
def nextpow2 ( value ) : if value >= 1 : return 2 ** np . ceil ( np . log2 ( value ) ) . astype ( int ) elif value > 0 : return 1 elif value == 0 : return 0 else : raise ValueError ( 'Value must be positive' )
Compute the nearest power of two greater or equal to the input value
65
14
244,085
def blocksize ( self , input_totalframes ) : blocksize = input_totalframes if self . pad : mod = input_totalframes % self . buffer_size if mod : blocksize += self . buffer_size - mod return blocksize
Return the total number of frames that this adapter will output according to the input_totalframes argument
61
22
244,086
def append_processor ( self , proc , source_proc = None ) : if source_proc is None and len ( self . processors ) : source_proc = self . processors [ 0 ] if source_proc and not isinstance ( source_proc , Processor ) : raise TypeError ( 'source_proc must be a Processor or None' ) if not isinstance ( proc , Processor ) : raise TypeError ( 'proc must be a Processor or None' ) if proc . type == 'decoder' and len ( self . processors ) : raise ValueError ( 'Only the first processor in a pipe could be a Decoder' ) # TODO : check if the processor is already in the pipe if source_proc : for child in self . _graph . neighbors_iter ( source_proc . uuid ( ) ) : child_proc = self . _graph . node [ child ] [ 'processor' ] if proc == child_proc : proc . _uuid = child_proc . uuid ( ) proc . process_pipe = self break if not self . _graph . has_node ( proc . uuid ( ) ) : self . processors . append ( proc ) # Add processor to the pipe self . _graph . add_node ( proc . uuid ( ) , processor = proc , id = proc . id ( ) ) if source_proc : self . _graph . add_edge ( self . processors [ 0 ] . uuid ( ) , proc . uuid ( ) , type = 'audio_source' ) proc . process_pipe = self # Add an edge between each parent and proc for parent in proc . parents . values ( ) : self . _graph . add_edge ( parent . uuid ( ) , proc . uuid ( ) , type = 'data_source' )
Append a new processor to the pipe
378
8
244,087
def simple_host_process ( argslist ) : vamp_host = 'vamp-simple-host' command = [ vamp_host ] command . extend ( argslist ) # try ? stdout = subprocess . check_output ( command , stderr = subprocess . STDOUT ) . splitlines ( ) return stdout
Call vamp - simple - host
72
7
244,088
def set_scale ( self ) : f_min = float ( self . lower_freq ) f_max = float ( self . higher_freq ) y_min = f_min y_max = f_max for y in range ( self . image_height ) : freq = y_min + y / ( self . image_height - 1.0 ) * ( y_max - y_min ) fft_bin = freq / f_max * ( self . fft_size / 2 + 1 ) if fft_bin < self . fft_size / 2 : alpha = fft_bin - int ( fft_bin ) self . y_to_bin . append ( ( int ( fft_bin ) , alpha * 255 ) )
generate the lookup which translates y - coordinate to fft - bin
167
14
244,089
def dict_from_hdf5 ( dict_like , h5group ) : # Read attributes for name , value in h5group . attrs . items ( ) : dict_like [ name ] = value
Load a dictionnary - like object from a h5 file group
45
14
244,090
def get_frames ( self ) : nb_frames = self . input_totalframes // self . output_blocksize if self . input_totalframes % self . output_blocksize == 0 : nb_frames -= 1 # Last frame must send eod=True for index in xrange ( 0 , nb_frames * self . output_blocksize , self . output_blocksize ) : yield ( self . samples [ index : index + self . output_blocksize ] , False ) yield ( self . samples [ nb_frames * self . output_blocksize : ] , True )
Define an iterator that will return frames at the given blocksize
134
13
244,091
def implementations ( interface , recurse = True , abstract = False ) : result = [ ] find_implementations ( interface , recurse , abstract , result ) return result
Returns the components implementing interface and if recurse any of the descendants of interface . If abstract is True also return the abstract implementations .
36
26
244,092
def find_implementations ( interface , recurse , abstract , result ) : for item in MetaComponent . implementations : if ( item [ 'interface' ] == interface and ( abstract or not item [ 'abstract' ] ) ) : extend_unique ( result , [ item [ 'class' ] ] ) if recurse : subinterfaces = interface . __subclasses__ ( ) if subinterfaces : for i in subinterfaces : find_implementations ( i , recurse , abstract , result )
Find implementations of an interface or of one of its descendants and extend result with the classes found .
108
19
244,093
def draw_peaks ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y : self . draw . line ( [ self . previous_x , self . previous_y , x , y1 , x , y2 ] , line_color ) else : self . draw . line ( [ x , y1 , x , y2 ] , line_color ) self . draw_anti_aliased_pixels ( x , y1 , y2 , line_color ) self . previous_x , self . previous_y = x , y2
Draw 2 peaks at x
184
5
244,094
def draw_peaks_inverted ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y and x < self . image_width - 1 : if y1 < y2 : self . draw . line ( ( x , 0 , x , y1 ) , line_color ) self . draw . line ( ( x , self . image_height , x , y2 ) , line_color ) else : self . draw . line ( ( x , 0 , x , y2 ) , line_color ) self . draw . line ( ( x , self . image_height , x , y1 ) , line_color ) else : self . draw . line ( ( x , 0 , x , self . image_height ) , line_color ) self . draw_anti_aliased_pixels ( x , y1 , y2 , line_color ) self . previous_x , self . previous_y = x , y1
Draw 2 inverted peaks at x
266
6
244,095
def draw_anti_aliased_pixels ( self , x , y1 , y2 , color ) : y_max = max ( y1 , y2 ) y_max_int = int ( y_max ) alpha = y_max - y_max_int if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self . image_height : current_pix = self . pixel [ int ( x ) , y_max_int + 1 ] r = int ( ( 1 - alpha ) * current_pix [ 0 ] + alpha * color [ 0 ] ) g = int ( ( 1 - alpha ) * current_pix [ 1 ] + alpha * color [ 1 ] ) b = int ( ( 1 - alpha ) * current_pix [ 2 ] + alpha * color [ 2 ] ) self . pixel [ x , y_max_int + 1 ] = ( r , g , b ) y_min = min ( y1 , y2 ) y_min_int = int ( y_min ) alpha = 1.0 - ( y_min - y_min_int ) if alpha > 0.0 and alpha < 1.0 and y_min_int - 1 >= 0 : current_pix = self . pixel [ x , y_min_int - 1 ] r = int ( ( 1 - alpha ) * current_pix [ 0 ] + alpha * color [ 0 ] ) g = int ( ( 1 - alpha ) * current_pix [ 1 ] + alpha * color [ 1 ] ) b = int ( ( 1 - alpha ) * current_pix [ 2 ] + alpha * color [ 2 ] ) self . pixel [ x , y_min_int - 1 ] = ( r , g , b )
vertical anti - aliasing at y1 and y2
385
12
244,096
def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 )
Apply last 2D transforms
38
5
244,097
def write_metadata ( self ) : import mutagen from mutagen import id3 id3 = id3 . ID3 ( self . filename ) for tag in self . metadata . keys ( ) : value = self . metadata [ tag ] frame = mutagen . id3 . Frames [ tag ] ( 3 , value ) try : id3 . add ( frame ) except : raise IOError ( 'EncoderError: cannot tag "' + tag + '"' ) try : id3 . save ( ) except : raise IOError ( 'EncoderError: cannot write tags' )
Write all ID3v2 . 4 tags to file from self . metadata
119
15
244,098
def main ( args = sys . argv [ 1 : ] ) : opt = docopt ( main . __doc__ . strip ( ) , args , options_first = True ) config_logging ( opt [ '--verbose' ] ) if opt [ 'check' ] : check_backends ( opt [ '--title' ] ) elif opt [ 'extract' ] : handler = fulltext . get if opt [ '--file' ] : handler = _handle_open for path in opt [ '<path>' ] : print ( handler ( path ) ) else : # we should never get here raise ValueError ( "don't know how to handle cmd" )
Extract text from a file .
145
7
244,099
def is_binary ( f ) : # NOTE: order matters here. We don't bail on Python 2 just yet. Both # codecs.open() and io.open() can open in text mode, both set the encoding # attribute. We must do that check first. # If it has a decoding attribute with a value, it is text mode. if getattr ( f , "encoding" , None ) : return False # Python 2 makes no further distinction. if not PY3 : return True # If the file has a mode, and it contains b, it is binary. try : if 'b' in getattr ( f , 'mode' , '' ) : return True except TypeError : import gzip if isinstance ( f , gzip . GzipFile ) : return True # in gzip mode is an integer raise # Can we sniff? try : f . seek ( 0 , os . SEEK_CUR ) except ( AttributeError , IOError ) : return False # Finally, let's sniff by reading a byte. byte = f . read ( 1 ) f . seek ( - 1 , os . SEEK_CUR ) return hasattr ( byte , 'decode' )
Return True if binary mode .
253
6