INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Dropout with the same drop mask for all fixed_mask_dims
def variational_dropout(units, keep_prob, fixed_mask_dims=(1,)): """ Dropout with the same drop mask for all fixed_mask_dims Args: units: a tensor, usually with shapes [B x T x F], where B - batch size T - tokens dimension F - feature dimension keep_prob: kee...
Builds the network using Keras.
def build(self): """Builds the network using Keras. """ word_inputs = kl.Input(shape=(None, MAX_WORD_LENGTH+2), dtype="int32") inputs = [word_inputs] word_outputs = self._build_word_cnn(word_inputs) if len(self.word_vectorizers) > 0: additional_word_inputs = [...
Builds word - level network
def _build_word_cnn(self, inputs): """Builds word-level network """ inputs = kl.Lambda(kb.one_hot, arguments={"num_classes": self.symbols_number_}, output_shape=lambda x: tuple(x) + (self.symbols_number_,))(inputs) char_embeddings = kl.Dense(self.char_embedding...
Creates the basic network architecture transforming word embeddings to intermediate outputs
def _build_basic_network(self, word_outputs): """ Creates the basic network architecture, transforming word embeddings to intermediate outputs """ if self.word_dropout > 0.0: lstm_outputs = kl.Dropout(self.word_dropout)(word_outputs) else: lstm_out...
Trains model on a single batch
def train_on_batch(self, data: List[Iterable], labels: Iterable[list]) -> None: """Trains model on a single batch Args: data: a batch of word sequences labels: a batch of correct tag sequences Returns: the trained model """ X, Y = self._transf...
Makes predictions on a single batch
def predict_on_batch(self, data: Union[list, tuple], return_indexes: bool = False) -> List[List[str]]: """ Makes predictions on a single batch Args: data: a batch of word sequences together with additional inputs return_indexes: whether to return...
Transforms a sentence to Numpy array which will be the network input.
def _make_sent_vector(self, sent: List, bucket_length: int =None) -> np.ndarray: """Transforms a sentence to Numpy array, which will be the network input. Args: sent: input sentence bucket_length: the width of the bucket Returns: A 3d array, answer[i][j][k] ...
Transforms a sentence of tags to Numpy array which will be the network target.
def _make_tags_vector(self, tags, bucket_length=None) -> np.ndarray: """Transforms a sentence of tags to Numpy array, which will be the network target. Args: tags: input sentence of tags bucket_length: the width of the bucket Returns: A 2d array, answer[i][j...
Calculate BLEU score
def bleu_advanced(y_true: List[Any], y_predicted: List[Any], weights: Tuple=(1,), smoothing_function=SMOOTH.method1, auto_reweigh=False, penalty=True) -> float: """Calculate BLEU score Parameters: y_true: list of reference tokens y_predicted: list of query to...
Verify signature certificate URL against Amazon Alexa requirements.
def verify_sc_url(url: str) -> bool: """Verify signature certificate URL against Amazon Alexa requirements. Each call of Agent passes incoming utterances batch through skills filter, agent skills, skills processor. Batch of dialog IDs can be provided, in other case utterances indexes in incoming batch ...
Extracts pycrypto X509 objects from SSL certificates chain string.
def extract_certs(certs_txt: str) -> List[crypto.X509]: """Extracts pycrypto X509 objects from SSL certificates chain string. Args: certs_txt: SSL certificates chain string. Returns: result: List of pycrypto X509 objects. """ pattern = r'-----BEGIN CERTIFICATE-----.+?-----END CERTI...
Verifies Subject Alternative Names ( SANs ) for Amazon certificate.
def verify_sans(amazon_cert: crypto.X509) -> bool: """Verifies Subject Alternative Names (SANs) for Amazon certificate. Args: amazon_cert: Pycrypto X509 Amazon certificate. Returns: result: True if verification was successful, False if not. """ cert_extentions = [amazon_cert.get_ex...
Verifies if Amazon and additional certificates creates chain of trust to a root CA.
def verify_certs_chain(certs_chain: List[crypto.X509], amazon_cert: crypto.X509) -> bool: """Verifies if Amazon and additional certificates creates chain of trust to a root CA. Args: certs_chain: List of pycrypto X509 intermediate certificates from signature chain URL. amazon_cert: Pycrypto X50...
Verifies Alexa request signature.
def verify_signature(amazon_cert: crypto.X509, signature: str, request_body: bytes) -> bool: """Verifies Alexa request signature. Args: amazon_cert: Pycrypto X509 Amazon certificate. signature: Base64 decoded Alexa request signature from Signature HTTP header. request_body: full HTTPS r...
Conducts series of Alexa SSL certificate verifications against Amazon Alexa requirements.
def verify_cert(signature_chain_url: str) -> Optional[crypto.X509]: """Conducts series of Alexa SSL certificate verifications against Amazon Alexa requirements. Args: signature_chain_url: Signature certificate URL from SignatureCertChainUrl HTTP header. Returns: result: Amazon certificate i...
Returns list of json compatible states of the RichMessage instance nested controls.
def json(self) -> list: """Returns list of json compatible states of the RichMessage instance nested controls. Returns: json_controls: Json representation of RichMessage instance nested controls. """ json_controls = [control.json() for control in self...
Returns list of MS Bot Framework compatible states of the RichMessage instance nested controls.
def ms_bot_framework(self) -> list: """Returns list of MS Bot Framework compatible states of the RichMessage instance nested controls. Returns: ms_bf_controls: MS Bot Framework representation of RichMessage instance nested controls. """ ms_bf_controls...
Returns list of Telegram compatible states of the RichMessage instance nested controls.
def telegram(self) -> list: """Returns list of Telegram compatible states of the RichMessage instance nested controls. Returns: telegram_controls: Telegram representation of RichMessage instance nested controls. """ telegram_controls = [control.telegr...
Returns list of Amazon Alexa compatible states of the RichMessage instance nested controls.
def alexa(self) -> list: """Returns list of Amazon Alexa compatible states of the RichMessage instance nested controls. Returns: alexa_controls: Amazon Alexa representation of RichMessage instance nested controls. """ alexa_controls = [control.alexa()...
DeepPavlov console configuration utility.
def main(): """DeepPavlov console configuration utility.""" args = parser.parse_args() path = get_settings_path() if args.default: if populate_settings_dir(force=True): print(f'Populated {path} with default settings files') else: print(f'{path} is already a defau...
Constructs function encapsulated in the graph.
def _graph_wrap(func, graph): """Constructs function encapsulated in the graph.""" @wraps(func) def _wrapped(*args, **kwargs): with graph.as_default(): return func(*args, **kwargs) return _wrapped
Constructs function encapsulated in the graph and the session.
def _keras_wrap(func, graph, session): """Constructs function encapsulated in the graph and the session.""" import keras.backend as K @wraps(func) def _wrapped(*args, **kwargs): with graph.as_default(): K.set_session(session) return func(*args, **kwargs) return _wrap...
Compute Area Under the Curve ( AUC ) from prediction scores.
def roc_auc_score(y_true: Union[List[List[float]], List[List[int]], np.ndarray], y_pred: Union[List[List[float]], List[List[int]], np.ndarray]) -> float: """ Compute Area Under the Curve (AUC) from prediction scores. Args: y_true: true binary labels y_pred: target scores, ...
Convert a token to a hash of given size. Args: token: a word hash_size: hash size
def hash_(token: str, hash_size: int) -> int: """Convert a token to a hash of given size. Args: token: a word hash_size: hash size Returns: int, hashed token """ return murmurhash3_32(token, positive=True) % hash_size
Calculate accuracy in terms of absolute coincidence
def accuracy(y_true: [list, np.ndarray], y_predicted: [list, np.ndarray]) -> float: """ Calculate accuracy in terms of absolute coincidence Args: y_true: array of true values y_predicted: array of predicted values Returns: portion of absolutely coincidental samples """ ...
Rounds predictions and calculates accuracy in terms of absolute coincidence.
def round_accuracy(y_true, y_predicted): """ Rounds predictions and calculates accuracy in terms of absolute coincidence. Args: y_true: list of true values y_predicted: list of predicted values Returns: portion of absolutely coincidental samples """ predictions = [round...
We ll stub out all the initializers in the pretrained LM with a function that loads the weights from the file
def _pretrained_initializer(varname, weight_file, embedding_weight_file=None): """ We'll stub out all the initializers in the pretrained LM with a function that loads the weights from the file """ weight_name_map = {} for i in range(2): for j in range(8): # if we decide to add more laye...
Weight the layers of a biLM with trainable scalar weights to compute ELMo representations.
def weight_layers(name, bilm_ops, l2_coef=None, use_top_only=False, do_layer_norm=False, reuse=False): """ Weight the layers of a biLM with trainable scalar weights to compute ELMo representations. For each output layer, this returns two ops. The first computes a layer specif...
options contains key char_cnn: {
def _build_word_char_embeddings(self): """ options contains key 'char_cnn': { 'n_characters': 262, # includes the start / end characters 'max_characters_per_token': 50, 'filters': [ [1, 32], [2, 32], [3, 64], [4, 128], ...
Reads a file from a path and returns data as a list of tuples of inputs and correct outputs for every data type in train valid and test.
def read(self, data_path: str, *args, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]: """Reads a file from a path and returns data as a list of tuples of inputs and correct outputs for every data type in ``train``, ``valid`` and ``test``. """ raise NotImplementedError
Builds agent based on PatternMatchingSkill and HighestConfidenceSelector.
def make_hello_bot_agent() -> DefaultAgent: """Builds agent based on PatternMatchingSkill and HighestConfidenceSelector. This is agent building tutorial. You can use this .py file to check how hello-bot agent works. Returns: agent: Agent capable of handling several simple greetings. """ sk...
Takes an array of integers and transforms it to an array of one - hot encoded vectors
def to_one_hot(x, k): """ Takes an array of integers and transforms it to an array of one-hot encoded vectors """ unit = np.eye(k, dtype=int) return unit[x]
Prettifies the dictionary of metrics.
def prettify_metrics(metrics: List[Tuple[str, float]], precision: int = 4) -> OrderedDict: """Prettifies the dictionary of metrics.""" prettified_metrics = OrderedDict() for key, value in metrics: value = round(value, precision) prettified_metrics[key] = value return prettified_metrics
Populate settings directory with default settings files
def populate_settings_dir(force: bool = False) -> bool: """ Populate settings directory with default settings files Args: force: if ``True``, replace existing settings files with default ones Returns: ``True`` if any files were copied and ``False`` otherwise """ res = False ...
Updates dialogue state with new slots calculates features. Returns: Tracker:.
def update_state(self, slots: Union[List[Tuple[str, Any]], Dict[str, Any]]) -> 'Tracker': """ Updates dialogue state with new ``slots``, calculates features. Returns: Tracker: .""" pass
Returns predictions of morphotagging model given in config: config_path:.
def predict_with_model(config_path: [Path, str]) -> List[Optional[List[str]]]: """Returns predictions of morphotagging model given in config :config_path:. Args: config_path: a path to config Returns: a list of morphological analyses for each sentence. Each analysis is either a list of tag...
Initiates Flask web service with Alexa skill.
def run_alexa_server(agent_generator: callable, multi_instance: bool = False, stateful: bool = False, port: Optional[int] = None, https: bool = False, ssl_key: str = None, ssl_cert: str = None) ...
Load model parameters from self. load_path
def load(self, exclude_scopes: tuple = ('Optimizer',)) -> None: """Load model parameters from self.load_path""" if not hasattr(self, 'sess'): raise RuntimeError('Your TensorFlow model {} must' ' have sess attribute!'.format(self.__class__.__name__)) pat...
Save model parameters to self. save_path
def save(self, exclude_scopes: tuple = ('Optimizer',)) -> None: """Save model parameters to self.save_path""" if not hasattr(self, 'sess'): raise RuntimeError('Your TensorFlow model {} must' ' have sess attribute!'.format(self.__class__.__name__)) path ...
Get train operation for given loss
def get_train_op(self, loss, learning_rate, optimizer=None, clip_norm=None, learnable_scopes=None, optimizer_scope_name=None, **kwargs): """ Get train operat...
Print number of * trainable * parameters in the network
def print_number_of_parameters(): """ Print number of *trainable* parameters in the network """ log.info('Number of parameters: ') variables = tf.trainable_variables() blocks = defaultdict(int) for var in variables: # Get the top level scope name of va...
Вычисляет минимальную стоимость появления нового символа в узлах словаря в соответствии со штрафами из costs
def _precompute_absense_costs(dictionary, removal_costs, insertion_costs, n, allow_spaces=False): """ Вычисляет минимальную стоимость появления нового символа в узлах словаря в соответствии со штрафами из costs Аргументы: --------------- dictionary : Trie с...
Finds all dictionary words in d - window from word
def search(self, word, d, allow_spaces=True, return_cost=True): """ Finds all dictionary words in d-window from word """ if not all((c in self.alphabet or (c == " " and self.allow_spaces)) for c in word): return [] # raise ValueError("{0} conta...
Находит все слова в префиксном боре расстояние до которых в соответствии с заданным преобразователем не превышает d
def _trie_search(self, word, d, transducer=None, allow_spaces=True, return_cost=True): """ Находит все слова в префиксном боре, расстояние до которых в соответствии с заданным преобразователем не превышает d """ if transducer is None: # разобратьс...
Предвычисляет будущие символы и стоимости операций с ними для h - эвристики
def _precompute_euristics(self): """ Предвычисляет будущие символы и стоимости операций с ними для h-эвристики """ if self.euristics is None: return # вычисление минимальной стоимости операции, # приводящей к появлению ('+') или исчезновению ('-') данн...
Вычисление h - эвристики из работы Hulden 2009 для текущей вершины словаря
def _euristic_h_function(self, suffix, index): """ Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря Аргументы: ---------- suffix : string непрочитанный суффикс входного слова index : int индекс текущего узла в словаре ...
Возвращает стоимость элементарной трансдукции up - > low или np. inf если такой элементарной трансдукции нет
def get_operation_cost(self, up, low): """ Возвращает стоимость элементарной трансдукции up->low или np.inf, если такой элементарной трансдукции нет Аргументы: ---------- up, low : string элементы элементарной трансдукции Возвращает: --------...
Строит пробразователь задающий обратное конечное преобразование
def inverse(self): """ Строит пробразователь, задающий обратное конечное преобразование """ # УПРОСТИТЬ ОБРАЩЕНИЕ!!! inversed_transducer = SegmentTransducer(self.alphabet, operation_costs=dict()) inversed_transducer.operation_costs = self._reversed_operation_costs ...
Вычисляет трансдукцию минимальной стоимости отображающую first в second
def distance(self, first, second, return_transduction = False): """ Вычисляет трансдукцию минимальной стоимости, отображающую first в second Аргументы: ----------- first : string second : string Верхний и нижний элементы трансдукции return_tr...
Возвращает все трансдукции переводящие first в second чья стоимость не превышает threshold
def transduce(self, first, second, threshold): """ Возвращает все трансдукции, переводящие first в second, чья стоимость не превышает threshold Возвращает: ---------- result : list список вида [(трансдукция, стоимость)] """ add_pred = (lambda ...
Возвращает все трансдукции с верхним элементом word чья стоимость не превышает max_cost
def lower_transductions(self, word, max_cost, return_cost=True): """ Возвращает все трансдукции с верхним элементом word, чья стоимость не превышает max_cost ` Возвращает: ---------- result : list список вида [(трансдукция, стоимость)], если return_cost=True ...
Функция динамически заполняющая таблицу costs стоимости трансдукций costs [ i ] [ j ] --- минимальная стоимость трансдукции переводящей first [: i ] в second [: j ]
def _fill_levenshtein_table(self, first, second, update_func, add_pred, clear_pred, threshold=None): """ Функция, динамически заполняющая таблицу costs стоимости трансдукций, costs[i][j] --- минимальная стоимость трансдукции, переводящей first[:i] в second[...
Заполняет массив _reversed_operation_costs на основе имеющегося массива operation_costs
def _make_reversed_operation_costs(self): """ Заполняет массив _reversed_operation_costs на основе имеющегося массива operation_costs """ _reversed_operation_costs = dict() for up, costs in self.operation_costs.items(): for low, cost in costs.items(): ...
Вычисляет максимальную длину элемента low в элементарной трансдукции ( up low ) для каждого up и максимальную длину элемента up в элементарной трансдукции ( up low ) для каждого low
def _make_maximal_key_lengths(self): """ Вычисляет максимальную длину элемента low в элементарной трансдукции (up, low) для каждого up и максимальную длину элемента up в элементарной трансдукции (up, low) для каждого low """ self.max_up_length =\ (max(...
Восстанавливает трансдукции по таблице обратных ссылок
def _backtraces_to_transductions(self, first, second, backtraces, threshold, return_cost=False): """ Восстанавливает трансдукции по таблице обратных ссылок Аргументы: ---------- first, second : string верхние и нижние элементы трансдукции backtraces : array-l...
возвращает все трансдукции стоимости < = max_cost которые можно получить из элементов initial
def _perform_insertions(self, initial, max_cost): """ возвращает все трансдукции стоимости <= max_cost, которые можно получить из элементов initial Аргументы: ---------- initial : list of tuples список исходных трансдукций вида [(трансдукция, стоимость)] ...
sets 1. 0 cost for every replacement insertion deletion and transposition
def _make_default_operation_costs(self, allow_spaces=False): """ sets 1.0 cost for every replacement, insertion, deletion and transposition """ self.operation_costs = dict() self.operation_costs[""] = {c: 1.0 for c in list(self.alphabet) + [' ']} for a in self.alphabet: ...
Initiates self - destruct timer.
def _start_timer(self) -> None: """Initiates self-destruct timer.""" self.timer = Timer(self.config['conversation_lifetime'], self.self_destruct_callback) self.timer.start()
Routes Alexa requests to appropriate handlers.
def handle_request(self, request: dict) -> dict: """Routes Alexa requests to appropriate handlers. Args: request: Alexa request. Returns: response: Response conforming Alexa response specification. """ request_type = request['request']['type'] req...
Infers DeepPavlov agent with raw user input extracted from Alexa request.
def _act(self, utterance: str) -> list: """Infers DeepPavlov agent with raw user input extracted from Alexa request. Args: utterance: Raw user input extracted from Alexa request. Returns: response: DeepPavlov agent response. """ if self.stateful: ...
Populates generated response with additional data conforming Alexa response specification.
def _generate_response(self, response: dict, request: dict) -> dict: """Populates generated response with additional data conforming Alexa response specification. Args: response: Raw user input extracted from Alexa request. request: Alexa request. Returns: re...
Handles IntentRequest Alexa request.
def _handle_intent(self, request: dict) -> dict: """Handles IntentRequest Alexa request. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification. """ intent_name = self.config['intent_name'] ...
Handles LaunchRequest Alexa request.
def _handle_launch(self, request: dict) -> dict: """Handles LaunchRequest Alexa request. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification. """ response = { 'response': { ...
Handles all unsupported types of Alexa requests. Returns standard message.
def _handle_unsupported(self, request: dict) -> dict: """Handles all unsupported types of Alexa requests. Returns standard message. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification. """ respo...
method that defines Struct s pretty printing rules for iPython
def _repr_pretty_(self, p, cycle): """method that defines ``Struct``'s pretty printing rules for iPython Args: p (IPython.lib.pretty.RepresentationPrinter): pretty printer object cycle (bool): is ``True`` if pretty detected a cycle """ if cycle: p.tex...
Calculates perplexity by loss
def elmo_loss2ppl(losses: List[np.ndarray]) -> float: """ Calculates perplexity by loss Args: losses: list of numpy arrays of model losses Returns: perplexity : float """ avg_loss = np.mean(losses) return float(np.exp(avg_loss))
Create: self. total_loss: total loss op for training self. softmax_W softmax_b: the softmax variables self. next_token_id/ _reverse: placeholders for gold input
def _build_loss(self, lstm_outputs): """ Create: self.total_loss: total loss op for training self.softmax_W, softmax_b: the softmax variables self.next_token_id / _reverse: placeholders for gold input """ batch_size = self.options['batch_size'] ...
Build and return the model described in corresponding configuration file.
def build_model(config: Union[str, Path, dict], mode: str = 'infer', load_trained: bool = False, download: bool = False, serialized: Optional[bytes] = None) -> Chainer: """Build and return the model described in corresponding configuration file.""" config = parse_config(config) ...
Start interaction with the model described in corresponding configuration file.
def interact_model(config: Union[str, Path, dict]) -> None: """Start interaction with the model described in corresponding configuration file.""" model = build_model(config) while True: args = [] for in_x in model.in_x: args.append((input('{}::'.format(in_x)),)) # ch...
Make a prediction with the component described in corresponding configuration file.
def predict_on_stream(config: Union[str, Path, dict], batch_size: int = 1, file_path: Optional[str] = None) -> None: """Make a prediction with the component described in corresponding configuration file.""" if file_path is None or file_path == '-': if sys.stdin.isatty(): raise RuntimeError('...
Reads input file in CONLL - U format
def read_infile(infile: Union[Path, str], from_words=False, word_column: int = WORD_COLUMN, pos_column: int = POS_COLUMN, tag_column: int = TAG_COLUMN, max_sents: int = -1, read_only_words: bool = False) -> List[Tuple[List, Union[List, None]]]: """Reads input file in ...
Processes all words in data using: func: ~deeppavlov. dataset_iterators. morphotagger_iterator. process_word.
def preprocess_data(data: List[Tuple[List[str], List[str]]], to_lower: bool = True, append_case: str = "first") -> List[Tuple[List[Tuple[str]], List[str]]]: """Processes all words in data using :func:`~deeppavlov.dataset_iterators.morphotagger_iterator.process_word`. Args: data:...
Returns a function object with the name given in string.
def fn_from_str(name: str) -> Callable[..., Any]: """Returns a function object with the name given in string.""" try: module_name, fn_name = name.split(':') except ValueError: raise ConfigError('Expected function description in a `module.submodules:function_name` form, but got `{}`' ...
Decorator for metric registration.
def register_metric(metric_name: str) -> Callable[..., Any]: """Decorator for metric registration.""" def decorate(fn): fn_name = fn.__module__ + ':' + fn.__name__ if metric_name in _REGISTRY and _REGISTRY[metric_name] != fn_name: log.warning('"{}" is already registered as a metric n...
Returns a metric callable with a corresponding name.
def get_metric_by_name(name: str) -> Callable[..., Any]: """Returns a metric callable with a corresponding name.""" if name not in _REGISTRY: raise ConfigError(f'"{name}" is not registered as a metric') return fn_from_str(_REGISTRY[name])
Convert given string label of decay type to special index
def from_str(cls, label: str) -> int: """ Convert given string label of decay type to special index Args: label: name of decay type. Set of values: `"linear"`, `"cosine"`, `"exponential"`, `"onecycle"`, `"trapezoid"`, `["polynomial", K]`, where K is ...
Find the best learning rate schedule and set obtained values of learning rate and momentum for further model training. Best learning rate will be divided by fit_learning_rate_div for further training model.
def fit(self, *args): """ Find the best learning rate schedule, and set obtained values of learning rate and momentum for further model training. Best learning rate will be divided by `fit_learning_rate_div` for further training model. Args: *args: arguments ...
Find the best value according to given losses
def _get_best(values: List[float], losses: List[float], max_loss_div: float = 0.9, min_val_div: float = 10.0) -> float: """ Find the best value according to given losses Args: values: list of considered values losses: list of obtained loss values corres...
Update learning rate and momentum variables after event ( given by event_name )
def process_event(self, event_name: str, data: dict) -> None: """ Update learning rate and momentum variables after event (given by `event_name`) Args: event_name: name of event after which the method was called. Set of values: `"after_validation"`, `"after_batch...
Embed one text sample
def _encode(self, tokens: List[str], mean: bool) -> Union[List[np.ndarray], np.ndarray]: """ Embed one text sample Args: tokens: tokenized text sample mean: whether to return mean embedding of tokens per sample Returns: list of embedded tokens or arr...
parses requirements from requirements. txt
def read_requirements(): """parses requirements from requirements.txt""" reqs_path = os.path.join(__location__, 'requirements.txt') with open(reqs_path, encoding='utf8') as f: reqs = [line.strip() for line in f if not line.strip().startswith('#')] names = [] links = [] for req in reqs: ...
Detokenizing a text undoes the tokenizing operation restores punctuation and spaces to the places that people expect them to be. Ideally detokenize ( tokenize ( text )) should be identical to text except for line breaks.
def detokenize(tokens): """ Detokenizing a text undoes the tokenizing operation, restores punctuation and spaces to the places that people expect them to be. Ideally, `detokenize(tokenize(text))` should be identical to `text`, except for line breaks. """ text = ' '.join(tokens) step0 = t...
Make ngrams from a list of tokens/ lemmas: param items: list of tokens lemmas or other strings to form ngrams: param ngram_range: range for producing ngrams ex. for unigrams + bigrams should be set to ( 1 2 ) for bigrams only should be set to ( 2 2 ): return: ngrams ( as strings ) generator
def ngramize(items: List[str], ngram_range=(1, 1)) -> Generator[List[str], Any, None]: """ Make ngrams from a list of tokens/lemmas :param items: list of tokens, lemmas or other strings to form ngrams :param ngram_range: range for producing ngrams, ex. for unigrams + bigrams should be set to (1, 2),...
Calculates log loss.
def sk_log_loss(y_true: Union[List[List[float]], List[List[int]], np.ndarray], y_predicted: Union[List[List[float]], List[List[int]], np.ndarray]) -> float: """ Calculates log loss. Args: y_true: list or array of true values y_predicted: list or array of predicted values ...
Makes a module spec.
def make_module_spec(options, weight_file): """Makes a module spec. Args: options: LM hyperparameters. weight_file: location of the hdf5 file with LM weights. Returns: A module spec object used for constructing a TF-Hub module. """ def module_fn(): """Spec function for a ...
Exports a TF - Hub module
def export2hub(weight_file, hub_dir, options): """Exports a TF-Hub module """ spec = make_module_spec(options, str(weight_file)) try: with tf.Graph().as_default(): module = hub.Module(spec) with tf.Session() as sess: sess.run(tf.global_variables_initial...
Format catalog item output
def show_details(item_data: Dict[Any, Any]) -> str: """Format catalog item output Parameters: item_data: item's attributes values Returns: [rich_message]: list of formatted rich message """ txt = "" for key, value in item_data.items(): txt += "**" + str(key) + "**" + ...
Make an agent
def make_agent() -> EcommerceAgent: """Make an agent Returns: agent: created Ecommerce agent """ config_path = find_config('tfidf_retrieve') skill = build_model(config_path) agent = EcommerceAgent(skills=[skill]) return agent
Parse parameters and run ms bot framework
def main(): """Parse parameters and run ms bot framework""" args = parser.parse_args() run_ms_bot_framework_server(agent_generator=make_agent, app_id=args.ms_id, app_secret=args.ms_secret, stateful=True)
Processes batch of utterances and returns corresponding responses batch.
def _call(self, utterances_batch: List[str], utterances_ids: List[int] = None) -> List[RichMessage]: """Processes batch of utterances and returns corresponding responses batch. Args: utterances_batch: Batch of incoming utterances. utterances_ids: Batch of dialog IDs correspondin...
Drops with: dropout probability temporal steps of input 3D tensor
def TemporalDropout(inputs, dropout=0.0): """ Drops with :dropout probability temporal steps of input 3D tensor """ # TO DO: adapt for >3D tensors if dropout == 0.0: return inputs inputs_func = lambda x: kb.ones_like(inputs[:, :, 0:1]) inputs_mask = kl.Lambda(inputs_func)(inputs) ...
A layer filling i - th column of a 2D tensor with 1 + ln ( 1 + i ) when it contains a meaningful symbol and with 0 when it contains PAD
def positions_func(inputs, pad=0): """ A layer filling i-th column of a 2D tensor with 1+ln(1+i) when it contains a meaningful symbol and with 0 when it contains PAD """ position_inputs = kb.cumsum(kb.ones_like(inputs, dtype="float32"), axis=1) position_inputs *= kb.cast(kb.not_equal(inputs,...
Download a file from URL to one or several target locations
def download(dest_file_path: [List[Union[str, Path]]], source_url: str, force_download=True): """Download a file from URL to one or several target locations Args: dest_file_path: path or list of paths to the file destination files (including file name) source_url: the source URL force_d...
Simple tar archive extractor
def untar(file_path, extract_folder=None): """Simple tar archive extractor Args: file_path: path to the tar file to be extracted extract_folder: folder to which the files will be extracted """ file_path = Path(file_path) if extract_folder is None: extract_folder = file_path...
Simple. gz archive extractor
def ungzip(file_path, extract_path: Path = None): """Simple .gz archive extractor Args: file_path: path to the gzip file to be extracted extract_path: path where the file will be extracted """ CHUNK = 16 * 1024 file_path = Path(file_path) extract_path = extract_...
Download and extract. tar. gz or. gz file to one or several target locations. The archive is deleted if extraction was successful.
def download_decompress(url: str, download_path: [Path, str], extract_paths=None): """Download and extract .tar.gz or .gz file to one or several target locations. The archive is deleted if extraction was successful. Args: url: URL for file downloading download_path: path to the directory wh...
Updates dict recursively
def update_dict_recursive(editable_dict: dict, editing_dict: dict) -> None: """Updates dict recursively You need to use this function to update dictionary if depth of editing_dict is more then 1 Args: editable_dict: dictionary, that will be edited editing_dict: dictionary, that contains ed...
Given a file URL return a md5 query of the file
def path_set_md5(url): """Given a file URL, return a md5 query of the file Args: url: a given URL Returns: URL of the md5 file """ scheme, netloc, path, query_string, fragment = urlsplit(url) path += '.md5' return urlunsplit((scheme, netloc, path, query_string, fragment))
Given a URL set or replace a query parameter and return the modified URL.
def set_query_parameter(url, param_name, param_value): """Given a URL, set or replace a query parameter and return the modified URL. Args: url: a given URL param_name: the parameter name to add param_value: the parameter value Returns: URL with the added parameter """ ...
Returns Amazon Alexa compatible state of the PlainText instance.
def alexa(self) -> dict: """Returns Amazon Alexa compatible state of the PlainText instance. Creating Amazon Alexa response blank with populated "outputSpeech" and "card sections. Returns: response: Amazon Alexa representation of PlainText state. """ respons...