code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def text_to_sequence(text): '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." Args: text: string to convert to ...
Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." Args: text: string to convert to a sequence cleaner_names: nam...
text_to_sequence
python
openvinotoolkit/open_model_zoo
demos/text_to_speech_demo/python/utils/text_preprocessing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/text_to_speech_demo/python/utils/text_preprocessing.py
Apache-2.0
def fold_with_overlap(x, target, overlap): ''' Fold the tensor with overlap for quick batched inference. Overlap will be used for crossfading in xfade_and_unfold() Args: x (tensor) : Upsampled conditioning features. shape=(1, timesteps, features) target (int) ...
Fold the tensor with overlap for quick batched inference. Overlap will be used for crossfading in xfade_and_unfold() Args: x (tensor) : Upsampled conditioning features. shape=(1, timesteps, features) target (int) : Target timesteps for each index of batch ...
fold_with_overlap
python
openvinotoolkit/open_model_zoo
demos/text_to_speech_demo/python/utils/wav_processing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/text_to_speech_demo/python/utils/wav_processing.py
Apache-2.0
def xfade_and_unfold(y, overlap): ''' Applies a crossfade and unfolds into a 1d array. Args: y (ndarry) : Batched sequences of audio samples shape=(num_folds, target + 2 * overlap) dtype=float overlap (int) : Timesteps for both xfade and rnn wa...
Applies a crossfade and unfolds into a 1d array. Args: y (ndarry) : Batched sequences of audio samples shape=(num_folds, target + 2 * overlap) dtype=float overlap (int) : Timesteps for both xfade and rnn warmup Return: (ndarry) : audi...
xfade_and_unfold
python
openvinotoolkit/open_model_zoo
demos/text_to_speech_demo/python/utils/wav_processing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/text_to_speech_demo/python/utils/wav_processing.py
Apache-2.0
def infer_from_discretized_mix_logistic(params): """ Sample from discretized mixture of logistic distributions Args: params (Tensor): B x C x T, [C/3,C/3,C/3] = [logit probs, means, log scales] Returns: Tensor: sample in range of [-1, 1]. """ log_scale_min = float(np.log(1e-14)) ...
Sample from discretized mixture of logistic distributions Args: params (Tensor): B x C x T, [C/3,C/3,C/3] = [logit probs, means, log scales] Returns: Tensor: sample in range of [-1, 1].
infer_from_discretized_mix_logistic
python
openvinotoolkit/open_model_zoo
demos/text_to_speech_demo/python/utils/wav_processing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/text_to_speech_demo/python/utils/wav_processing.py
Apache-2.0
def __call__(self, inputs): """ Main forecasting method. Arguments: inputs (np.array): input data. Returns: preds (dict): predicted quantiles. """ self.infer_request.infer(inputs={self.input_tensor_name: inputs}) preds = self.infer_request.get_te...
Main forecasting method. Arguments: inputs (np.array): input data. Returns: preds (dict): predicted quantiles.
__call__
python
openvinotoolkit/open_model_zoo
demos/time_series_forecasting_demo/python/time_series_forecasting_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/time_series_forecasting_demo/python/time_series_forecasting_demo.py
Apache-2.0
def __getitem__(self, idx): """ Get sample. Arguments: idx (idx): idx of the sample. Returns: sample: get annotation object. """ try: return self.data[idx] except KeyError: raise IndexError
Get sample. Arguments: idx (idx): idx of the sample. Returns: sample: get annotation object.
__getitem__
python
openvinotoolkit/open_model_zoo
demos/time_series_forecasting_demo/python/time_series_forecasting_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/time_series_forecasting_demo/python/time_series_forecasting_demo.py
Apache-2.0
def update_curves(self, preds, gt): """ Update curves. Arguments: preds (dict<np.array>): dict of predicted quantiles. gt (Annotation): annotation object. """ self.curves["gt"].set_ydata(gt.inorm(gt.outputs.flatten())) for key, val in preds.items(): ...
Update curves. Arguments: preds (dict<np.array>): dict of predicted quantiles. gt (Annotation): annotation object.
update_curves
python
openvinotoolkit/open_model_zoo
demos/time_series_forecasting_demo/python/time_series_forecasting_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/time_series_forecasting_demo/python/time_series_forecasting_demo.py
Apache-2.0
def main(): """ Preprocess GNHK dataset into text line images """ os.makedirs(os.path.dirname(TEST_FOLDER), exist_ok=True) open(TEST_TXT, 'w').close() # clear the file images = glob.glob('eng*.jpg') for img_idx, image in enumerate(images): img_id = Path(image).stem print(img...
Preprocess GNHK dataset into text line images
main
python
openvinotoolkit/open_model_zoo
models/intel/handwritten-english-recognition-0001/preprocess_gnhk.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/models/intel/handwritten-english-recognition-0001/preprocess_gnhk.py
Apache-2.0
def infer(self, m_t, a1_t, a2_t, a3_t, a4_t, h1, h2, x): """ implement one step forward pass from WaveRNN fatchord version :return: """ x = torch.cat([x, m_t, a1_t], dim=1) x = self.model.I(x) h1 = self.rnn1(x, h1) x = x + h1 inp = torch.cat([x, a...
implement one step forward pass from WaveRNN fatchord version :return:
infer
python
openvinotoolkit/open_model_zoo
models/public/wavernn/wavernn_to_onnx.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/models/public/wavernn/wavernn_to_onnx.py
Apache-2.0
def forward(self, images): """ Args: inputs[Tensor]: [BxCxHxW] Returns: outputs[Tensor]: [Bx(H*W*A=6)x(K(classes)+4(boxes))] """ h, w = images.shape[2:] features = self.backbone(images) features = [features[f] for f in self.in_features] ...
Args: inputs[Tensor]: [BxCxHxW] Returns: outputs[Tensor]: [Bx(H*W*A=6)x(K(classes)+4(boxes))]
forward
python
openvinotoolkit/open_model_zoo
models/public/yolof/model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/models/public/yolof/model.py
Apache-2.0
def register(linter): """ Required method to auto register this checker. """ linter.register_checker(BackslashChecker(linter)) linter.register_checker(AbsoluteImportsChecker(linter)) linter.register_checker(StringFormatChecker(linter)) linter.register_checker(BadFunctionChecker(linter))
Required method to auto register this checker.
register
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/pylint_checkers.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/pylint_checkers.py
Apache-2.0
def get_opts(options): """ Args: options: options object. Returns: args (tuple): positional options. kwargs (map): keyword arguments. """ if isinstance(options, tuple): if len(options) == 2 and isinstance(options[-1], dict): args, kwargs = options ...
Args: options: options object. Returns: args (tuple): positional options. kwargs (map): keyword arguments.
get_opts
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/dependency.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/dependency.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of ContainerPrediction objects """ r...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of ContainerPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/attributes_recognition.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of ContainerPrediction objects """ resul...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of ContainerPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/attribute_classification.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/attribute_classification.py
Apache-2.0
def _ctc_decoder_prediction(prediction, labels): """ Decodes a sequence of labels to words """ blank_id = len(labels) hypotheses = [] # CTC decoding procedure for batch_elem in prediction: decoded_prediction = [] previous = blank_id ...
Decodes a sequence of labels to words
_ctc_decoder_prediction
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def _extract_predictions(self, outputs_list, meta): """ Extract the value of network's output identified by the provided name. The result is returned as list(numpy.ndarray), arrays are to be concatenated along the first axis. """ is_multi_infer = meta[-1].get('multi_infer...
Extract the value of network's output identified by the provided name. The result is returned as list(numpy.ndarray), arrays are to be concatenated along the first axis.
_extract_predictions
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def __init__(self, alphabet, beam_width, sep=' ', lm=None, start_with_bos=True, alpha=1.0, beta=0.0, oov_score=None, allowed_prefixes=None): """ Some args: alphabet (list of str), alphabet, including the blank symbol as '' sep (str), word separator char. Use '' for c...
Some args: alphabet (list of str), alphabet, including the blank symbol as '' sep (str), word separator char. Use '' for character-based LM without word separator (e.g. Chinese).
__init__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def finalize_scores(self): """ This essentially adds a word space at the end to score the last word. The resulting score is in candidates[...].logp_blank, the higher the better. """ if self.candidates_finalized: return self.candidates_finalized = True ...
This essentially adds a word space at the end to score the last word. The resulting score is in candidates[...].logp_blank, the higher the better.
finalize_scores
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def _get_extended_candidate(self, old_cand, new_char, new_char_index): """ Find existing or create new CtcBeamSearchCandidate with text extended with the given character. """ new_text_state, new_word = old_cand.text_state.extended(new_char, new_char_index, sep=self.sep) i...
Find existing or create new CtcBeamSearchCandidate with text extended with the given character.
_get_extended_candidate
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def _prune_candidates(self, beam_width=None): """ Keep top beam_width candidates by score. Candidates are taken from self.candidates, and updated in place. The score is computed from cand.logp_blank and cand.logp_non_blank. Candidates are not sorted. Side effects: ...
Keep top beam_width candidates by score. Candidates are taken from self.candidates, and updated in place. The score is computed from cand.logp_blank and cand.logp_non_blank. Candidates are not sorted. Side effects: self.candidates is updated
_prune_candidates
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def __init__(self, other=None): """ Without args: make an uninitialized CtcBeamSearchCandidate. With args: shallow copy words and lm_state to a new CtcBeamSearchCandidate, set logp_* fields to -np.inf. """ if other is None: return self.text_state = o...
Without args: make an uninitialized CtcBeamSearchCandidate. With args: shallow copy words and lm_state to a new CtcBeamSearchCandidate, set logp_* fields to -np.inf.
__init__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def empty(lm=None, start_with_bos=True): """ Create an empty initial candidate Args: with_lm (bool), if LM state should be used start_with_bos (bool), True = initialize LM state with start-of-sentence False = initialize LM state with empty context (anywhere in the ...
Create an empty initial candidate Args: with_lm (bool), if LM state should be used start_with_bos (bool), True = initialize LM state with start-of-sentence False = initialize LM state with empty context (anywhere in the sentence)
empty
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def extended(self, new_char, new_char_index, sep=' '): """ Return a copy of self extended with a new character. Use sep='' for character-based LMs. Return pair: TextState, new state with the string value extended by new_char str or None, the new word if word space e...
Return a copy of self extended with a new character. Use sep='' for character-based LMs. Return pair: TextState, new state with the string value extended by new_char str or None, the new word if word space encountered, or None otherwise
extended
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def log_sum_exp(a, b): """ Logically equivalent to: return math.log(math.exp(a) + math.exp(b)) but avoids the possible over/underflow in math.exp(). """ # Checking for -inf is here to only silence runtime warning. if a == -np.inf: return b if b == -np.inf: return a ...
Logically equivalent to: return math.log(math.exp(a) + math.exp(b)) but avoids the possible over/underflow in math.exp().
log_sum_exp
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def read_vocabulary_prefixes(lm_filename, vocab_offset, vocab_length): """ Extract the set of all possible prefixes of vocabulary words from LM file in kenlm binary format. Args: lm_filename (pathlib.Path) vocab_offset (int) vocab_length (int or None), None defaults to spanning until th...
Extract the set of all possible prefixes of vocabulary words from LM file in kenlm binary format. Args: lm_filename (pathlib.Path) vocab_offset (int) vocab_length (int or None), None defaults to spanning until the end of file Return: set of str with all possible prefixes of th...
read_vocabulary_prefixes
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/audio_recognition.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of ClassificationPrediction objects """ ...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of ClassificationPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/classification.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/classification.py
Apache-2.0
def get_proposals(self, rpn_cls_prob_reshape, bbox_deltas, im_info, _feat_stride=16): """ Parameters rpn_cls_prob_reshape: (H , W , Ax2) probabilities for predicted regions bbox_deltas: (H , W , Ax4), predicted regions im_info: a list of [image_height, image_width, scale_ratios] ...
Parameters rpn_cls_prob_reshape: (H , W , Ax2) probabilities for predicted regions bbox_deltas: (H , W , Ax4), predicted regions im_info: a list of [image_height, image_width, scale_ratios] _feat_stride: the downsampling ratio of feature map to the original input image A...
get_proposals
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/ctpn.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/ctpn.py
Apache-2.0
def _filter_boxes(boxes, min_size): """Remove all boxes with any side smaller than min_size.""" ws = boxes[:, 2] - boxes[:, 0] + 1 hs = boxes[:, 3] - boxes[:, 1] + 1 keep = np.where((ws >= min_size) & (hs >= min_size))[0] return keep
Remove all boxes with any side smaller than min_size.
_filter_boxes
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/ctpn.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/ctpn.py
Apache-2.0
def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects """ prediction_batch = self._extract_predictions(raw, frame_meta)...
Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/detection.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: image metadata Returns: list of DetectionPrediction objects """ predictions = self._extract_pred...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: image metadata Returns: list of DetectionPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/detection.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: images metadata Returns: list of DetectionPrediction objects """ raw_outputs = self._extract_pre...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: images metadata Returns: list of DetectionPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/detection.py
Apache-2.0
def generate_output_layer_info(self): """ Generates face detection layer information, which is referenced in process function """ output_layers = [] for i in range(len(self.layer_info['layer_names'])): start = 1.5 anchor_size = self.layer_info['an...
Generates face detection layer information, which is referenced in process function
generate_output_layer_info
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/detection.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: raw: output of model. identifiers: list of input data identifiers. frame_meta: metadata for frame. Returns: list of HitRatioPrediction objects. """ raw_prediction = self._e...
Args: raw: output of model. identifiers: list of input data identifiers. frame_meta: metadata for frame. Returns: list of HitRatioPrediction objects.
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/hit_ratio.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/hit_ratio.py
Apache-2.0
def is_result_valid(result: dict): ''' this method check whether values of result dict have the same length ''' list_len = -1 for val in result.values(): if list_len < 0: list_len = len(val) else: if list_len != len(val): ...
this method check whether values of result dict have the same length
is_result_valid
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/mixed_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/mixed_adapter.py
Apache-2.0
def nms(boxes, threshold, overlap_type): """ Args: boxes: [:,0:5] threshold: 0.5 like overlap_type: 'Min' or 'Union' Returns: indexes of passed boxes """ if boxes.shape[0] == 0: return np.array([]) x1 = boxes[:, 0] ...
Args: boxes: [:,0:5] threshold: 0.5 like overlap_type: 'Min' or 'Union' Returns: indexes of passed boxes
nms
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/mtcnn.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/mtcnn.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of RegressionPrediction objects """ pred...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: list of meta information about each frame Returns: list of RegressionPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/regression.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/regression.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of ReIdentificationPrediction objects """ self.select_output_blob(raw if not isinstance(raw, list) else ra...
Args: identifiers: list of input data identifiers raw: output of model Returns: list of ReIdentificationPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/reidentification.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/reidentification.py
Apache-2.0
def delta2box(deltas, anchors, size, stride): 'Convert deltas from anchors to boxes' anchors_wh = anchors[:, 2:] - anchors[:, :2] + 1 ctr = anchors[:, :2] + 0.5 * anchors_wh pred_ctr = deltas[:, :2] * anchors_wh + ctr pred_wh = np.exp(deltas[:, 2:]) * anchors...
Convert deltas from anchors to boxes
delta2box
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/retinanet.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/retinanet.py
Apache-2.0
def _generate_anchors(base_size=16): """ Generate anchor (reference) windows by enumerating aspect ratios X scales w.r.t. a reference window. """ num_anchors = len(self.ratios) * len(self.scales) # initialize output anchors anchors = np...
Generate anchor (reference) windows by enumerating aspect ratios X scales w.r.t. a reference window.
_generate_anchors
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/retinanet.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/retinanet.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model which is ndarray of shape (batch, det_count, 6), each detection is defined by 6 values: class_id, prob, x_min, y_min, x_max, y_max ...
Args: identifiers: list of input data identifiers raw: output of model which is ndarray of shape (batch, det_count, 6), each detection is defined by 6 values: class_id, prob, x_min, y_min, x_max, y_max Returns: list of DetectionPrediction objects ...
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/ssd.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/ssd.py
Apache-2.0
def to_boxes(self, image_shape, segm_pos_scores, link_pos_scores): """ Returns boxes for each image in batch. """ mask = self.decode_image(segm_pos_scores, link_pos_scores) mask = np.asarray(mask, np.int32)[...] bboxes = self.mask_to_bboxes(mask, image_shape) return bboxes
Returns boxes for each image in batch.
to_boxes
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/text_detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/text_detection.py
Apache-2.0
def get_neighbours(x_coord, y_coord): """ Returns 8-point neighbourhood of given point. """ return [ (x_coord - 1, y_coord - 1), (x_coord, y_coord - 1), (x_coord + 1, y_coord - 1), (x_coord - 1, y_coord), (x_coord + 1, y_coord), (x_coord - 1, y_co...
Returns 8-point neighbourhood of given point.
get_neighbours
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/text_detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/text_detection.py
Apache-2.0
def nms_locality(polys, thres=0.3): ''' locality aware nms of EAST :param polys: a N*9 numpy array. first 8 coordinates, then prob :return: boxes after nms ''' def intersection(g, p): g = Polygon(g[:8].reshape((4, 2))) p = Polygon(p[:8].reshape((4,...
locality aware nms of EAST :param polys: a N*9 numpy array. first 8 coordinates, then prob :return: boxes after nms
nms_locality
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/text_detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/text_detection.py
Apache-2.0
def decode(probabilities, beam_size=10, blank_id=None): """ Decode given output probabilities to sequence of labels. Arguments: probabilities: The output log probabilities for each time step. Should be an array of shape (time x output dim). beam_size (int): S...
Decode given output probabilities to sequence of labels. Arguments: probabilities: The output log probabilities for each time step. Should be an array of shape (time x output dim). beam_size (int): Size of the beam to use during decoding. blank_id (int):...
decode
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/text_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/text_recognition.py
Apache-2.0
def decode(prob_index, blank_id): """ Decode given output probabilities to sequence of labels. Arguments: prob_index: The max index along the probabilities dimension. blank_id (int): Index of the CTC blank label. Returns the output label sequence. """ ...
Decode given output probabilities to sequence of labels. Arguments: prob_index: The max index along the probabilities dimension. blank_id (int): Index of the CTC blank label. Returns the output label sequence.
decode
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/text_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/text_recognition.py
Apache-2.0
def sanitize_coordinates(_x1, _x2, img_size, padding=0): """ Sanitizes the input coordinates so that x1 < x2, x1 != x2, x1 >= 0, and x2 <= image_size. Also converts from relative to absolute coordinates. """ _x1 = _x1 * img_size _x2 = _x2 * img_size x1 = np.clip(_x1 - padding, 0, img_size) ...
Sanitizes the input coordinates so that x1 < x2, x1 != x2, x1 >= 0, and x2 <= image_size. Also converts from relative to absolute coordinates.
sanitize_coordinates
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/yolact.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/yolact.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: meta info about prediction Returns: list of DetectionPrediction objects """ prediction = self._...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: meta info about prediction Returns: list of DetectionPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/yolo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/yolo.py
Apache-2.0
def permute_to_HWA_K(tensor, K): """ Transpose/reshape a tensor from ((A x K), H, W) to ((HxWxA), K) """ assert tensor.ndim == 3, tensor.shape _, H, W = tensor.shape tensor = tensor.reshape(-1, K, H, W) tensor = tensor.transpose(2, 3, 0, 1) tensor = tensor.reshape(-1, K) return tenso...
Transpose/reshape a tensor from ((A x K), H, W) to ((HxWxA), K)
permute_to_HWA_K
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/yolo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/yolo.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ Args: identifiers: list of input data identifiers raw: output of model frame_meta: meta info about data processing Returns: list of DetectionPrediction objects """ predictions = s...
Args: identifiers: list of input data identifiers raw: output of model frame_meta: meta info about data processing Returns: list of DetectionPrediction objects
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/yolo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/yolo.py
Apache-2.0
def parameters(cls): """ parameters declares additional configuration parameters for adapter. It is classmethod for extraction parameters without object creation """ # get parent parameters if any params = super().parameters() # update configuration for specific a...
parameters declares additional configuration parameters for adapter. It is classmethod for extraction parameters without object creation
parameters
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/yolo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/yolo.py
Apache-2.0
def configure(self): """ configure method used for parsing and initialization configuration parameters. It called in __init__ """ self.conf_threshold = self.get_value_from_config("conf_threshold") self.multi_label = self.get_value_from_config("multi_label")
configure method used for parsing and initialization configuration parameters. It called in __init__
configure
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/yolo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/yolo.py
Apache-2.0
def process(self, raw, identifiers, frame_meta): """ the main processing method for adapters. Parameters: raw: dict or list of dicts with raw model outputs from launcher identifiers: unique identifier which input data this prediction belongs (usually file name) fram...
the main processing method for adapters. Parameters: raw: dict or list of dicts with raw model outputs from launcher identifiers: unique identifier which input data this prediction belongs (usually file name) frame_meta: list of metadata for input data per input frame in b...
process
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/adapters/yolo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/adapters/yolo.py
Apache-2.0
def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs): """Reads data from disk and returns dataset in converted for AC format Args: check_content (bool, optional): Check if content is valid. Defaults to False. progress_callback (bool, op...
Reads data from disk and returns dataset in converted for AC format Args: check_content (bool, optional): Check if content is valid. Defaults to False. progress_callback (bool, optional): Display progress. Defaults to None. progress_interval (int, optional): Units to display...
convert
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/antispoofing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/antispoofing.py
Apache-2.0
def generate_annotations(self): ''' read json file with images paths and return list of the items''' annotation_store = [] dataset_annotations = read_json(self.annotations) for index in dataset_annotations: path = dataset_annotations[index]['path'] target_...
read json file with images paths and return list of the items
generate_annotations
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/antispoofing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/antispoofing.py
Apache-2.0
def configure(self): """ This method is responsible for obtaining the necessary parameters for converting from the command line or config. """ self.data_batch_file = self.get_value_from_config('data_batch_file') self.batch_meta_file = self.get_value_from_config('batch_met...
This method is responsible for obtaining the necessary parameters for converting from the command line or config.
configure
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/cifar.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/cifar.py
Apache-2.0
def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs): """ This method is executed automatically when convert.py is started. All arguments are automatically got from command line arguments or config file in method configure Returns: ...
This method is executed automatically when convert.py is started. All arguments are automatically got from command line arguments or config file in method configure Returns: annotations: list of annotation representation objects. meta: dictionary with additional dataset...
convert
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/cifar.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/cifar.py
Apache-2.0
def get_single_col_by_input_type(input_type, column_definition): """Returns name of single column. Args: input_type: Input type of column to extract column_definition: Column definition list for experiment """ cols = [tup[0] for tup in column_definition if tup[2] == input_type] if len(cols...
Returns name of single column. Args: input_type: Input type of column to extract column_definition: Column definition list for experiment
get_single_col_by_input_type
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
Apache-2.0
def extract_cols_from_data_type(data_type, column_definition, excluded_input_types): """Extracts the names of columns that correspond to a define data_type. Args: data_type: DataType of columns to extract. column_definition: Column definition to use. excluded_input_ty...
Extracts the names of columns that correspond to a define data_type. Args: data_type: DataType of columns to extract. column_definition: Column definition to use. excluded_input_types: Set of input types to exclude Returns: List of names for columns with data type specified.
extract_cols_from_data_type
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
Apache-2.0
def split_data(self, df, valid_boundary=1315, test_boundary=1339): """Splits data frame into training-validation-test data frames. This also calibrates scaling object, and transforms data for each split. Args: df: Source data frame to split. valid_boundary: Starting year for ...
Splits data frame into training-validation-test data frames. This also calibrates scaling object, and transforms data for each split. Args: df: Source data frame to split. valid_boundary: Starting year for validation data test_boundary: Starting year for test data R...
split_data
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
Apache-2.0
def set_scalers(self, df): """Calibrates scalers using the data supplied. Args: df: Data to use to calibrate scalers. """ print_info('Setting scalers with training data...') column_definitions = self.getcolumn_definition() id_column = get_single_col_by_...
Calibrates scalers using the data supplied. Args: df: Data to use to calibrate scalers.
set_scalers
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
Apache-2.0
def transform_inputs(self, df): """Performs feature transformations. This includes both feature engineering, preprocessing and normalisation. Args: df: Data frame to transform. Returns: Transformed data frame. """ if self.real_scalers is None and self...
Performs feature transformations. This includes both feature engineering, preprocessing and normalisation. Args: df: Data frame to transform. Returns: Transformed data frame.
transform_inputs
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
Apache-2.0
def getcolumn_definition(self): """"Returns formatted column definition in order expected by the TFT.""" column_definition = self.column_definition # Sanity checks first. # Ensure only one ID and time column exist def _check_single_column(input_type): length = len(...
"Returns formatted column definition in order expected by the TFT.
getcolumn_definition
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/electricity_time_series_forecasting.py
Apache-2.0
def read_vocab(vocab_path): """Reads vocab file from disk as .pkl or .json Args: vocab_path (str): path to vocab file Raises: ValueError: If wrong extension of the file Returns: Vocab: Vocab object with sign2id and id2sign dictinaries """ if vocab_path.suffix == '.pkl'...
Reads vocab file from disk as .pkl or .json Args: vocab_path (str): path to vocab file Raises: ValueError: If wrong extension of the file Returns: Vocab: Vocab object with sign2id and id2sign dictinaries
read_vocab
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/im2latex.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/im2latex.py
Apache-2.0
def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs): """ This method is executed automatically when convert.py is started. All arguments are automatically got from command line arguments or config file in method configure Returns: ...
This method is executed automatically when convert.py is started. All arguments are automatically got from command line arguments or config file in method configure Returns: annotations: list of annotation representation objects. meta: dictionary with additional dataset...
convert
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/mrlEyes_2018_01.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/mrlEyes_2018_01.py
Apache-2.0
def all_special_ids(self): """ List the vocabulary indices of the special tokens ('<unk>', '<cls>'...) mapped to class attributes (cls_token, unk_token...). """ all_toks = self.all_special_tokens all_ids = self.convert_tokens_to_ids(all_toks) return all_ids
List the vocabulary indices of the special tokens ('<unk>', '<cls>'...) mapped to class attributes (cls_token, unk_token...).
all_special_ids
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
Apache-2.0
def all_special_tokens(self): """ List all the special tokens ('<unk>', '<cls>'...) mapped to class attributes (cls_token, unk_token...). """ all_toks = [] set_attr = self.special_tokens_map for attr_value in set_attr.values(): all_toks = all_toks + (list(...
List all the special tokens ('<unk>', '<cls>'...) mapped to class attributes (cls_token, unk_token...).
all_special_tokens
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
Apache-2.0
def convert_ids_to_tokens(self, ids, skip_special_tokens=False): """ Converts a single index or a sequence of indices (integers) in a token " (resp.) a sequence of tokens (str/unicode), using the vocabulary and added tokens. Args: skip_special_tokens: Don't decode special...
Converts a single index or a sequence of indices (integers) in a token " (resp.) a sequence of tokens (str/unicode), using the vocabulary and added tokens. Args: skip_special_tokens: Don't decode special tokens (self.all_special_tokens). Default: False
convert_ids_to_tokens
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
Apache-2.0
def truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since i...
Truncates a sequence pair in place to the maximum length.
truncate_seq_pair
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/annotation_converters/_nlp_common.py
Apache-2.0
def merge(arguments): """ Args: arguments: command-line arguments. Returns: dictionary containing configuration. """ global_config, local_config = ConfigReader._read_configs(arguments) if not local_config: raise ConfigError('Missing lo...
Args: arguments: command-line arguments. Returns: dictionary containing configuration.
merge
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/config/config_reader.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/config/config_reader.py
Apache-2.0
def layer_norm(input_array, gamma, beta, epsilon=1e-5): """ Input array layer normalization (aka torch.nn.LayerNorm). """ mean = np.mean(input_array, axis=-1, keepdims=True) std = np.std(input_array, axis=-1, keepdims=True) normalized = (input_array - mean) / np.sqrt(std ...
Input array layer normalization (aka torch.nn.LayerNorm).
layer_norm
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/evaluators/custom_evaluators/openvino_clip_evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/evaluators/custom_evaluators/openvino_clip_evaluator.py
Apache-2.0
def normalize(input_array, p=2, axis=-1, epsilon=1e-12): """ Input array normalization using the p-norm (aka torch.nn.functional.normalize). """ norm = np.linalg.norm(input_array, ord=p, axis=axis, keepdims=True) norm = np.maximum(norm, epsilon) normalized = input_array /...
Input array normalization using the p-norm (aka torch.nn.functional.normalize).
normalize
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/evaluators/custom_evaluators/openvino_clip_evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/evaluators/custom_evaluators/openvino_clip_evaluator.py
Apache-2.0
def get_w_embedding(w, embedding_dim=512, dtype=torch.float32): """ see https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps: torch.Tensor: generate embedding vectors at these timesteps embedding_dim: int: dimensio...
see https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps: torch.Tensor: generate embedding vectors at these timesteps embedding_dim: int: dimension of the embeddings to generate dtype: data type of the generated e...
get_w_embedding
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/evaluators/custom_evaluators/stable_diffusion_evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/evaluators/custom_evaluators/stable_diffusion_evaluator.py
Apache-2.0
def predict(self, inputs, metadata=None, **kwargs): """ Args: inputs: dictionary where keys are input layers names and values are data for them. metadata: metadata of input representations Returns: raw data from network. """ results = [] ...
Args: inputs: dictionary where keys are input layers names and values are data for them. metadata: metadata of input representations Returns: raw data from network.
predict
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/launcher/caffe_launcher.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/launcher/caffe_launcher.py
Apache-2.0
def validate(self, entry, field_uri=None, ie_core=None, fetch_only=False, validation_scheme=None): """ Validate that launcher entry meets all configuration structure requirements. Args: entry: launcher configuration file entry. field_uri: id of launcher entry. ...
Validate that launcher entry meets all configuration structure requirements. Args: entry: launcher configuration file entry. field_uri: id of launcher entry. ie_core: IECore instance. fetch_only: only fetch possible error without raising valid...
validate
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/launcher/dlsdk_launcher_config.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/launcher/dlsdk_launcher_config.py
Apache-2.0
def create_launcher(launcher_config, model_name='', delayed_model_loading=False, **kwargs): """ Args: launcher_config: launcher configuration file entry. model_name: evaluation model name delayed_model_loading: allows postpone model loading to the launcher Returns: framework-...
Args: launcher_config: launcher configuration file entry. model_name: evaluation model name delayed_model_loading: allows postpone model loading to the launcher Returns: framework-specific launcher object.
create_launcher
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/launcher/launcher.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/launcher/launcher.py
Apache-2.0
def set_tensors(self, dataset_input): """ Set input tensors: :param dataset_input: dict {"input_layer_name": input_data} :return: None """ for layer, data in dataset_input.items(): self._interpreter.set_tensor( self._inputs[layer]['index'], dat...
Set input tensors: :param dataset_input: dict {"input_layer_name": input_data} :return: None
set_tensors
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/launcher/tf_lite_launcher.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/launcher/tf_lite_launcher.py
Apache-2.0
def bbox_match(annotation: List[DetectionAnnotation], prediction: List[DetectionPrediction], label, overlap_evaluator, overlap_thresh=0.5, ignore_difficult=True, allow_multiple_matches_per_ignored=True, include_boundaries=True, use_filtered_tp=False): """ Args: annotation: ...
Args: annotation: ground truth bounding boxes. prediction: predicted bounding boxes. label: class for which bounding boxes are matched. overlap_evaluator: evaluator of overlap. overlap_thresh: bounding box IoU threshold. ignore_difficult: ignores difficult bounding b...
bbox_match
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/detection.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/detection.py
Apache-2.0
def score_calc(self, annotations, predictions): """ Calculate IS metric for prediction labels. """ mean_probabilities_of_classes = np.expand_dims(np.mean(predictions, axis=0), axis=0) KL_d = predictions * (np.log(predictions + self.eps) - np.log(mean_probabilities_of_classes + s...
Calculate IS metric for prediction labels.
score_calc
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/gan_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/gan_metrics.py
Apache-2.0
def score_calc(self, annotations, predictions): """ Calculate FID between feature vector of the real and generated images. """ if isinstance(sqrtm, UnsupportedPackage): sqrtm.raise_error(self.__provider__) assert annotations.shape[1] == predictions.shape[1], "Expecte...
Calculate FID between feature vector of the real and generated images.
score_calc
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/gan_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/gan_metrics.py
Apache-2.0
def preprocess_formula(formula): """Formula preprocessing Args: l (str): Input formula Returns: str: Preprocessed formula """ formula = formula.strip() formula = formula.replace(r'\pmatrix', r'\mypmatrix') formula = formula.replace(r'\matrix', r'\mymatrix') # remove lea...
Formula preprocessing Args: l (str): Input formula Returns: str: Preprocessed formula
preprocess_formula
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
Apache-2.0
def render_routine(line): """Function for rendering single formula Args: line (tuple): formula idx, formula string, path to store rendered image """ formula, file_idx, folder_path = line output_path = folder_path / file_idx pre_name = os.path.normcase(output_path).replace('/', '_').repl...
Function for rendering single formula Args: line (tuple): formula idx, formula string, path to store rendered image
render_routine
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
Apache-2.0
def check_differ(diff): """Checks if difference of two images has a substring of blue or red pixels with length >= MAX_PX_ROW_DIFF In other words, if one image is shifted from another less then MAX_PX_ROW_DIFF, images are equal Args: diff (np.array): Difference of two images Returns: ...
Checks if difference of two images has a substring of blue or red pixels with length >= MAX_PX_ROW_DIFF In other words, if one image is shifted from another less then MAX_PX_ROW_DIFF, images are equal Args: diff (np.array): Difference of two images Returns: bool: Images match
check_differ
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
Apache-2.0
def preprocess(img): """Preprocessing of the image (transpostion and binarization) Args: im1 (np.array): input image Returns: np.array: preprocessed image """ # transpose for more convenient work img = np.transpose(img) img = (img >= 160).astype(np.uint8) return img
Preprocessing of the image (transpostion and binarization) Args: im1 (np.array): input image Returns: np.array: preprocessed image
preprocess
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
Apache-2.0
def match_images(params): """Function for single comparing two images Args: im1 (str): path to image1 im2 (str): path to image2 out_path (str, optional): Path to store diff of two images. Defaults to None. max_pixel_column_diff (int, optional): Maximum number of black pixels in ...
Function for single comparing two images Args: im1 (str): path to image1 im2 (str): path to image2 out_path (str, optional): Path to store diff of two images. Defaults to None. max_pixel_column_diff (int, optional): Maximum number of black pixels in column to treat it as whi...
match_images
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
Apache-2.0
def compare_pics(self, images_dir): """ Function reads images and compares them, first, as is second, deletes all whitespaces and compares again. This step helps to escape the situation when two pics are not equal because of different length of spaces """ total_nu...
Function reads images and compares them, first, as is second, deletes all whitespaces and compares again. This step helps to escape the situation when two pics are not equal because of different length of spaces
compare_pics
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
Apache-2.0
def render_images(self, annotations, predictions, images_dir): """Runs render script to render images and store them into images_dir Args: annotations (str): Ground-truth formula predictions (str): Predicted formula """ out_path_gold = Path(images_dir, 'images_go...
Runs render script to render images and store them into images_dir Args: annotations (str): Ground-truth formula predictions (str): Predicted formula
render_images
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/im2latex_images_match.py
Apache-2.0
def __call__(self, line): """Common post-processing tokenizer for `13a` and `zh` tokenizers. :param line: a segment to tokenize :return: the tokenized line """ for (_re, repl) in self._re: line = _re.sub(repl, line) # no leading or trailing spaces ret...
Common post-processing tokenizer for `13a` and `zh` tokenizers. :param line: a segment to tokenize :return: the tokenized line
__call__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/machine_translation.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/machine_translation.py
Apache-2.0
def __call__(self, line): """Tokenizes an input line using a relatively minimal tokenization that is however equivalent to mteval-v13a, used by WMT. :param line: a segment to tokenize :return: the tokenized line """ if self.lower_case: line = line.lower() ...
Tokenizes an input line using a relatively minimal tokenization that is however equivalent to mteval-v13a, used by WMT. :param line: a segment to tokenize :return: the tokenized line
__call__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/machine_translation.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/machine_translation.py
Apache-2.0
def to_homogeneous(points): """Convert N-dimensional points to homogeneous coordinates. Args: points: torch.Tensor or numpy.ndarray with size (..., N). Returns: A torch.Tensor or numpy.ndarray with size (..., N+1). """ if isinstance(points, torch.Tensor): pad = points.new_one...
Convert N-dimensional points to homogeneous coordinates. Args: points: torch.Tensor or numpy.ndarray with size (..., N). Returns: A torch.Tensor or numpy.ndarray with size (..., N+1).
to_homogeneous
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/matches_homography.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/matches_homography.py
Apache-2.0
def validate_config(cls, config, fetch_only=False, uri_prefix=''): """ Validate that metric entry meets all configuration structure requirements. """ errors = [] if cls.__name__ == Metric.__name__: metric_provider = config.get('type') if not metric_provide...
Validate that metric entry meets all configuration structure requirements.
validate_config
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/metric.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/metric.py
Apache-2.0
def update_metrics_on_object(self, annotation, prediction): """ Updates metric value corresponding given annotation and prediction objects. """ metric_results = [] for metric in self.metrics: metric_results.append(metric.metric_fn.submit(annotation, prediction)) ...
Updates metric value corresponding given annotation and prediction objects.
update_metrics_on_object
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/metric_executor.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/metric_executor.py
Apache-2.0
def update_metrics_on_batch(self, batch_ids, annotation, prediction, profile=False, deprocessed_annotation=None, deprocessed_prediction=None): """ Updates metric value corresponding given batch. Args: annotation: list of batch number of annotation obj...
Updates metric value corresponding given batch. Args: annotation: list of batch number of annotation objects. prediction: list of batch number of prediction objects.
update_metrics_on_batch
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/metric_executor.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/metrics/metric_executor.py
Apache-2.0
def frame(x, frame_length=2048, hop_length=512): """Slice a data array into (overlapping) frames.""" n_frames = (x.shape[-1] - frame_length) // hop_length strides = np.asarray(x.strides) new_stride = np.prod(strides[strides > 0] // x.itemsize) * x.itemsize s...
Slice a data array into (overlapping) frames.
frame
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/preprocessor/audio_preprocessing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/preprocessor/audio_preprocessing.py
Apache-2.0
def _convert_samples_to_float32(samples): """Convert sample type to float32. Audio sample type is usually integer or float-point. Integers will be scaled to [-1, 1] in float32. """ float32_samples = samples.astype('float32') if samples.dtype in np.sctypes['int']: ...
Convert sample type to float32. Audio sample type is usually integer or float-point. Integers will be scaled to [-1, 1] in float32.
_convert_samples_to_float32
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/preprocessor/audio_preprocessing_ext.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/preprocessor/audio_preprocessing_ext.py
Apache-2.0
def __init__(self, identifier, path_to_gt, gt_loader=GTLoader.OPENCV): """ Args: identifier: object identifier (e.g. image name). path_to_gt: path where ground truth images should be loaded from. gt_loader: back-end, used to load ground truth images. """ ...
Args: identifier: object identifier (e.g. image name). path_to_gt: path where ground truth images should be loaded from. gt_loader: back-end, used to load ground truth images.
__init__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/representation/image_inpainting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/representation/image_inpainting.py
Apache-2.0
def __init__(self, identifiers, prediction): """ Args: identifiers: object identifier (e.g. image name). prediction: array with shape (height, width) contained result image. """ super().__init__(identifiers) self.value = prediction
Args: identifiers: object identifier (e.g. image name). prediction: array with shape (height, width) contained result image.
__init__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/representation/image_inpainting.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/representation/image_inpainting.py
Apache-2.0
def __init__(self, identifier, path_to_gt, gt_loader=GTLoader.PILLOW): """ Args: identifier: object identifier (e.g. image name). path_to_gt: path where gt image should be loaded from. The path is relative to data source. gt_loader: back-end, used to load segmentation...
Args: identifier: object identifier (e.g. image name). path_to_gt: path where gt image should be loaded from. The path is relative to data source. gt_loader: back-end, used to load segmentation masks.
__init__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/representation/image_processing.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/representation/image_processing.py
Apache-2.0
def __init__(self, identifier, path_to_mask, mask_loader=GTMaskLoader.PILLOW): """ Args: identifier: object identifier (e.g. image name). path_to_mask: path where segmentation mask should be loaded from. The path is relative to data source. mask_loader: back-end, used...
Args: identifier: object identifier (e.g. image name). path_to_mask: path where segmentation mask should be loaded from. The path is relative to data source. mask_loader: back-end, used to load segmentation masks.
__init__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/representation/segmentation_representation.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/representation/segmentation_representation.py
Apache-2.0
def __init__(self, identifiers, mask): """ Args: identifiers: object identifier (e.g. image name). mask: array with shape (n_classes, height, width) of probabilities at each location. """ super().__init__(identifiers) self.mask = mask
Args: identifiers: object identifier (e.g. image name). mask: array with shape (n_classes, height, width) of probabilities at each location.
__init__
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/accuracy_checker/representation/segmentation_representation.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/accuracy_checker/representation/segmentation_representation.py
Apache-2.0
def make_representation(bounding_boxes, is_ground_truth=False, score=None, meta=None): """ Args: bounding_boxes: string or list of strings `score label x0 y0 x1 y1; label score x0 y0 x1 y1; ...`. is_ground_truth: True if bbs are annotation boxes. score: value in [0, 1], if not None, all ...
Args: bounding_boxes: string or list of strings `score label x0 y0 x1 y1; label score x0 y0 x1 y1; ...`. is_ground_truth: True if bbs are annotation boxes. score: value in [0, 1], if not None, all prediction boxes are considered with the given score. meta: metadata for representatio...
make_representation
python
openvinotoolkit/open_model_zoo
tools/accuracy_checker/tests/common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/tools/accuracy_checker/tests/common.py
Apache-2.0