Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def attr(self, key): ret = ctypes.c_char_p() success = ctypes.c_int() _check_call(_LIB.XGBoosterGetAttr( self.handle, c_str(key), ctypes.byref(ret), ctypes.byref(success))) if success.value != 0: return py_str(...
[ "Get attribute string from the Booster.\n\n Parameters\n ----------\n key : str\n The key to get attribute from.\n\n Returns\n -------\n value : str\n The attribute value of the key, returns None if attribute do not exist.\n " ]
Please provide a description of the function:def attributes(self): length = c_bst_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() _check_call(_LIB.XGBoosterGetAttrNames(self.handle, ctypes.byref(length), ...
[ "Get attributes stored in the Booster as a dictionary.\n\n Returns\n -------\n result : dictionary of attribute_name: attribute_value pairs of strings.\n Returns an empty dict if there's no attributes.\n " ]
Please provide a description of the function:def set_attr(self, **kwargs): for key, value in kwargs.items(): if value is not None: if not isinstance(value, STRING_TYPES): raise ValueError("Set Attr only accepts string values") value = c_st...
[ "Set the attribute of the Booster.\n\n Parameters\n ----------\n **kwargs\n The attributes to set. Setting a value to None deletes an attribute.\n " ]
Please provide a description of the function:def set_param(self, params, value=None): if isinstance(params, Mapping): params = params.items() elif isinstance(params, STRING_TYPES) and value is not None: params = [(params, value)] for key, val in params: ...
[ "Set parameters into the Booster.\n\n Parameters\n ----------\n params: dict/list/str\n list of key,value pairs, dict of key to value or simply str key\n value: optional\n value of the specified parameter, when params is str key\n " ]
Please provide a description of the function:def eval(self, data, name='eval', iteration=0): self._validate_features(data) return self.eval_set([(data, name)], iteration)
[ "Evaluate the model on mat.\n\n Parameters\n ----------\n data : DMatrix\n The dmatrix storing the input.\n\n name : str, optional\n The name of the dataset.\n\n iteration : int, optional\n The current iteration number.\n\n Returns\n ...
Please provide a description of the function:def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False, pred_contribs=False, approx_contribs=False, pred_interactions=False, validate_features=True): option_mask = 0x00 if output_margin: ...
[ "\n Predict with data.\n\n .. note:: This function is not thread safe.\n\n For each booster object, predict can only be called from one thread.\n If you want to run prediction using multiple thread, call ``bst.copy()`` to make copies\n of model object and then call ``predict...
Please provide a description of the function:def save_model(self, fname): if isinstance(fname, STRING_TYPES): # assume file name _check_call(_LIB.XGBoosterSaveModel(self.handle, c_str(fname))) else: raise TypeError("fname must be a string")
[ "\n Save the model to a file.\n\n The model is saved in an XGBoost internal binary format which is\n universal among the various XGBoost interfaces. Auxiliary attributes of\n the Python Booster object (such as feature_names) will not be saved.\n To preserve all attributes, pickle ...
Please provide a description of the function:def load_model(self, fname): if isinstance(fname, STRING_TYPES): # assume file name, cannot use os.path.exist to check, file can be from URL. _check_call(_LIB.XGBoosterLoadModel(self.handle, c_str(fname))) else: bu...
[ "\n Load the model from a file.\n\n The model is loaded from an XGBoost internal binary format which is\n universal among the various XGBoost interfaces. Auxiliary attributes of\n the Python Booster object (such as feature_names) will not be loaded.\n To preserve all attributes, p...
Please provide a description of the function:def dump_model(self, fout, fmap='', with_stats=False, dump_format="text"): if isinstance(fout, STRING_TYPES): fout = open(fout, 'w') need_close = True else: need_close = False ret = self.get_dump(fmap, with...
[ "\n Dump model into a text or JSON file.\n\n Parameters\n ----------\n fout : string\n Output file name.\n fmap : string, optional\n Name of the file containing feature map names.\n with_stats : bool, optional\n Controls whether the split st...
Please provide a description of the function:def get_dump(self, fmap='', with_stats=False, dump_format="text"): length = c_bst_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() if self.feature_names is not None and fmap == '': flen = len(self.feature_names) fname...
[ "\n Returns the model dump as a list of strings.\n\n Parameters\n ----------\n fmap : string, optional\n Name of the file containing feature map names.\n with_stats : bool, optional\n Controls whether the split statistics are output.\n dump_format : st...
Please provide a description of the function:def get_score(self, fmap='', importance_type='weight'): if getattr(self, 'booster', None) is not None and self.booster not in {'gbtree', 'dart'}: raise ValueError('Feature importance is not defined for Booster type {}' ...
[ "Get feature importance of each feature.\n Importance type can be defined as:\n\n * 'weight': the number of times a feature is used to split the data across all trees.\n * 'gain': the average gain across all splits the feature is used in.\n * 'cover': the average coverage across all spli...
Please provide a description of the function:def trees_to_dataframe(self, fmap=''): # pylint: disable=too-many-locals if not PANDAS_INSTALLED: raise Exception(('pandas must be available to use this method.' 'Install pandas before calling again.')) ...
[ "Parse a boosted tree model text dump into a pandas DataFrame structure.\n\n This feature is only defined when the decision tree model is chosen as base\n learner (`booster in {gbtree, dart}`). It is not defined for other base learner\n types, such as linear learners (`booster=gblinear`).\n\n ...
Please provide a description of the function:def _validate_features(self, data): if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_types else: # Booster can't accept data with different feature names ...
[ "\n Validate Booster and data's feature_names are identical.\n Set feature_names and feature_types from DMatrix\n " ]
Please provide a description of the function:def get_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): xgdump = self.get_dump(fmap=fmap) values = [] regexp = re.compile(r"\[{0}<([\d.Ee+-]+)\]".format(feature)) for i, _ in enumerate(xgdump): m ...
[ "Get split value histogram of a feature\n\n Parameters\n ----------\n feature: str\n The name of the feature.\n fmap: str (optional)\n The name of feature map file.\n bin: int, default None\n The maximum number of bins.\n Number of bins ...
Please provide a description of the function:def plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', importance_type='weight', max_num_features=None, grid=True...
[ "Plot importance based on fitted trees.\n\n Parameters\n ----------\n booster : Booster, XGBModel or dict\n Booster or XGBModel instance, or dict taken by Booster.get_fscore()\n ax : matplotlib Axes, default None\n Target axes instance. If None, new figure and axes will be created.\n gr...
Please provide a description of the function:def _parse_node(graph, text, condition_node_params, leaf_node_params): match = _NODEPAT.match(text) if match is not None: node = match.group(1) graph.node(node, label=match.group(2), **condition_node_params) return node match = _LEAFP...
[ "parse dumped node" ]
Please provide a description of the function:def _parse_edge(graph, node, text, yes_color='#0000FF', no_color='#FF0000'): try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, la...
[ "parse dumped edge" ]
Please provide a description of the function:def to_graphviz(booster, fmap='', num_trees=0, rankdir='UT', yes_color='#0000FF', no_color='#FF0000', condition_node_params=None, leaf_node_params=None, **kwargs): if condition_node_params is None: condition_node_params = {} ...
[ "Convert specified tree to graphviz instance. IPython can automatically plot the\n returned graphiz instance. Otherwise, you should call .render() method\n of the returned graphiz instance.\n\n Parameters\n ----------\n booster : Booster, XGBModel\n Booster or XGBModel instance\n fmap: str ...
Please provide a description of the function:def newAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True): a = QAction(text, parent) if icon is not None: a.setIcon(newIcon(icon)) if shortcut is not None: if isinstance(shortcut, ...
[ "Create a new action and assign callbacks, shortcuts, etc." ]
Please provide a description of the function:def natural_sort(list, key=lambda s:s): def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_func(key) lis...
[ "\n Sort the list into natural alphanumeric order.\n " ]
Please provide a description of the function:def mouseMoveEvent(self, ev): pos = self.transformPos(ev.pos()) # Update coordinates in status bar if image is opened window = self.parent().window() if window.filePath is not None: self.parent().window().labelCoordinates...
[ "Update line with last point and current coordinates." ]
Please provide a description of the function:def selectShapePoint(self, point): self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape shape.highlightVertex(index, shape.MOVE_VERTEX) self.s...
[ "Select the first shape created which contains this point." ]
Please provide a description of the function:def snapPointToCanvas(self, x, y): if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height(): x = max(x, 0) y = max(y, 0) x = min(x, self.pixmap.width()) y = min(y, self.pixmap.height()) ...
[ "\n Moves a point x,y to within the boundaries of the canvas.\n :return: (x,y,snapped) where snapped is True if x or y were changed, False if not.\n " ]
Please provide a description of the function:def get_main_app(argv=[]): app = QApplication(argv) app.setApplicationName(__appname__) app.setWindowIcon(newIcon("app")) # Tzutalin 201705+: Accept extra agruments to change predefined class file # Usage : labelImg.py image predefClassFile saveDir ...
[ "\n Standard boilerplate Qt application code.\n Do everything but app.exec_() -- so that we can test the application in one thread\n " ]
Please provide a description of the function:def toggleActions(self, value=True): for z in self.actions.zoomActions: z.setEnabled(value) for action in self.actions.onLoadActive: action.setEnabled(value)
[ "Enable/Disable widgets which depend on an opened image." ]
Please provide a description of the function:def toggleDrawingSensitive(self, drawing=True): self.actions.editMode.setEnabled(not drawing) if not drawing and self.beginner(): # Cancel creation. print('Cancel creation.') self.canvas.setEditing(True) ...
[ "In the middle of drawing, toggling between modes should be disabled." ]
Please provide a description of the function:def btnstate(self, item= None): if not self.canvas.editing(): return item = self.currentItem() if not item: # If not selected Item, take the first one item = self.labelList.item(self.labelList.count()-1) diff...
[ " Function to handle difficult examples\n Update on each object " ]
Please provide a description of the function:def newShape(self): if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.text(): if len(self.labelHist) > 0: self.labelDialog = LabelDialog( parent=self, listItem=self.labelHist) ...
[ "Pop-up and give focus to the label editor.\n\n position MUST be in global coordinates.\n " ]
Please provide a description of the function:def loadFile(self, filePath=None): self.resetState() self.canvas.setEnabled(False) if filePath is None: filePath = self.settings.get(SETTING_FILENAME) # Make sure that filePath is a regular python string, rather than QStr...
[ "Load the specified file, or the last opened file if None.", "Annotation file priority:\n PascalXML > YOLO\n " ]
Please provide a description of the function:def scaleFitWindow(self): e = 2.0 # So that no scrollbars are generated. w1 = self.centralWidget().width() - e h1 = self.centralWidget().height() - e a1 = w1 / h1 # Calculate a new scale value based on the pixmap's aspect rat...
[ "Figure out the size of the pixmap in order to fit the main widget." ]
Please provide a description of the function:def ustr(x): '''py2/py3 unicode helper''' if sys.version_info < (3, 0, 0): from PyQt4.QtCore import QString if type(x) == str: return x.decode(DEFAULT_ENCODING) if type(x) == QString: #https://blog.csdn.net/friendan/ar...
[]
Please provide a description of the function:def prettify(self, elem): rough_string = ElementTree.tostring(elem, 'utf8') root = etree.fromstring(rough_string) return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace(" ".encode(), "\t".encode()) # minidom d...
[ "\n Return a pretty-printed XML string for the Element.\n " ]
Please provide a description of the function:def genXML(self): # Check conditions if self.filename is None or \ self.foldername is None or \ self.imgSize is None: return None top = Element('annotation') if self.verified: t...
[ "\n Return XML root\n " ]
Please provide a description of the function:async def fetch(self, url, method='GET', headers=None, body=None): request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) self.logge...
[ "Perform a HTTP request and return decoded JSON data" ]
Please provide a description of the function:def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): if self.enableRateLimit: self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method, params, he...
[ "A better wrapper over request for deferred signing" ]
Please provide a description of the function:def request(self, path, api='public', method='GET', params={}, headers=None, body=None): return self.fetch2(path, api, method, params, headers, body)
[ "Exchange.request is the entry point for all generated methods" ]
Please provide a description of the function:def find_broadly_matched_key(self, broad, string): keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string.find(key) >= 0: return key return None
[ "A helper method for matching error strings exactly vs broadly" ]
Please provide a description of the function:def fetch(self, url, method='GET', headers=None, body=None): request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, request_headers, body) self.log...
[ "Perform a HTTP request and return decoded JSON data" ]
Please provide a description of the function:def safe_either(method, dictionary, key1, key2, default_value=None): value = method(dictionary, key1) return value if value is not None else method(dictionary, key2, default_value)
[ "A helper-wrapper for the safe_value_2() family." ]
Please provide a description of the function:def truncate(num, precision=0): if precision > 0: decimal_precision = math.pow(10, precision) return math.trunc(num * decimal_precision) / decimal_precision return int(Exchange.truncate_to_string(num, precision))
[ "Deprecated, use decimal_to_precision instead" ]
Please provide a description of the function:def truncate_to_string(num, precision=0): if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip('0') decimal_digits = decimal_digits if len(decimal_...
[ "Deprecated, todo: remove references from subclasses" ]
Please provide a description of the function:def check_address(self, address): if address is None: self.raise_error(InvalidAddress, details='address is None') if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddressLength or ' ' in address: ...
[ "Checks an address is not the same character repeated or an empty sequence" ]
Please provide a description of the function:def reduce_filename(f): r''' Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb Where XXX is a variation on the model size for example And where YYY is a const related to the training dataset ''' f = os.path.basename(f).split('.'...
[]
Please provide a description of the function:def keep_only_digits(s): r''' local helper to just keep digits ''' fs = '' for c in s: if c.isdigit(): fs += c return int(fs)
[]
Please provide a description of the function:def parse_stm_file(stm_file): r stm_segments = [] with codecs.open(stm_file, encoding="utf-8") as stm_lines: for stm_line in stm_lines: stmSegment = STMSegment(stm_line) if not "ignore_time_segment_in_scoring" == stmSegment.transcr...
[ "\n Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`.\n " ]
Please provide a description of the function:def read_wave(path): with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width == 2 sample_rate = wf.getframerate() ...
[ "Reads a .wav file.\n\n Takes the path, and returns (PCM audio data, sample rate).\n " ]
Please provide a description of the function:def write_wave(path, audio, sample_rate): with contextlib.closing(wave.open(path, 'wb')) as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(sample_rate) wf.writeframes(audio)
[ "Writes a .wav file.\n\n Takes path, PCM audio data, and sample rate.\n " ]
Please provide a description of the function:def frame_generator(frame_duration_ms, audio, sample_rate): n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) offset = 0 timestamp = 0.0 duration = (float(n) / sample_rate) / 2.0 while offset + n < len(audio): yield Frame(audio[offset:o...
[ "Generates audio frames from PCM audio data.\n\n Takes the desired frame duration in milliseconds, the PCM data, and\n the sample rate.\n\n Yields Frames of the requested duration.\n " ]
Please provide a description of the function:def run(self): ''' Initialise the runner function with the passed args, kwargs ''' # Retrieve args/kwargs here; and fire up the processing using them try: transcript = self.fn(*self.args, **self.kwargs) except: ...
[]
Please provide a description of the function:def exec_command(command, cwd=None): r''' Helper to exec locally (subprocess) or remotely (paramiko) ''' rc = None stdout = stderr = None if ssh_conn is None: ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.get('LD_LIBRARY_PATH', ''...
[]
Please provide a description of the function:def get_arch_string(): r''' Check local or remote system arch, to produce TaskCluster proper link. ''' rc, stdout, stderr = exec_command('uname -sm') if rc > 0: raise AssertionError('Error checking OS') stdout = stdout.lower().strip() if ...
[]
Please provide a description of the function:def extract_native_client_tarball(dir): r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir. ''' assert_valid_dir(dir) target_tarball = os.path.join(dir, 'native_client.tar.xz') if os.path.isfile(target_tarball) and os.st...
[]
Please provide a description of the function:def is_zip_file(models): r''' Ensure that a path is a zip file by: - checking length is 1 - checking extension is '.zip' ''' ext = os.path.splitext(models[0])[1] return (len(models) == 1) and (ext == '.zip')
[]
Please provide a description of the function:def maybe_inspect_zip(models): r''' Detect if models is a list of protocolbuffer files or a ZIP file. If the latter, then unzip it and return the list of protocolbuffer files that were inside. ''' if not(is_zip_file(models)): return models ...
[]
Please provide a description of the function:def all_files(models=[]): r''' Return a list of full path of files matching 'models', sorted in human numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000). Files are supposed to be named identically except one variable component e.g. the list...
[]
Please provide a description of the function:def setup_tempdir(dir, models, wav, alphabet, lm_binary, trie, binaries): r''' Copy models, libs and binary to a directory (new one if dir is None) ''' if dir is None: dir = tempfile.mkdtemp(suffix='dsbench') sorted_models = all_files(models=mode...
[]
Please provide a description of the function:def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
[]
Please provide a description of the function:def get_sshconfig(): r''' Read user's SSH configuration file ''' with open(os.path.expanduser('~/.ssh/config')) as f: cfg = paramiko.SSHConfig() cfg.parse(f) ret_dict = {} for d in cfg._config: _copy = dict(d) ...
[]
Please provide a description of the function:def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True): r''' Establish a SSH connection to a remote host. It should be able to use SSH's config file Host name declarations. By default, will not automatically add trust for hosts, wi...
[]
Please provide a description of the function:def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-1): r''' Core of the running of the benchmarks. We will run on all of models, against the WAV file provided as wav, and the provided alphabet. ''' assert_valid_dir(dir) ...
[]
Please provide a description of the function:def produce_csv(input, output): r''' Take an input dictionnary and write it to the object-file output. ''' output.write('"model","mean","std"\n') for model_data in input: output.write('"%s",%f,%f\n' % (model_data['name'], model_data['mean'], model...
[]
Please provide a description of the function:def to_sparse_tuple(sequence): r indices = np.asarray(list(zip([0]*len(sequence), range(len(sequence)))), dtype=np.int64) shape = np.asarray([1, len(sequence)], dtype=np.int64) return indices, sequence, shape
[ "Creates a sparse representention of ``sequence``.\n Returns a tuple with (indices, values, shape)\n " ]
Please provide a description of the function:def _parallel_downloader(voxforge_url, archive_dir, total, counter): def download(d): (i, file) = d download_url = voxforge_url + '/' + file c = counter.increment() print('Downloading file {} ({}/{})...'.format(i+1, c, total)...
[ "Generate a function to download a file based on given parameters\n This works by currying the above given arguments into a closure\n in the form of the following function.\n\n :param voxforge_url: the base voxforge URL\n :param archive_dir: the location to store the downloaded file\n :param total: ...
Please provide a description of the function:def _parallel_extracter(data_dir, number_of_test, number_of_dev, total, counter): def extract(d): (i, archive) = d if i < number_of_test: dataset_dir = path.join(data_dir, "test") elif i<number_of_test+number_of_dev: ...
[ "Generate a function to extract a tar file based on given parameters\n This works by currying the above given arguments into a closure\n in the form of the following function.\n\n :param data_dir: the target directory to extract into\n :param number_of_test: the number of files to keep as the test...
Please provide a description of the function:def increment(self, amount=1): self.__lock.acquire() self.__count += amount v = self.value() self.__lock.release() return v
[ "Increments the counter by the given amount\n :param amount: the amount to increment by (default 1)\n :return: the incremented value of the counter\n " ]
Please provide a description of the function:def calculate_report(labels, decodings, distances, losses): r''' This routine will calculate a WER report. It'll compute the `mean` WER and create ``Sample`` objects of the ``report_count`` top lowest loss items from the provided WER results tuple (only items...
[]
Please provide a description of the function:def sparse_tensor_value_to_texts(value, alphabet): r return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)
[ "\n Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings\n representing its values, converting tokens to strings using ``alphabet``.\n " ]
Please provide a description of the function:def parse_args(args): parser = argparse.ArgumentParser( description="Imports GramVaani data for Deep Speech" ) parser.add_argument( "--version", action="version", version="GramVaaniImporter {ver}".format(ver=__version__), ...
[ "Parse command line parameters\n Args:\n args ([str]): Command line parameters as list of strings\n Returns:\n :obj:`argparse.Namespace`: command line parameters namespace\n " ]
Please provide a description of the function:def setup_logging(level): format = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" logging.basicConfig( level=level, stream=sys.stdout, format=format, datefmt="%Y-%m-%d %H:%M:%S" )
[ "Setup basic logging\n Args:\n level (int): minimum log level for emitting messages\n " ]
Please provide a description of the function:def main(args): args = parse_args(args) setup_logging(args.loglevel) _logger.info("Starting GramVaani importer...") _logger.info("Starting loading GramVaani csv...") csv = GramVaaniCSV(args.csv_filename) _logger.info("Starting downloading GramVaa...
[ "Main entry point allowing external calls\n Args:\n args ([str]): command line parameter list\n " ]
Please provide a description of the function:def download(self): mp3_directory = self._pre_download() self.data.swifter.apply(func=lambda arg: self._download(*arg, mp3_directory), axis=1, raw=True) return mp3_directory
[ "Downloads the data associated with this instance\n Return:\n mp3_directory (os.path): The directory into which the associated mp3's were downloaded\n " ]
Please provide a description of the function:def convert(self): wav_directory = self._pre_convert() for mp3_filename in self.mp3_directory.glob('**/*.mp3'): wav_filename = path.join(wav_directory, os.path.splitext(os.path.basename(mp3_filename))[0] + ".wav") if not path....
[ "Converts the mp3's associated with this instance to wav's\n Return:\n wav_directory (os.path): The directory into which the associated wav's were downloaded\n " ]
Please provide a description of the function:def text_to_char_array(original, alphabet): r return np.asarray([alphabet.label_from_string(c) for c in original])
[ "\n Given a Python string ``original``, remove unsupported characters, map characters\n to integers and return a numpy array representing the processed string.\n " ]
Please provide a description of the function:def wer_cer_batch(originals, results): r # The WER is calculated on word (and NOT on character) level. # Therefore we split the strings into words first assert len(originals) == len(results) total_cer = 0.0 total_char_length = 0.0 total_wer = 0....
[ "\n The WER is defined as the editing/Levenshtein distance on word level\n divided by the amount of words in the original text.\n In case of the original having more words (N) than the result and both\n being totally different (all N words resulting in 1 edit operation each),\n the WER will always be...
Please provide a description of the function:def variable_on_cpu(name, shape, initializer): r # Use the /cpu:0 device for scoped operations with tf.device(Config.cpu_device): # Create or get apropos variable var = tf.get_variable(name=name, shape=shape, initializer=initializer) return va...
[ "\n Next we concern ourselves with graph creation.\n However, before we do so we must introduce a utility function ``variable_on_cpu()``\n used to create a variable in CPU memory.\n " ]
Please provide a description of the function:def calculate_mean_edit_distance_and_loss(iterator, dropout, reuse): r''' This routine beam search decodes a mini-batch and calculates the loss and mean edit distance. Next to total and average loss it returns the mean edit distance, the decoded result and th...
[]
Please provide a description of the function:def get_tower_results(iterator, optimizer, dropout_rates): r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers. ''' ...
[]
Please provide a description of the function:def average_gradients(tower_gradients): r''' A routine for computing each variable's average of the gradients obtained from the GPUs. Note also that this code acts as a synchronization point as it requires all GPUs to be finished with their mini-batch before ...
[]
Please provide a description of the function:def log_variable(variable, gradient=None): r''' We introduce a function for logging a tensor variable's current state. It logs scalar values for the mean, standard deviation, minimum and maximum. Furthermore it logs a histogram of its state and (if given) of ...
[]
Please provide a description of the function:def export(): r''' Restores the trained variables into a simpler graph that will be exported for serving. ''' log_info('Exporting the model...') from tensorflow.python.framework.ops import Tensor, Operation inputs, outputs, _ = create_inference_graph...
[]
Please provide a description of the function:def ctc_beam_search_decoder(probs_seq, alphabet, beam_size, cutoff_prob=1.0, cutoff_top_n=40, scorer=None): beam_results = swi...
[ "Wrapper for the CTC Beam Search Decoder.\n\n :param probs_seq: 2-D list of probability distributions over each time\n step, with each element being a list of normalized\n probabilities over alphabet and blank.\n :type probs_seq: 2-D list\n :param alphabet: alphabe...
Please provide a description of the function:def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob...
[ "Wrapper for the batched CTC beam search decoder.\n\n :param probs_seq: 3-D list with each element as an instance of 2-D list\n of probabilities used by ctc_beam_search_decoder().\n :type probs_seq: 3-D list\n :param alphabet: alphabet list.\n :alphabet: Alphabet\n :param beam_si...
Please provide a description of the function:def resample(self, data, input_rate): data16 = np.fromstring(string=data, dtype=np.int16) resample_size = int(len(data16) / self.input_rate * self.RATE_PROCESS) resample = signal.resample(data16, resample_size) resample16 = np.array(r...
[ "\n Microphone may not support our native processing sampling rate, so\n resample from input_rate to RATE_PROCESS here for webrtcvad and\n deepspeech\n\n Args:\n data (binary): Input audio stream\n input_rate (int): Input audio rate to resample from\n " ]
Please provide a description of the function:def read_resampled(self): return self.resample(data=self.buffer_queue.get(), input_rate=self.input_rate)
[ "Return a block of audio data resampled to 16000hz, blocking if necessary." ]
Please provide a description of the function:def frame_generator(self): if self.input_rate == self.RATE_PROCESS: while True: yield self.read() else: while True: yield self.read_resampled()
[ "Generator that yields all audio frames from microphone." ]
Please provide a description of the function:def vad_collector(self, padding_ms=300, ratio=0.75, frames=None): if frames is None: frames = self.frame_generator() num_padding_frames = padding_ms // self.frame_duration_ms ring_buffer = collections.deque(maxlen=num_padding_frames) ...
[ "Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None.\n Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being triggered.\n Example: (frame, ..., frame, None, frame, ...,...
Please provide a description of the function:def cut(sentence, HMM=True): global dt if jieba.pool is None: for w in dt.cut(sentence, HMM=HMM): yield w else: parts = strdecode(sentence).splitlines(True) if HMM: result = jieba.pool.map(_lcut_internal, parts...
[ "\n Global `cut` function that supports parallel processing.\n\n Note that this only works using dt, custom POSTokenizer\n instances are not supported.\n " ]
Please provide a description of the function:def enable_parallel(processnum=None): global pool, dt, cut, cut_for_search from multiprocessing import cpu_count if os.name == 'nt': raise NotImplementedError( "jieba: parallel mode only supports posix system") else: from mult...
[ "\n Change the module's `cut` and `cut_for_search` functions to the\n parallel version.\n\n Note that this only works using dt, custom Tokenizer\n instances are not supported.\n " ]
Please provide a description of the function:def cut(self, sentence, cut_all=False, HMM=True): ''' The main function that segments an entire sentence that contains Chinese characters into separated words. Parameter: - sentence: The str(unicode) to be segmented. -...
[]
Please provide a description of the function:def cut_for_search(self, sentence, HMM=True): words = self.cut(sentence, HMM=HMM) for w in words: if len(w) > 2: for i in xrange(len(w) - 1): gram2 = w[i:i + 2] if self.FREQ.get(gram...
[ "\n Finer segmentation for search engines.\n " ]
Please provide a description of the function:def load_userdict(self, f): ''' Load personalized dict to improve detect rate. Parameter: - f : A plain text file contains words and their ocurrences. Can be a file-like object, or the path of the dictionary file, ...
[]
Please provide a description of the function:def add_word(self, word, freq=None, tag=None): self.check_initialized() word = strdecode(word) freq = int(freq) if freq is not None else self.suggest_freq(word, False) self.FREQ[word] = freq self.total += freq if tag: ...
[ "\n Add a word to dictionary.\n\n freq and tag can be omitted, freq defaults to be a calculated value\n that ensures the word can be cut out.\n " ]
Please provide a description of the function:def suggest_freq(self, segment, tune=False): self.check_initialized() ftotal = float(self.total) freq = 1 if isinstance(segment, string_types): word = segment for seg in self.cut(word, HMM=False): ...
[ "\n Suggest word frequency to force the characters in a word to be\n joined or splitted.\n\n Parameter:\n - segment : The segments that the word is expected to be cut into,\n If the word should be treated as a whole, use a str.\n - tune : If True, tu...
Please provide a description of the function:def tokenize(self, unicode_sentence, mode="default", HMM=True): if not isinstance(unicode_sentence, text_type): raise ValueError("jieba: the input parameter should be unicode.") start = 0 if mode == 'default': for w in...
[ "\n Tokenize a sentence and yields tuples of (word, start, end)\n\n Parameter:\n - sentence: the str(unicode) to be segmented.\n - mode: \"default\" or \"search\", \"search\" is for finer segmentation.\n - HMM: whether to use the Hidden Markov Model.\n " ]
Please provide a description of the function:def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): self.pos_filt = frozenset(allowPOS) g = UndirectWeightedGraph() cm = defaultdict(int) words = tuple(self.tokenizer.cut(sentence)...
[ "\n Extract keywords from sentence using TextRank algorithm.\n Parameter:\n - topK: return how many top keywords. `None` for all possible words.\n - withWeight: if True, return a list of (word, weight);\n if False, return a list of words.\n - a...
Please provide a description of the function:def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False): if allowPOS: allowPOS = frozenset(allowPOS) words = self.postokenizer.cut(sentence) else: words = self.tokenizer.cut(sentenc...
[ "\n Extract keywords from sentence using TF-IDF algorithm.\n Parameter:\n - topK: return how many top keywords. `None` for all possible words.\n - withWeight: if True, return a list of (word, weight);\n if False, return a list of words.\n - all...
Please provide a description of the function:def paracrawl_v3_pairs(paracrawl_file): raw_sentences = _raw_sentences(paracrawl_file) for s_en in raw_sentences: try: s_xx = next(raw_sentences) if s_en and s_xx: # Prevent empty string examples. yield s_en, s_xx except StopIteration: ...
[ "Generates raw (English, other) pairs from a ParaCrawl V3.0 data file.\n\n Args:\n paracrawl_file: A ParaCrawl V3.0 en-.. data file.\n Yields:\n Pairs of (sentence_en, sentence_xx), as Unicode strings.\n Raises:\n StopIteration: If the file ends while this method is in the middle of\n creating a ...
Please provide a description of the function:def _raw_sentences(paracrawl_file): for line_utf8 in paracrawl_file: line_uni = line_utf8.decode('UTF-8') text_match = re.match(r' +<seg>(.*)</seg>$', line_uni) if text_match: txt = text_match.group(1) txt = re.sub(r'&amp;', r'&', txt) txt ...
[ "Generates Unicode strings, one for each <seg> in a ParaCrawl data file.\n\n Also decodes some of the most common HTML entities found in ParaCrawl data.\n\n Args:\n paracrawl_file: A ParaCrawl V3.0 en-.. data file.\n Yields:\n One Unicode string for each <seg> element in the ParaCrawl data file.\n " ]
Please provide a description of the function:def clean_en_xx_pairs(en_xx_pairs): for s1, s2 in en_xx_pairs: if _regex_filter(s1): continue s1_list, s2_list = _split_sentences(s1, s2) if len(s1_list) != len(s2_list): continue # discard this pair elif len(s1_list) == 1: yield s1, s...
[ "Generates a cleaned-up stream of (English, other) translation pairs.\n\n Cleaning includes both filtering and simplistic sentence splitting, with\n minimal assumptions on the non-English pair member: (1) All filtering is\n done based on the English member of the pair, and (2) sentence splitting\n assumes only ...
Please provide a description of the function:def _get_case_file_paths(tmp_dir, case, training_fraction=0.95): paths = tf.gfile.Glob("%s/*.jpg" % tmp_dir) if not paths: raise ValueError("Search of tmp_dir (%s) " % tmp_dir, "for subimage paths yielded an empty list, ", ...
[ "Obtain a list of image paths corresponding to training or eval case.\n\n Args:\n tmp_dir: str, the root path to which raw images were written, at the\n top level having meta/ and raw/ subdirs.\n case: bool, whether obtaining file paths for training (true) or eval\n (false).\n training_fraction:...