partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
variational_dropout
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: keep probability fixed_mask_dims: in these dimensions the mask will ...
deeppavlov/core/layers/tf_layers.py
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...
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...
[ "Dropout", "with", "the", "same", "drop", "mask", "for", "all", "fixed_mask_dims" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L930-L948
[ "def", "variational_dropout", "(", "units", ",", "keep_prob", ",", "fixed_mask_dims", "=", "(", "1", ",", ")", ")", ":", "units_shape", "=", "tf", ".", "shape", "(", "units", ")", "noise_shape", "=", "[", "units_shape", "[", "n", "]", "for", "n", "in",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
CharacterTagger.build
Builds the network using Keras.
deeppavlov/models/morpho_tagger/network.py
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 = [...
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", "the", "network", "using", "Keras", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L140-L160
[ "def", "build", "(", "self", ")", ":", "word_inputs", "=", "kl", ".", "Input", "(", "shape", "=", "(", "None", ",", "MAX_WORD_LENGTH", "+", "2", ")", ",", "dtype", "=", "\"int32\"", ")", "inputs", "=", "[", "word_inputs", "]", "word_outputs", "=", "s...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
CharacterTagger._build_word_cnn
Builds word-level network
deeppavlov/models/morpho_tagger/network.py
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...
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...
[ "Builds", "word", "-", "level", "network" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L162-L197
[ "def", "_build_word_cnn", "(", "self", ",", "inputs", ")", ":", "inputs", "=", "kl", ".", "Lambda", "(", "kb", ".", "one_hot", ",", "arguments", "=", "{", "\"num_classes\"", ":", "self", ".", "symbols_number_", "}", ",", "output_shape", "=", "lambda", "x...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
CharacterTagger._build_basic_network
Creates the basic network architecture, transforming word embeddings to intermediate outputs
deeppavlov/models/morpho_tagger/network.py
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...
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...
[ "Creates", "the", "basic", "network", "architecture", "transforming", "word", "embeddings", "to", "intermediate", "outputs" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L199-L219
[ "def", "_build_basic_network", "(", "self", ",", "word_outputs", ")", ":", "if", "self", ".", "word_dropout", ">", "0.0", ":", "lstm_outputs", "=", "kl", ".", "Dropout", "(", "self", ".", "word_dropout", ")", "(", "word_outputs", ")", "else", ":", "lstm_ou...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
CharacterTagger.train_on_batch
Trains model on a single batch Args: data: a batch of word sequences labels: a batch of correct tag sequences Returns: the trained model
deeppavlov/models/morpho_tagger/network.py
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...
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...
[ "Trains", "model", "on", "a", "single", "batch" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L234-L244
[ "def", "train_on_batch", "(", "self", ",", "data", ":", "List", "[", "Iterable", "]", ",", "labels", ":", "Iterable", "[", "list", "]", ")", "->", "None", ":", "X", ",", "Y", "=", "self", ".", "_transform_batch", "(", "data", ",", "labels", ")", "s...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
CharacterTagger.predict_on_batch
Makes predictions on a single batch Args: data: a batch of word sequences together with additional inputs return_indexes: whether to return tag indexes in vocabulary or tags themselves Returns: a batch of label sequences
deeppavlov/models/morpho_tagger/network.py
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...
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...
[ "Makes", "predictions", "on", "a", "single", "batch" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L246-L266
[ "def", "predict_on_batch", "(", "self", ",", "data", ":", "Union", "[", "list", ",", "tuple", "]", ",", "return_indexes", ":", "bool", "=", "False", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "X", "=", "self", ".", "_transform_batch",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
CharacterTagger._make_sent_vector
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] contains the index of k-th letter in j-th word of i-th input sentence.
deeppavlov/models/morpho_tagger/network.py
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] ...
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", "to", "Numpy", "array", "which", "will", "be", "the", "network", "input", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L268-L288
[ "def", "_make_sent_vector", "(", "self", ",", "sent", ":", "List", ",", "bucket_length", ":", "int", "=", "None", ")", "->", "np", ".", "ndarray", ":", "bucket_length", "=", "bucket_length", "or", "len", "(", "sent", ")", "answer", "=", "np", ".", "zer...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
CharacterTagger._make_tags_vector
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] contains the index of j-th tag in i-th input sentence.
deeppavlov/models/morpho_tagger/network.py
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...
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...
[ "Transforms", "a", "sentence", "of", "tags", "to", "Numpy", "array", "which", "will", "be", "the", "network", "target", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L290-L304
[ "def", "_make_tags_vector", "(", "self", ",", "tags", ",", "bucket_length", "=", "None", ")", "->", "np", ".", "ndarray", ":", "bucket_length", "=", "bucket_length", "or", "len", "(", "tags", ")", "answer", "=", "np", ".", "zeros", "(", "shape", "=", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
bleu_advanced
Calculate BLEU score Parameters: y_true: list of reference tokens y_predicted: list of query tokens weights: n-gram weights smoothing_function: SmoothingFunction auto_reweigh: Option to re-normalize the weights uniformly penalty: either enable brevity penalty or not ...
deeppavlov/metrics/bleu.py
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...
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...
[ "Calculate", "BLEU", "score" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/bleu.py#L27-L55
[ "def", "bleu_advanced", "(", "y_true", ":", "List", "[", "Any", "]", ",", "y_predicted", ":", "List", "[", "Any", "]", ",", "weights", ":", "Tuple", "=", "(", "1", ",", ")", ",", "smoothing_function", "=", "SMOOTH", ".", "method1", ",", "auto_reweigh",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
verify_sc_url
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 are used as dialog IDs. Args: u...
deeppavlov/utils/alexa/ssl_tools.py
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 ...
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 ...
[ "Verify", "signature", "certificate", "URL", "against", "Amazon", "Alexa", "requirements", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/ssl_tools.py#L29-L58
[ "def", "verify_sc_url", "(", "url", ":", "str", ")", "->", "bool", ":", "parsed", "=", "urlsplit", "(", "url", ")", "scheme", ":", "str", "=", "parsed", ".", "scheme", "netloc", ":", "str", "=", "parsed", ".", "netloc", "path", ":", "str", "=", "pa...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
extract_certs
Extracts pycrypto X509 objects from SSL certificates chain string. Args: certs_txt: SSL certificates chain string. Returns: result: List of pycrypto X509 objects.
deeppavlov/utils/alexa/ssl_tools.py
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...
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...
[ "Extracts", "pycrypto", "X509", "objects", "from", "SSL", "certificates", "chain", "string", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/ssl_tools.py#L61-L73
[ "def", "extract_certs", "(", "certs_txt", ":", "str", ")", "->", "List", "[", "crypto", ".", "X509", "]", ":", "pattern", "=", "r'-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----'", "certs_txt", "=", "re", ".", "findall", "(", "pattern", ",", "certs_txt", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
verify_sans
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.
deeppavlov/utils/alexa/ssl_tools.py
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...
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", "Subject", "Alternative", "Names", "(", "SANs", ")", "for", "Amazon", "certificate", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/ssl_tools.py#L76-L95
[ "def", "verify_sans", "(", "amazon_cert", ":", "crypto", ".", "X509", ")", "->", "bool", ":", "cert_extentions", "=", "[", "amazon_cert", ".", "get_extension", "(", "i", ")", "for", "i", "in", "range", "(", "amazon_cert", ".", "get_extension_count", "(", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
verify_certs_chain
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 X509 Amazon certificate. Returns: result: True if verification was successful, False if...
deeppavlov/utils/alexa/ssl_tools.py
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...
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", "if", "Amazon", "and", "additional", "certificates", "creates", "chain", "of", "trust", "to", "a", "root", "CA", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/ssl_tools.py#L98-L152
[ "def", "verify_certs_chain", "(", "certs_chain", ":", "List", "[", "crypto", ".", "X509", "]", ",", "amazon_cert", ":", "crypto", ".", "X509", ")", "->", "bool", ":", "store", "=", "crypto", ".", "X509Store", "(", ")", "# add certificates from Amazon provided ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
verify_signature
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 request body Returns: result: True if verification was successful, False if not.
deeppavlov/utils/alexa/ssl_tools.py
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...
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...
[ "Verifies", "Alexa", "request", "signature", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/ssl_tools.py#L155-L173
[ "def", "verify_signature", "(", "amazon_cert", ":", "crypto", ".", "X509", ",", "signature", ":", "str", ",", "request_body", ":", "bytes", ")", "->", "bool", ":", "signature", "=", "base64", ".", "b64decode", "(", "signature", ")", "try", ":", "crypto", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
verify_cert
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 if verification was successful, None if not.
deeppavlov/utils/alexa/ssl_tools.py
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...
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...
[ "Conducts", "series", "of", "Alexa", "SSL", "certificate", "verifications", "against", "Amazon", "Alexa", "requirements", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/ssl_tools.py#L176-L217
[ "def", "verify_cert", "(", "signature_chain_url", ":", "str", ")", "->", "Optional", "[", "crypto", ".", "X509", "]", ":", "try", ":", "certs_chain_get", "=", "requests", ".", "get", "(", "signature_chain_url", ")", "except", "requests", ".", "exceptions", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
RichMessage.json
Returns list of json compatible states of the RichMessage instance nested controls. Returns: json_controls: Json representation of RichMessage instance nested controls.
deeppavlov/core/agent/rich_content.py
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...
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", "json", "compatible", "states", "of", "the", "RichMessage", "instance", "nested", "controls", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/agent/rich_content.py#L115-L124
[ "def", "json", "(", "self", ")", "->", "list", ":", "json_controls", "=", "[", "control", ".", "json", "(", ")", "for", "control", "in", "self", ".", "controls", "]", "return", "json_controls" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
RichMessage.ms_bot_framework
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.
deeppavlov/core/agent/rich_content.py
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...
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", "MS", "Bot", "Framework", "compatible", "states", "of", "the", "RichMessage", "instance", "nested", "controls", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/agent/rich_content.py#L126-L135
[ "def", "ms_bot_framework", "(", "self", ")", "->", "list", ":", "ms_bf_controls", "=", "[", "control", ".", "ms_bot_framework", "(", ")", "for", "control", "in", "self", ".", "controls", "]", "return", "ms_bf_controls" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
RichMessage.telegram
Returns list of Telegram compatible states of the RichMessage instance nested controls. Returns: telegram_controls: Telegram representation of RichMessage instance nested controls.
deeppavlov/core/agent/rich_content.py
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...
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", "Telegram", "compatible", "states", "of", "the", "RichMessage", "instance", "nested", "controls", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/agent/rich_content.py#L137-L146
[ "def", "telegram", "(", "self", ")", "->", "list", ":", "telegram_controls", "=", "[", "control", ".", "telegram", "(", ")", "for", "control", "in", "self", ".", "controls", "]", "return", "telegram_controls" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
RichMessage.alexa
Returns list of Amazon Alexa compatible states of the RichMessage instance nested controls. Returns: alexa_controls: Amazon Alexa representation of RichMessage instance nested controls.
deeppavlov/core/agent/rich_content.py
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()...
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()...
[ "Returns", "list", "of", "Amazon", "Alexa", "compatible", "states", "of", "the", "RichMessage", "instance", "nested", "controls", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/agent/rich_content.py#L148-L157
[ "def", "alexa", "(", "self", ")", "->", "list", ":", "alexa_controls", "=", "[", "control", ".", "alexa", "(", ")", "for", "control", "in", "self", ".", "controls", "]", "return", "alexa_controls" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
main
DeepPavlov console configuration utility.
deeppavlov/settings.py
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...
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...
[ "DeepPavlov", "console", "configuration", "utility", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/settings.py#L24-L35
[ "def", "main", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "path", "=", "get_settings_path", "(", ")", "if", "args", ".", "default", ":", "if", "populate_settings_dir", "(", "force", "=", "True", ")", ":", "print", "(", "f'Popula...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
_graph_wrap
Constructs function encapsulated in the graph.
deeppavlov/core/models/tf_backend.py
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
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", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/tf_backend.py#L22-L28
[ "def", "_graph_wrap", "(", "func", ",", "graph", ")", ":", "@", "wraps", "(", "func", ")", "def", "_wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "graph", ".", "as_default", "(", ")", ":", "return", "func", "(", "*", "arg...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
_keras_wrap
Constructs function encapsulated in the graph and the session.
deeppavlov/core/models/tf_backend.py
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...
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...
[ "Constructs", "function", "encapsulated", "in", "the", "graph", "and", "the", "session", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/tf_backend.py#L31-L40
[ "def", "_keras_wrap", "(", "func", ",", "graph", ",", "session", ")", ":", "import", "keras", ".", "backend", "as", "K", "@", "wraps", "(", "func", ")", "def", "_wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "graph", ".", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
roc_auc_score
Compute Area Under the Curve (AUC) from prediction scores. Args: y_true: true binary labels y_pred: target scores, can either be probability estimates of the positive class Returns: Area Under the Curve (AUC) from prediction scores
deeppavlov/metrics/roc_auc_score.py
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, ...
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, ...
[ "Compute", "Area", "Under", "the", "Curve", "(", "AUC", ")", "from", "prediction", "scores", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/roc_auc_score.py#L25-L41
[ "def", "roc_auc_score", "(", "y_true", ":", "Union", "[", "List", "[", "List", "[", "float", "]", "]", ",", "List", "[", "List", "[", "int", "]", "]", ",", "np", ".", "ndarray", "]", ",", "y_pred", ":", "Union", "[", "List", "[", "List", "[", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
hash_
Convert a token to a hash of given size. Args: token: a word hash_size: hash size Returns: int, hashed token
deeppavlov/models/vectorizers/hashing_tfidf_vectorizer.py
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
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
[ "Convert", "a", "token", "to", "a", "hash", "of", "given", "size", ".", "Args", ":", "token", ":", "a", "word", "hash_size", ":", "hash", "size" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/vectorizers/hashing_tfidf_vectorizer.py#L33-L43
[ "def", "hash_", "(", "token", ":", "str", ",", "hash_size", ":", "int", ")", "->", "int", ":", "return", "murmurhash3_32", "(", "token", ",", "positive", "=", "True", ")", "%", "hash_size" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
accuracy
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
deeppavlov/metrics/accuracy.py
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 """ ...
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 """ ...
[ "Calculate", "accuracy", "in", "terms", "of", "absolute", "coincidence" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/accuracy.py#L24-L37
[ "def", "accuracy", "(", "y_true", ":", "[", "list", ",", "np", ".", "ndarray", "]", ",", "y_predicted", ":", "[", "list", ",", "np", ".", "ndarray", "]", ")", "->", "float", ":", "examples_len", "=", "len", "(", "y_true", ")", "correct", "=", "sum"...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
round_accuracy
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
deeppavlov/metrics/accuracy.py
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...
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...
[ "Rounds", "predictions", "and", "calculates", "accuracy", "in", "terms", "of", "absolute", "coincidence", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/accuracy.py#L94-L108
[ "def", "round_accuracy", "(", "y_true", ",", "y_predicted", ")", ":", "predictions", "=", "[", "round", "(", "x", ")", "for", "x", "in", "y_predicted", "]", "examples_len", "=", "len", "(", "y_true", ")", "correct", "=", "sum", "(", "[", "y1", "==", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
_pretrained_initializer
We'll stub out all the initializers in the pretrained LM with a function that loads the weights from the file
deeppavlov/models/elmo/elmo_model.py
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...
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...
[ "We", "ll", "stub", "out", "all", "the", "initializers", "in", "the", "pretrained", "LM", "with", "a", "function", "that", "loads", "the", "weights", "from", "the", "file" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/elmo_model.py#L192-L248
[ "def", "_pretrained_initializer", "(", "varname", ",", "weight_file", ",", "embedding_weight_file", "=", "None", ")", ":", "weight_name_map", "=", "{", "}", "for", "i", "in", "range", "(", "2", ")", ":", "for", "j", "in", "range", "(", "8", ")", ":", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
weight_layers
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 specific weighted average of the biLM layers, and the second the l2 regularizer loss term. The regularization terms are also ad...
deeppavlov/models/elmo/elmo_model.py
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...
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...
[ "Weight", "the", "layers", "of", "a", "biLM", "with", "trainable", "scalar", "weights", "to", "compute", "ELMo", "representations", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/elmo_model.py#L597-L728
[ "def", "weight_layers", "(", "name", ",", "bilm_ops", ",", "l2_coef", "=", "None", ",", "use_top_only", "=", "False", ",", "do_layer_norm", "=", "False", ",", "reuse", "=", "False", ")", ":", "def", "_l2_regularizer", "(", "weights", ")", ":", "if", "l2_...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
BidirectionalLanguageModelGraph._build_word_char_embeddings
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], [5, 256], [6, 512], [7, 5...
deeppavlov/models/elmo/elmo_model.py
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], ...
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], ...
[ "options", "contains", "key", "char_cnn", ":", "{" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/elmo_model.py#L292-L462
[ "def", "_build_word_char_embeddings", "(", "self", ")", ":", "projection_dim", "=", "self", ".", "options", "[", "'lstm'", "]", "[", "'projection_dim'", "]", "cnn_options", "=", "self", ".", "options", "[", "'char_cnn'", "]", "filters", "=", "cnn_options", "["...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
DatasetReader.read
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``.
deeppavlov/core/data/dataset_reader.py
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
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
[ "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", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/dataset_reader.py#L21-L25
[ "def", "read", "(", "self", ",", "data_path", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Dict", "[", "str", ",", "List", "[", "Tuple", "[", "Any", ",", "Any", "]", "]", "]", ":", "raise", "NotImplementedError" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
make_hello_bot_agent
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.
deeppavlov/agents/hello_bot_agent/hello_bot_agent.py
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...
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...
[ "Builds", "agent", "based", "on", "PatternMatchingSkill", "and", "HighestConfidenceSelector", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/hello_bot_agent/hello_bot_agent.py#L20-L34
[ "def", "make_hello_bot_agent", "(", ")", "->", "DefaultAgent", ":", "skill_hello", "=", "PatternMatchingSkill", "(", "[", "'Hello world'", "]", ",", "patterns", "=", "[", "'hi'", ",", "'hello'", ",", "'good day'", "]", ")", "skill_bye", "=", "PatternMatchingSkil...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
to_one_hot
Takes an array of integers and transforms it to an array of one-hot encoded vectors
deeppavlov/models/morpho_tagger/common_tagger.py
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]
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]
[ "Takes", "an", "array", "of", "integers", "and", "transforms", "it", "to", "an", "array", "of", "one", "-", "hot", "encoded", "vectors" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/common_tagger.py#L14-L20
[ "def", "to_one_hot", "(", "x", ",", "k", ")", ":", "unit", "=", "np", ".", "eye", "(", "k", ",", "dtype", "=", "int", ")", "return", "unit", "[", "x", "]" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
prettify_metrics
Prettifies the dictionary of metrics.
deeppavlov/core/trainers/utils.py
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
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
[ "Prettifies", "the", "dictionary", "of", "metrics", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/trainers/utils.py#L41-L47
[ "def", "prettify_metrics", "(", "metrics", ":", "List", "[", "Tuple", "[", "str", ",", "float", "]", "]", ",", "precision", ":", "int", "=", "4", ")", "->", "OrderedDict", ":", "prettified_metrics", "=", "OrderedDict", "(", ")", "for", "key", ",", "val...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
populate_settings_dir
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
deeppavlov/core/common/paths.py
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 ...
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 ...
[ "Populate", "settings", "directory", "with", "default", "settings", "files" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/common/paths.py#L36-L57
[ "def", "populate_settings_dir", "(", "force", ":", "bool", "=", "False", ")", "->", "bool", ":", "res", "=", "False", "if", "_default_settings_path", "==", "_settings_path", ":", "return", "res", "for", "src", "in", "list", "(", "_default_settings_path", ".", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Tracker.update_state
Updates dialogue state with new ``slots``, calculates features. Returns: Tracker: .
deeppavlov/models/go_bot/tracker.py
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
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
[ "Updates", "dialogue", "state", "with", "new", "slots", "calculates", "features", ".", "Returns", ":", "Tracker", ":", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/go_bot/tracker.py#L35-L42
[ "def", "update_state", "(", "self", ",", "slots", ":", "Union", "[", "List", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "'Tracker'", ":", "pass" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
predict_with_model
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 tags or a list of full CONLL-U descriptions.
deeppavlov/models/morpho_tagger/common.py
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...
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...
[ "Returns", "predictions", "of", "morphotagging", "model", "given", "in", "config", ":", "config_path", ":", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/common.py#L14-L52
[ "def", "predict_with_model", "(", "config_path", ":", "[", "Path", ",", "str", "]", ")", "->", "List", "[", "Optional", "[", "List", "[", "str", "]", "]", "]", ":", "config", "=", "parse_config", "(", "config_path", ")", "reader_config", "=", "config", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
run_alexa_server
Initiates Flask web service with Alexa skill. Args: agent_generator: Callback Alexa agents factory. multi_instance: Multi instance mode flag. stateful: Stateful mode flag. port: Flask web service port. https: Flag for running Alexa skill service in https mode. ssl_ke...
deeppavlov/utils/alexa/server.py
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) ...
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) ...
[ "Initiates", "Flask", "web", "service", "with", "Alexa", "skill", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/server.py#L84-L274
[ "def", "run_alexa_server", "(", "agent_generator", ":", "callable", ",", "multi_instance", ":", "bool", "=", "False", ",", "stateful", ":", "bool", "=", "False", ",", "port", ":", "Optional", "[", "int", "]", "=", "None", ",", "https", ":", "bool", "=", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
TFModel.load
Load model parameters from self.load_path
deeppavlov/core/models/tf_model.py
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...
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...
[ "Load", "model", "parameters", "from", "self", ".", "load_path" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/tf_model.py#L42-L54
[ "def", "load", "(", "self", ",", "exclude_scopes", ":", "tuple", "=", "(", "'Optimizer'", ",", ")", ")", "->", "None", ":", "if", "not", "hasattr", "(", "self", ",", "'sess'", ")", ":", "raise", "RuntimeError", "(", "'Your TensorFlow model {} must'", "' ha...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
TFModel.save
Save model parameters to self.save_path
deeppavlov/core/models/tf_model.py
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 ...
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 ...
[ "Save", "model", "parameters", "to", "self", ".", "save_path" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/tf_model.py#L68-L77
[ "def", "save", "(", "self", ",", "exclude_scopes", ":", "tuple", "=", "(", "'Optimizer'", ",", ")", ")", "->", "None", ":", "if", "not", "hasattr", "(", "self", ",", "'sess'", ")", ":", "raise", "RuntimeError", "(", "'Your TensorFlow model {} must'", "' ha...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
TFModel.get_train_op
Get train operation for given loss Args: loss: loss, tf tensor or scalar learning_rate: scalar or placeholder. clip_norm: clip gradients norm by clip_norm. learnable_scopes: which scopes are trainable (None for all). optimizer: instance of tf.train.Op...
deeppavlov/core/models/tf_model.py
def get_train_op(self, loss, learning_rate, optimizer=None, clip_norm=None, learnable_scopes=None, optimizer_scope_name=None, **kwargs): """ Get train operat...
def get_train_op(self, loss, learning_rate, optimizer=None, clip_norm=None, learnable_scopes=None, optimizer_scope_name=None, **kwargs): """ Get train operat...
[ "Get", "train", "operation", "for", "given", "loss" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/tf_model.py#L97-L149
[ "def", "get_train_op", "(", "self", ",", "loss", ",", "learning_rate", ",", "optimizer", "=", "None", ",", "clip_norm", "=", "None", ",", "learnable_scopes", "=", "None", ",", "optimizer_scope_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
TFModel.print_number_of_parameters
Print number of *trainable* parameters in the network
deeppavlov/core/models/tf_model.py
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...
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...
[ "Print", "number", "of", "*", "trainable", "*", "parameters", "in", "the", "network" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/tf_model.py#L152-L167
[ "def", "print_number_of_parameters", "(", ")", ":", "log", ".", "info", "(", "'Number of parameters: '", ")", "variables", "=", "tf", ".", "trainable_variables", "(", ")", "blocks", "=", "defaultdict", "(", "int", ")", "for", "var", "in", "variables", ":", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
_precompute_absense_costs
Вычисляет минимальную стоимость появления нового символа в узлах словаря в соответствии со штрафами из costs Аргументы: --------------- dictionary : Trie словарь, хранящийся в виде ациклического автомата removal_costs : dict штрафы за удаление символов insertion_costs : dict ...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _precompute_absense_costs(dictionary, removal_costs, insertion_costs, n, allow_spaces=False): """ Вычисляет минимальную стоимость появления нового символа в узлах словаря в соответствии со штрафами из costs Аргументы: --------------- dictionary : Trie с...
def _precompute_absense_costs(dictionary, removal_costs, insertion_costs, n, allow_spaces=False): """ Вычисляет минимальную стоимость появления нового символа в узлах словаря в соответствии со штрафами из costs Аргументы: --------------- dictionary : Trie с...
[ "Вычисляет", "минимальную", "стоимость", "появления", "нового", "символа", "в", "узлах", "словаря", "в", "соответствии", "со", "штрафами", "из", "costs" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L214-L269
[ "def", "_precompute_absense_costs", "(", "dictionary", ",", "removal_costs", ",", "insertion_costs", ",", "n", ",", "allow_spaces", "=", "False", ")", ":", "answer", "=", "[", "dict", "(", ")", "for", "node", "in", "dictionary", ".", "data", "]", "if", "n"...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LevenshteinSearcher.search
Finds all dictionary words in d-window from word
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
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...
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...
[ "Finds", "all", "dictionary", "words", "in", "d", "-", "window", "from", "word" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L44-L53
[ "def", "search", "(", "self", ",", "word", ",", "d", ",", "allow_spaces", "=", "True", ",", "return_cost", "=", "True", ")", ":", "if", "not", "all", "(", "(", "c", "in", "self", ".", "alphabet", "or", "(", "c", "==", "\" \"", "and", "self", ".",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LevenshteinSearcher._trie_search
Находит все слова в префиксном боре, расстояние до которых в соответствии с заданным преобразователем не превышает d
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _trie_search(self, word, d, transducer=None, allow_spaces=True, return_cost=True): """ Находит все слова в префиксном боре, расстояние до которых в соответствии с заданным преобразователем не превышает d """ if transducer is None: # разобратьс...
def _trie_search(self, word, d, transducer=None, allow_spaces=True, return_cost=True): """ Находит все слова в префиксном боре, расстояние до которых в соответствии с заданным преобразователем не превышает d """ if transducer is None: # разобратьс...
[ "Находит", "все", "слова", "в", "префиксном", "боре", "расстояние", "до", "которых", "в", "соответствии", "с", "заданным", "преобразователем", "не", "превышает", "d" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L55-L121
[ "def", "_trie_search", "(", "self", ",", "word", ",", "d", ",", "transducer", "=", "None", ",", "allow_spaces", "=", "True", ",", "return_cost", "=", "True", ")", ":", "if", "transducer", "is", "None", ":", "# разобраться с пробелами", "transducer", "=", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LevenshteinSearcher._precompute_euristics
Предвычисляет будущие символы и стоимости операций с ними для h-эвристики
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _precompute_euristics(self): """ Предвычисляет будущие символы и стоимости операций с ними для h-эвристики """ if self.euristics is None: return # вычисление минимальной стоимости операции, # приводящей к появлению ('+') или исчезновению ('-') данн...
def _precompute_euristics(self): """ Предвычисляет будущие символы и стоимости операций с ними для h-эвристики """ if self.euristics is None: return # вычисление минимальной стоимости операции, # приводящей к появлению ('+') или исчезновению ('-') данн...
[ "Предвычисляет", "будущие", "символы", "и", "стоимости", "операций", "с", "ними", "для", "h", "-", "эвристики" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L123-L156
[ "def", "_precompute_euristics", "(", "self", ")", ":", "if", "self", ".", "euristics", "is", "None", ":", "return", "# вычисление минимальной стоимости операции,", "# приводящей к появлению ('+') или исчезновению ('-') данного символа", "removal_costs", "=", "{", "a", ":", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LevenshteinSearcher._euristic_h_function
Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря Аргументы: ---------- suffix : string непрочитанный суффикс входного слова index : int индекс текущего узла в словаре Возвращает: ----------- cost : float ...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _euristic_h_function(self, suffix, index): """ Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря Аргументы: ---------- suffix : string непрочитанный суффикс входного слова index : int индекс текущего узла в словаре ...
def _euristic_h_function(self, suffix, index): """ Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря Аргументы: ---------- suffix : string непрочитанный суффикс входного слова index : int индекс текущего узла в словаре ...
[ "Вычисление", "h", "-", "эвристики", "из", "работы", "Hulden", "2009", "для", "текущей", "вершины", "словаря" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L164-L199
[ "def", "_euristic_h_function", "(", "self", ",", "suffix", ",", "index", ")", ":", "if", "self", ".", "euristics", ">", "0", ":", "suffix", "=", "suffix", "[", ":", "self", ".", "euristics", "]", "# кэширование результатов", "index_temporary_euristics", "=", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer.get_operation_cost
Возвращает стоимость элементарной трансдукции up->low или np.inf, если такой элементарной трансдукции нет Аргументы: ---------- up, low : string элементы элементарной трансдукции Возвращает: ----------- cost : float стоимость элементарной...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def get_operation_cost(self, up, low): """ Возвращает стоимость элементарной трансдукции up->low или np.inf, если такой элементарной трансдукции нет Аргументы: ---------- up, low : string элементы элементарной трансдукции Возвращает: --------...
def get_operation_cost(self, up, low): """ Возвращает стоимость элементарной трансдукции up->low или np.inf, если такой элементарной трансдукции нет Аргументы: ---------- up, low : string элементы элементарной трансдукции Возвращает: --------...
[ "Возвращает", "стоимость", "элементарной", "трансдукции", "up", "-", ">", "low", "или", "np", ".", "inf", "если", "такой", "элементарной", "трансдукции", "нет" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L308-L328
[ "def", "get_operation_cost", "(", "self", ",", "up", ",", "low", ")", ":", "up_costs", "=", "self", ".", "operation_costs", ".", "get", "(", "up", ",", "None", ")", "if", "up_costs", "is", "None", ":", "return", "np", ".", "inf", "cost", "=", "up_cos...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer.inverse
Строит пробразователь, задающий обратное конечное преобразование
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def inverse(self): """ Строит пробразователь, задающий обратное конечное преобразование """ # УПРОСТИТЬ ОБРАЩЕНИЕ!!! inversed_transducer = SegmentTransducer(self.alphabet, operation_costs=dict()) inversed_transducer.operation_costs = self._reversed_operation_costs ...
def inverse(self): """ Строит пробразователь, задающий обратное конечное преобразование """ # УПРОСТИТЬ ОБРАЩЕНИЕ!!! inversed_transducer = SegmentTransducer(self.alphabet, operation_costs=dict()) inversed_transducer.operation_costs = self._reversed_operation_costs ...
[ "Строит", "пробразователь", "задающий", "обратное", "конечное", "преобразование" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L330-L342
[ "def", "inverse", "(", "self", ")", ":", "# УПРОСТИТЬ ОБРАЩЕНИЕ!!!", "inversed_transducer", "=", "SegmentTransducer", "(", "self", ".", "alphabet", ",", "operation_costs", "=", "dict", "(", ")", ")", "inversed_transducer", ".", "operation_costs", "=", "self", ".",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer.distance
Вычисляет трансдукцию минимальной стоимости, отображающую first в second Аргументы: ----------- first : string second : string Верхний и нижний элементы трансдукции return_transduction : bool (optional, default=False) следует ли возвращать трансд...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def distance(self, first, second, return_transduction = False): """ Вычисляет трансдукцию минимальной стоимости, отображающую first в second Аргументы: ----------- first : string second : string Верхний и нижний элементы трансдукции return_tr...
def distance(self, first, second, return_transduction = False): """ Вычисляет трансдукцию минимальной стоимости, отображающую first в second Аргументы: ----------- first : string second : string Верхний и нижний элементы трансдукции return_tr...
[ "Вычисляет", "трансдукцию", "минимальной", "стоимости", "отображающую", "first", "в", "second" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L344-L387
[ "def", "distance", "(", "self", ",", "first", ",", "second", ",", "return_transduction", "=", "False", ")", ":", "if", "return_transduction", ":", "add_pred", "=", "(", "lambda", "x", ",", "y", ":", "(", "y", "==", "np", ".", "inf", "or", "x", "<", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer.transduce
Возвращает все трансдукции, переводящие first в second, чья стоимость не превышает threshold Возвращает: ---------- result : list список вида [(трансдукция, стоимость)]
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def transduce(self, first, second, threshold): """ Возвращает все трансдукции, переводящие first в second, чья стоимость не превышает threshold Возвращает: ---------- result : list список вида [(трансдукция, стоимость)] """ add_pred = (lambda ...
def transduce(self, first, second, threshold): """ Возвращает все трансдукции, переводящие first в second, чья стоимость не превышает threshold Возвращает: ---------- result : list список вида [(трансдукция, стоимость)] """ add_pred = (lambda ...
[ "Возвращает", "все", "трансдукции", "переводящие", "first", "в", "second", "чья", "стоимость", "не", "превышает", "threshold" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L389-L407
[ "def", "transduce", "(", "self", ",", "first", ",", "second", ",", "threshold", ")", ":", "add_pred", "=", "(", "lambda", "x", ",", "y", ":", "x", "<=", "threshold", ")", "clear_pred", "=", "(", "lambda", "x", ",", "y", ":", "False", ")", "update_f...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer.lower_transductions
Возвращает все трансдукции с верхним элементом word, чья стоимость не превышает max_cost ` Возвращает: ---------- result : list список вида [(трансдукция, стоимость)], если return_cost=True список трансдукций, если return_cost=False список отсортирован ...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def lower_transductions(self, word, max_cost, return_cost=True): """ Возвращает все трансдукции с верхним элементом word, чья стоимость не превышает max_cost ` Возвращает: ---------- result : list список вида [(трансдукция, стоимость)], если return_cost=True ...
def lower_transductions(self, word, max_cost, return_cost=True): """ Возвращает все трансдукции с верхним элементом word, чья стоимость не превышает max_cost ` Возвращает: ---------- result : list список вида [(трансдукция, стоимость)], если return_cost=True ...
[ "Возвращает", "все", "трансдукции", "с", "верхним", "элементом", "word", "чья", "стоимость", "не", "превышает", "max_cost" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L409-L439
[ "def", "lower_transductions", "(", "self", ",", "word", ",", "max_cost", ",", "return_cost", "=", "True", ")", ":", "prefixes", "=", "[", "[", "]", "for", "i", "in", "range", "(", "len", "(", "word", ")", "+", "1", ")", "]", "prefixes", "[", "0", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer._fill_levenshtein_table
Функция, динамически заполняющая таблицу costs стоимости трансдукций, costs[i][j] --- минимальная стоимость трансдукции, переводящей first[:i] в second[:j] Аргументы: ---------- first, second : string Верхний и нижний элементы трансдукции update_func : callab...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _fill_levenshtein_table(self, first, second, update_func, add_pred, clear_pred, threshold=None): """ Функция, динамически заполняющая таблицу costs стоимости трансдукций, costs[i][j] --- минимальная стоимость трансдукции, переводящей first[:i] в second[...
def _fill_levenshtein_table(self, first, second, update_func, add_pred, clear_pred, threshold=None): """ Функция, динамически заполняющая таблицу costs стоимости трансдукций, costs[i][j] --- минимальная стоимость трансдукции, переводящей first[:i] в second[...
[ "Функция", "динамически", "заполняющая", "таблицу", "costs", "стоимости", "трансдукций", "costs", "[", "i", "]", "[", "j", "]", "---", "минимальная", "стоимость", "трансдукции", "переводящей", "first", "[", ":", "i", "]", "в", "second", "[", ":", "j", "]" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L463-L543
[ "def", "_fill_levenshtein_table", "(", "self", ",", "first", ",", "second", ",", "update_func", ",", "add_pred", ",", "clear_pred", ",", "threshold", "=", "None", ")", ":", "m", ",", "n", "=", "len", "(", "first", ")", ",", "len", "(", "second", ")", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer._make_reversed_operation_costs
Заполняет массив _reversed_operation_costs на основе имеющегося массива operation_costs
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
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(): ...
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(): ...
[ "Заполняет", "массив", "_reversed_operation_costs", "на", "основе", "имеющегося", "массива", "operation_costs" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L545-L556
[ "def", "_make_reversed_operation_costs", "(", "self", ")", ":", "_reversed_operation_costs", "=", "dict", "(", ")", "for", "up", ",", "costs", "in", "self", ".", "operation_costs", ".", "items", "(", ")", ":", "for", "low", ",", "cost", "in", "costs", ".",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer._make_maximal_key_lengths
Вычисляет максимальную длину элемента low в элементарной трансдукции (up, low) для каждого up и максимальную длину элемента up в элементарной трансдукции (up, low) для каждого low
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _make_maximal_key_lengths(self): """ Вычисляет максимальную длину элемента low в элементарной трансдукции (up, low) для каждого up и максимальную длину элемента up в элементарной трансдукции (up, low) для каждого low """ self.max_up_length =\ (max(...
def _make_maximal_key_lengths(self): """ Вычисляет максимальную длину элемента low в элементарной трансдукции (up, low) для каждого up и максимальную длину элемента up в элементарной трансдукции (up, low) для каждого low """ self.max_up_length =\ (max(...
[ "Вычисляет", "максимальную", "длину", "элемента", "low", "в", "элементарной", "трансдукции", "(", "up", "low", ")", "для", "каждого", "up", "и", "максимальную", "длину", "элемента", "up", "в", "элементарной", "трансдукции", "(", "up", "low", ")", "для", "каждо...
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L558-L577
[ "def", "_make_maximal_key_lengths", "(", "self", ")", ":", "self", ".", "max_up_length", "=", "(", "max", "(", "len", "(", "up", ")", "for", "up", "in", "self", ".", "operation_costs", ")", "if", "len", "(", "self", ".", "operation_costs", ")", ">", "0...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer._backtraces_to_transductions
Восстанавливает трансдукции по таблице обратных ссылок Аргументы: ---------- first, second : string верхние и нижние элементы трансдукции backtraces : array-like, dtype=list, shape=(len(first)+1, len(second)+1) таблица обратных ссылок threshold : float ...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _backtraces_to_transductions(self, first, second, backtraces, threshold, return_cost=False): """ Восстанавливает трансдукции по таблице обратных ссылок Аргументы: ---------- first, second : string верхние и нижние элементы трансдукции backtraces : array-l...
def _backtraces_to_transductions(self, first, second, backtraces, threshold, return_cost=False): """ Восстанавливает трансдукции по таблице обратных ссылок Аргументы: ---------- first, second : string верхние и нижние элементы трансдукции backtraces : array-l...
[ "Восстанавливает", "трансдукции", "по", "таблице", "обратных", "ссылок" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L579-L623
[ "def", "_backtraces_to_transductions", "(", "self", ",", "first", ",", "second", ",", "backtraces", ",", "threshold", ",", "return_cost", "=", "False", ")", ":", "m", ",", "n", "=", "len", "(", "first", ")", ",", "len", "(", "second", ")", "agenda", "=...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer._perform_insertions
возвращает все трансдукции стоимости <= max_cost, которые можно получить из элементов initial Аргументы: ---------- initial : list of tuples список исходных трансдукций вида [(трансдукция, стоимость)] max_cost : float максимальная стоимость трансдукции ...
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
def _perform_insertions(self, initial, max_cost): """ возвращает все трансдукции стоимости <= max_cost, которые можно получить из элементов initial Аргументы: ---------- initial : list of tuples список исходных трансдукций вида [(трансдукция, стоимость)] ...
def _perform_insertions(self, initial, max_cost): """ возвращает все трансдукции стоимости <= max_cost, которые можно получить из элементов initial Аргументы: ---------- initial : list of tuples список исходных трансдукций вида [(трансдукция, стоимость)] ...
[ "возвращает", "все", "трансдукции", "стоимости", "<", "=", "max_cost", "которые", "можно", "получить", "из", "элементов", "initial" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L625-L653
[ "def", "_perform_insertions", "(", "self", ",", "initial", ",", "max_cost", ")", ":", "queue", "=", "list", "(", "initial", ")", "final", "=", "initial", "while", "len", "(", "queue", ")", ">", "0", ":", "transduction", ",", "cost", "=", "queue", "[", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
SegmentTransducer._make_default_operation_costs
sets 1.0 cost for every replacement, insertion, deletion and transposition
deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py
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: ...
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: ...
[ "sets", "1", ".", "0", "cost", "for", "every", "replacement", "insertion", "deletion", "and", "transposition" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/levenshtein_searcher.py#L655-L674
[ "def", "_make_default_operation_costs", "(", "self", ",", "allow_spaces", "=", "False", ")", ":", "self", ".", "operation_costs", "=", "dict", "(", ")", "self", ".", "operation_costs", "[", "\"\"", "]", "=", "{", "c", ":", "1.0", "for", "c", "in", "list"...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Conversation._start_timer
Initiates self-destruct timer.
deeppavlov/utils/alexa/conversation.py
def _start_timer(self) -> None: """Initiates self-destruct timer.""" self.timer = Timer(self.config['conversation_lifetime'], self.self_destruct_callback) self.timer.start()
def _start_timer(self) -> None: """Initiates self-destruct timer.""" self.timer = Timer(self.config['conversation_lifetime'], self.self_destruct_callback) self.timer.start()
[ "Initiates", "self", "-", "destruct", "timer", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/conversation.py#L69-L72
[ "def", "_start_timer", "(", "self", ")", "->", "None", ":", "self", ".", "timer", "=", "Timer", "(", "self", ".", "config", "[", "'conversation_lifetime'", "]", ",", "self", ".", "self_destruct_callback", ")", "self", ".", "timer", ".", "start", "(", ")"...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Conversation.handle_request
Routes Alexa requests to appropriate handlers. Args: request: Alexa request. Returns: response: Response conforming Alexa response specification.
deeppavlov/utils/alexa/conversation.py
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...
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...
[ "Routes", "Alexa", "requests", "to", "appropriate", "handlers", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/conversation.py#L79-L99
[ "def", "handle_request", "(", "self", ",", "request", ":", "dict", ")", "->", "dict", ":", "request_type", "=", "request", "[", "'request'", "]", "[", "'type'", "]", "request_id", "=", "request", "[", "'request'", "]", "[", "'requestId'", "]", "log", "."...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Conversation._act
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.
deeppavlov/utils/alexa/conversation.py
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: ...
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: ...
[ "Infers", "DeepPavlov", "agent", "with", "raw", "user", "input", "extracted", "from", "Alexa", "request", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/conversation.py#L101-L116
[ "def", "_act", "(", "self", ",", "utterance", ":", "str", ")", "->", "list", ":", "if", "self", ".", "stateful", ":", "utterance", "=", "[", "[", "utterance", "]", ",", "[", "self", ".", "key", "]", "]", "else", ":", "utterance", "=", "[", "[", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Conversation._generate_response
Populates generated response with additional data conforming Alexa response specification. Args: response: Raw user input extracted from Alexa request. request: Alexa request. Returns: response: Response conforming Alexa response specification.
deeppavlov/utils/alexa/conversation.py
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...
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...
[ "Populates", "generated", "response", "with", "additional", "data", "conforming", "Alexa", "response", "specification", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/conversation.py#L118-L134
[ "def", "_generate_response", "(", "self", ",", "response", ":", "dict", ",", "request", ":", "dict", ")", "->", "dict", ":", "response_template", "=", "deepcopy", "(", "self", ".", "response_template", ")", "response_template", "[", "'sessionAttributes'", "]", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Conversation._handle_intent
Handles IntentRequest Alexa request. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification.
deeppavlov/utils/alexa/conversation.py
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'] ...
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", "IntentRequest", "Alexa", "request", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/conversation.py#L136-L174
[ "def", "_handle_intent", "(", "self", ",", "request", ":", "dict", ")", "->", "dict", ":", "intent_name", "=", "self", ".", "config", "[", "'intent_name'", "]", "slot_name", "=", "self", ".", "config", "[", "'slot_name'", "]", "request_id", "=", "request",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Conversation._handle_launch
Handles LaunchRequest Alexa request. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification.
deeppavlov/utils/alexa/conversation.py
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': { ...
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", "LaunchRequest", "Alexa", "request", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/conversation.py#L176-L200
[ "def", "_handle_launch", "(", "self", ",", "request", ":", "dict", ")", "->", "dict", ":", "response", "=", "{", "'response'", ":", "{", "'shouldEndSession'", ":", "False", ",", "'outputSpeech'", ":", "{", "'type'", ":", "'PlainText'", ",", "'text'", ":", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Conversation._handle_unsupported
Handles all unsupported types of Alexa requests. Returns standard message. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification.
deeppavlov/utils/alexa/conversation.py
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...
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...
[ "Handles", "all", "unsupported", "types", "of", "Alexa", "requests", ".", "Returns", "standard", "message", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/conversation.py#L214-L238
[ "def", "_handle_unsupported", "(", "self", ",", "request", ":", "dict", ")", "->", "dict", ":", "response", "=", "{", "'response'", ":", "{", "'shouldEndSession'", ":", "False", ",", "'outputSpeech'", ":", "{", "'type'", ":", "'PlainText'", ",", "'text'", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Struct._repr_pretty_
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
deeppavlov/configs/__init__.py
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...
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...
[ "method", "that", "defines", "Struct", "s", "pretty", "printing", "rules", "for", "iPython" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/configs/__init__.py#L56-L67
[ "def", "_repr_pretty_", "(", "self", ",", "p", ",", "cycle", ")", ":", "if", "cycle", ":", "p", ".", "text", "(", "'Struct(...)'", ")", "else", ":", "with", "p", ".", "group", "(", "7", ",", "'Struct('", ",", "')'", ")", ":", "p", ".", "pretty", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
elmo_loss2ppl
Calculates perplexity by loss Args: losses: list of numpy arrays of model losses Returns: perplexity : float
deeppavlov/metrics/elmo_metrics.py
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))
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))
[ "Calculates", "perplexity", "by", "loss" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/elmo_metrics.py#L23-L33
[ "def", "elmo_loss2ppl", "(", "losses", ":", "List", "[", "np", ".", "ndarray", "]", ")", "->", "float", ":", "avg_loss", "=", "np", ".", "mean", "(", "losses", ")", "return", "float", "(", "np", ".", "exp", "(", "avg_loss", ")", ")" ]
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LanguageModel._build_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
deeppavlov/models/elmo/bilm_model.py
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'] ...
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'] ...
[ "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" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/bilm_model.py#L412-L509
[ "def", "_build_loss", "(", "self", ",", "lstm_outputs", ")", ":", "batch_size", "=", "self", ".", "options", "[", "'batch_size'", "]", "unroll_steps", "=", "self", ".", "options", "[", "'unroll_steps'", "]", "n_tokens_vocab", "=", "self", ".", "options", "["...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
build_model
Build and return the model described in corresponding configuration file.
deeppavlov/core/commands/infer.py
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) ...
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) ...
[ "Build", "and", "return", "the", "model", "described", "in", "corresponding", "configuration", "file", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/commands/infer.py#L30-L70
[ "def", "build_model", "(", "config", ":", "Union", "[", "str", ",", "Path", ",", "dict", "]", ",", "mode", ":", "str", "=", "'infer'", ",", "load_trained", ":", "bool", "=", "False", ",", "download", ":", "bool", "=", "False", ",", "serialized", ":",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
interact_model
Start interaction with the model described in corresponding configuration file.
deeppavlov/core/commands/infer.py
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...
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...
[ "Start", "interaction", "with", "the", "model", "described", "in", "corresponding", "configuration", "file", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/commands/infer.py#L73-L89
[ "def", "interact_model", "(", "config", ":", "Union", "[", "str", ",", "Path", ",", "dict", "]", ")", "->", "None", ":", "model", "=", "build_model", "(", "config", ")", "while", "True", ":", "args", "=", "[", "]", "for", "in_x", "in", "model", "."...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
predict_on_stream
Make a prediction with the component described in corresponding configuration file.
deeppavlov/core/commands/infer.py
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('...
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('...
[ "Make", "a", "prediction", "with", "the", "component", "described", "in", "corresponding", "configuration", "file", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/commands/infer.py#L92-L122
[ "def", "predict_on_stream", "(", "config", ":", "Union", "[", "str", ",", "Path", ",", "dict", "]", ",", "batch_size", ":", "int", "=", "1", ",", "file_path", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "if", "file_path", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
read_infile
Reads input file in CONLL-U format Args: infile: a path to a file word_column: column containing words (default=1) pos_column: column containing part-of-speech labels (default=3) tag_column: column containing fine-grained tags (default=5) max_sents: maximal number of sents t...
deeppavlov/dataset_readers/morphotagging_dataset_reader.py
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 ...
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 ...
[ "Reads", "input", "file", "in", "CONLL", "-", "U", "format" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/dataset_readers/morphotagging_dataset_reader.py#L33-L81
[ "def", "read_infile", "(", "infile", ":", "Union", "[", "Path", ",", "str", "]", ",", "from_words", "=", "False", ",", "word_column", ":", "int", "=", "WORD_COLUMN", ",", "pos_column", ":", "int", "=", "POS_COLUMN", ",", "tag_column", ":", "int", "=", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
preprocess_data
Processes all words in data using :func:`~deeppavlov.dataset_iterators.morphotagger_iterator.process_word`. Args: data: a list of pairs (words, tags), each pair corresponds to a single sentence to_lower: whether to lowercase append_case: whether to add case mark Returns: a ...
deeppavlov/dataset_iterators/morphotagger_iterator.py
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:...
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:...
[ "Processes", "all", "words", "in", "data", "using", ":", "func", ":", "~deeppavlov", ".", "dataset_iterators", ".", "morphotagger_iterator", ".", "process_word", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/dataset_iterators/morphotagger_iterator.py#L25-L45
[ "def", "preprocess_data", "(", "data", ":", "List", "[", "Tuple", "[", "List", "[", "str", "]", ",", "List", "[", "str", "]", "]", "]", ",", "to_lower", ":", "bool", "=", "True", ",", "append_case", ":", "str", "=", "\"first\"", ")", "->", "List", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
fn_from_str
Returns a function object with the name given in string.
deeppavlov/core/common/metrics_registry.py
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 `{}`' ...
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 `{}`' ...
[ "Returns", "a", "function", "object", "with", "the", "name", "given", "in", "string", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/common/metrics_registry.py#L19-L27
[ "def", "fn_from_str", "(", "name", ":", "str", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "try", ":", "module_name", ",", "fn_name", "=", "name", ".", "split", "(", "':'", ")", "except", "ValueError", ":", "raise", "ConfigError", "(", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
register_metric
Decorator for metric registration.
deeppavlov/core/common/metrics_registry.py
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...
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...
[ "Decorator", "for", "metric", "registration", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/common/metrics_registry.py#L30-L39
[ "def", "register_metric", "(", "metric_name", ":", "str", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "def", "decorate", "(", "fn", ")", ":", "fn_name", "=", "fn", ".", "__module__", "+", "':'", "+", "fn", ".", "__name__", "if", "metric_...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
get_metric_by_name
Returns a metric callable with a corresponding name.
deeppavlov/core/common/metrics_registry.py
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])
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])
[ "Returns", "a", "metric", "callable", "with", "a", "corresponding", "name", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/common/metrics_registry.py#L42-L46
[ "def", "get_metric_by_name", "(", "name", ":", "str", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "if", "name", "not", "in", "_REGISTRY", ":", "raise", "ConfigError", "(", "f'\"{name}\" is not registered as a metric'", ")", "return", "fn_from_str", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
DecayType.from_str
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 a polynomial power Returns: index of ...
deeppavlov/core/models/lr_scheduled_model.py
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 ...
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 ...
[ "Convert", "given", "string", "label", "of", "decay", "type", "to", "special", "index" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/lr_scheduled_model.py#L40-L56
[ "def", "from_str", "(", "cls", ",", "label", ":", "str", ")", "->", "int", ":", "label_norm", "=", "label", ".", "replace", "(", "'1'", ",", "'one'", ")", ".", "upper", "(", ")", "if", "label_norm", "in", "cls", ".", "__members__", ":", "return", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LRScheduledModel.fit
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 Returns:
deeppavlov/core/models/lr_scheduled_model.py
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 ...
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", "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"...
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/lr_scheduled_model.py#L294-L371
[ "def", "fit", "(", "self", ",", "*", "args", ")", ":", "data", "=", "list", "(", "zip", "(", "*", "args", ")", ")", "self", ".", "save", "(", ")", "if", "self", ".", "_fit_batch_size", "is", "None", ":", "raise", "ConfigError", "(", "\"in order to ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LRScheduledModel._get_best
Find the best value according to given losses Args: values: list of considered values losses: list of obtained loss values corresponding to `values` max_loss_div: maximal divergence of loss to be considered significant min_val_div: minimum divergence of loss to b...
deeppavlov/core/models/lr_scheduled_model.py
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...
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...
[ "Find", "the", "best", "value", "according", "to", "given", "losses" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/lr_scheduled_model.py#L374-L394
[ "def", "_get_best", "(", "values", ":", "List", "[", "float", "]", ",", "losses", ":", "List", "[", "float", "]", ",", "max_loss_div", ":", "float", "=", "0.9", ",", "min_val_div", ":", "float", "=", "10.0", ")", "->", "float", ":", "assert", "len", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
LRScheduledModel.process_event
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"`, `"after_epoch"`, `"after_train_log"` data: dictionary with paramet...
deeppavlov/core/models/lr_scheduled_model.py
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...
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...
[ "Update", "learning", "rate", "and", "momentum", "variables", "after", "event", "(", "given", "by", "event_name", ")" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/lr_scheduled_model.py#L396-L442
[ "def", "process_event", "(", "self", ",", "event_name", ":", "str", ",", "data", ":", "dict", ")", "->", "None", ":", "if", "event_name", "==", "\"after_validation\"", ":", "if", "data", "[", "'impatience'", "]", ">", "self", ".", "_learning_rate_last_impati...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
Embedder._encode
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 array of mean values
deeppavlov/models/embedders/abstract_embedder.py
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...
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...
[ "Embed", "one", "text", "sample" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/embedders/abstract_embedder.py#L103-L135
[ "def", "_encode", "(", "self", ",", "tokens", ":", "List", "[", "str", "]", ",", "mean", ":", "bool", ")", "->", "Union", "[", "List", "[", "np", ".", "ndarray", "]", ",", "np", ".", "ndarray", "]", ":", "embedded_tokens", "=", "[", "]", "for", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
read_requirements
parses requirements from requirements.txt
setup.py
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: ...
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: ...
[ "parses", "requirements", "from", "requirements", ".", "txt" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/setup.py#L22-L35
[ "def", "read_requirements", "(", ")", ":", "reqs_path", "=", "os", ".", "path", ".", "join", "(", "__location__", ",", "'requirements.txt'", ")", "with", "open", "(", "reqs_path", ",", "encoding", "=", "'utf8'", ")", "as", "f", ":", "reqs", "=", "[", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
detokenize
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.
deeppavlov/models/tokenizers/utils.py
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...
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...
[ "Detokenizing", "a", "text", "undoes", "the", "tokenizing", "operation", "restores", "punctuation", "and", "spaces", "to", "the", "places", "that", "people", "expect", "them", "to", "be", ".", "Ideally", "detokenize", "(", "tokenize", "(", "text", "))", "shoul...
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/tokenizers/utils.py#L19-L35
[ "def", "detokenize", "(", "tokens", ")", ":", "text", "=", "' '", ".", "join", "(", "tokens", ")", "step0", "=", "text", ".", "replace", "(", "'. . .'", ",", "'...'", ")", "step1", "=", "step0", ".", "replace", "(", "\"`` \"", ",", "'\"'", ")", "."...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
ngramize
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
deeppavlov/models/tokenizers/utils.py
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),...
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),...
[ "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", ...
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/tokenizers/utils.py#L38-L54
[ "def", "ngramize", "(", "items", ":", "List", "[", "str", "]", ",", "ngram_range", "=", "(", "1", ",", "1", ")", ")", "->", "Generator", "[", "List", "[", "str", "]", ",", "Any", ",", "None", "]", ":", "ngrams", "=", "[", "]", "ranges", "=", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
sk_log_loss
Calculates log loss. Args: y_true: list or array of true values y_predicted: list or array of predicted values Returns: Log loss
deeppavlov/metrics/log_loss.py
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 ...
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 ...
[ "Calculates", "log", "loss", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/log_loss.py#L25-L37
[ "def", "sk_log_loss", "(", "y_true", ":", "Union", "[", "List", "[", "List", "[", "float", "]", "]", ",", "List", "[", "List", "[", "int", "]", "]", ",", "np", ".", "ndarray", "]", ",", "y_predicted", ":", "Union", "[", "List", "[", "List", "[", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
make_module_spec
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.
deeppavlov/models/elmo/elmo2tfhub.py
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 ...
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 ...
[ "Makes", "a", "module", "spec", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/elmo2tfhub.py#L23-L187
[ "def", "make_module_spec", "(", "options", ",", "weight_file", ")", ":", "def", "module_fn", "(", ")", ":", "\"\"\"Spec function for a token embedding module.\"\"\"", "# init", "_bos_id", "=", "256", "_eos_id", "=", "257", "_bow_id", "=", "258", "_eow_id", "=", "2...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
export2hub
Exports a TF-Hub module
deeppavlov/models/elmo/elmo2tfhub.py
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...
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...
[ "Exports", "a", "TF", "-", "Hub", "module" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/elmo2tfhub.py#L190-L206
[ "def", "export2hub", "(", "weight_file", ",", "hub_dir", ",", "options", ")", ":", "spec", "=", "make_module_spec", "(", "options", ",", "str", "(", "weight_file", ")", ")", "try", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
show_details
Format catalog item output Parameters: item_data: item's attributes values Returns: [rich_message]: list of formatted rich message
deeppavlov/agents/ecommerce_agent/ecommerce_agent.py
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) + "**" + ...
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) + "**" + ...
[ "Format", "catalog", "item", "output" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/ecommerce_agent/ecommerce_agent.py#L158-L173
[ "def", "show_details", "(", "item_data", ":", "Dict", "[", "Any", ",", "Any", "]", ")", "->", "str", ":", "txt", "=", "\"\"", "for", "key", ",", "value", "in", "item_data", ".", "items", "(", ")", ":", "txt", "+=", "\"**\"", "+", "str", "(", "key...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
make_agent
Make an agent Returns: agent: created Ecommerce agent
deeppavlov/agents/ecommerce_agent/ecommerce_agent.py
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
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
[ "Make", "an", "agent" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/ecommerce_agent/ecommerce_agent.py#L176-L186
[ "def", "make_agent", "(", ")", "->", "EcommerceAgent", ":", "config_path", "=", "find_config", "(", "'tfidf_retrieve'", ")", "skill", "=", "build_model", "(", "config_path", ")", "agent", "=", "EcommerceAgent", "(", "skills", "=", "[", "skill", "]", ")", "re...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
main
Parse parameters and run ms bot framework
deeppavlov/agents/ecommerce_agent/ecommerce_agent.py
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)
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)
[ "Parse", "parameters", "and", "run", "ms", "bot", "framework" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/ecommerce_agent/ecommerce_agent.py#L189-L196
[ "def", "main", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "run_ms_bot_framework_server", "(", "agent_generator", "=", "make_agent", ",", "app_id", "=", "args", ".", "ms_id", ",", "app_secret", "=", "args", ".", "ms_secret", ",", "st...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
EcommerceAgent._call
Processes batch of utterances and returns corresponding responses batch. Args: utterances_batch: Batch of incoming utterances. utterances_ids: Batch of dialog IDs corresponding to incoming utterances. Returns: responses: A batch of responses corresponding to the ...
deeppavlov/agents/ecommerce_agent/ecommerce_agent.py
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...
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...
[ "Processes", "batch", "of", "utterances", "and", "returns", "corresponding", "responses", "batch", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/ecommerce_agent/ecommerce_agent.py#L53-L131
[ "def", "_call", "(", "self", ",", "utterances_batch", ":", "List", "[", "str", "]", ",", "utterances_ids", ":", "List", "[", "int", "]", "=", "None", ")", "->", "List", "[", "RichMessage", "]", ":", "rich_message", "=", "RichMessage", "(", ")", "for", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
TemporalDropout
Drops with :dropout probability temporal steps of input 3D tensor
deeppavlov/models/morpho_tagger/cells.py
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) ...
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) ...
[ "Drops", "with", ":", "dropout", "probability", "temporal", "steps", "of", "input", "3D", "tensor" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/cells.py#L141-L155
[ "def", "TemporalDropout", "(", "inputs", ",", "dropout", "=", "0.0", ")", ":", "# TO DO: adapt for >3D tensors", "if", "dropout", "==", "0.0", ":", "return", "inputs", "inputs_func", "=", "lambda", "x", ":", "kb", ".", "ones_like", "(", "inputs", "[", ":", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
positions_func
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
deeppavlov/models/morpho_tagger/cells.py
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,...
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,...
[ "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" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/cells.py#L158-L166
[ "def", "positions_func", "(", "inputs", ",", "pad", "=", "0", ")", ":", "position_inputs", "=", "kb", ".", "cumsum", "(", "kb", ".", "ones_like", "(", "inputs", ",", "dtype", "=", "\"float32\"", ")", ",", "axis", "=", "1", ")", "position_inputs", "*=",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
download
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_download: download file if it already exists, or not
deeppavlov/core/data/utils.py
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...
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...
[ "Download", "a", "file", "from", "URL", "to", "one", "or", "several", "target", "locations" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/utils.py#L83-L125
[ "def", "download", "(", "dest_file_path", ":", "[", "List", "[", "Union", "[", "str", ",", "Path", "]", "]", "]", ",", "source_url", ":", "str", ",", "force_download", "=", "True", ")", ":", "if", "isinstance", "(", "dest_file_path", ",", "list", ")", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
untar
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
deeppavlov/core/data/utils.py
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...
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", "tar", "archive", "extractor" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/utils.py#L128-L142
[ "def", "untar", "(", "file_path", ",", "extract_folder", "=", "None", ")", ":", "file_path", "=", "Path", "(", "file_path", ")", "if", "extract_folder", "is", "None", ":", "extract_folder", "=", "file_path", ".", "parent", "extract_folder", "=", "Path", "(",...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
ungzip
Simple .gz archive extractor Args: file_path: path to the gzip file to be extracted extract_path: path where the file will be extracted
deeppavlov/core/data/utils.py
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_...
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_...
[ "Simple", ".", "gz", "archive", "extractor" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/utils.py#L145-L162
[ "def", "ungzip", "(", "file_path", ",", "extract_path", ":", "Path", "=", "None", ")", ":", "CHUNK", "=", "16", "*", "1024", "file_path", "=", "Path", "(", "file_path", ")", "extract_path", "=", "extract_path", "or", "file_path", ".", "with_suffix", "(", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
download_decompress
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 where downloaded file will be stored until the end of extraction extract_pat...
deeppavlov/core/data/utils.py
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...
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...
[ "Download", "and", "extract", ".", "tar", ".", "gz", "or", ".", "gz", "file", "to", "one", "or", "several", "target", "locations", ".", "The", "archive", "is", "deleted", "if", "extraction", "was", "successful", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/utils.py#L165-L224
[ "def", "download_decompress", "(", "url", ":", "str", ",", "download_path", ":", "[", "Path", ",", "str", "]", ",", "extract_paths", "=", "None", ")", ":", "file_name", "=", "Path", "(", "urlparse", "(", "url", ")", ".", "path", ")", ".", "name", "do...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
update_dict_recursive
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 edits Returns: None
deeppavlov/core/data/utils.py
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...
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...
[ "Updates", "dict", "recursively" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/utils.py#L431-L446
[ "def", "update_dict_recursive", "(", "editable_dict", ":", "dict", ",", "editing_dict", ":", "dict", ")", "->", "None", ":", "for", "k", ",", "v", "in", "editing_dict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "collections", ".", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
path_set_md5
Given a file URL, return a md5 query of the file Args: url: a given URL Returns: URL of the md5 file
deeppavlov/core/data/utils.py
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))
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", "file", "URL", "return", "a", "md5", "query", "of", "the", "file" ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/utils.py#L449-L460
[ "def", "path_set_md5", "(", "url", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query_string", ",", "fragment", "=", "urlsplit", "(", "url", ")", "path", "+=", "'.md5'", "return", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "path", "...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
set_query_parameter
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
deeppavlov/core/data/utils.py
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 """ ...
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 """ ...
[ "Given", "a", "URL", "set", "or", "replace", "a", "query", "parameter", "and", "return", "the", "modified", "URL", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/data/utils.py#L463-L480
[ "def", "set_query_parameter", "(", "url", ",", "param_name", ",", "param_value", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query_string", ",", "fragment", "=", "urlsplit", "(", "url", ")", "query_params", "=", "parse_qs", "(", "query_string", ")"...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
test
PlainText.alexa
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.
deeppavlov/agents/rich_content/default_rich_content.py
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...
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...
[ "Returns", "Amazon", "Alexa", "compatible", "state", "of", "the", "PlainText", "instance", "." ]
deepmipt/DeepPavlov
python
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/rich_content/default_rich_content.py#L58-L80
[ "def", "alexa", "(", "self", ")", "->", "dict", ":", "response", "=", "{", "'response'", ":", "{", "'shouldEndSession'", ":", "False", ",", "'outputSpeech'", ":", "{", "'type'", ":", "'PlainText'", ",", "'text'", ":", "self", ".", "content", "}", ",", ...
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c